query
stringlengths
9
9.05k
document
stringlengths
10
222k
metadata
dict
negatives
sequencelengths
30
30
negative_scores
sequencelengths
30
30
document_score
stringlengths
4
10
document_rank
stringclasses
2 values
Take the weather_df and returns a dataframe with the station name and numeric weather Input parameters
def clean_weather_df(weather_df): col = weather_df.columns drop_col = list(col[7::2]) clean_num = weather_df[weather_df['LATITUDE'].str.contains( "LATITUDE") == False] num_weather = clean_num.drop(drop_col, axis=1) just_num = num_weather.drop(['NAME', 'STATION'], axis=1) all_weatherdf = just_num.apply(pd.to_numeric) all_weatherdf['name'] = num_weather['NAME'] return all_weatherdf
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def station_stats(df):", "def url_to_df(url, station_name, dictionary):\n \n path_to_data = os.path.join(et.data.get_data(url=url))\n \n dataframe = pd.read_csv(path_to_data)\n \n dataframe['Station ID'] = station_name\n \n output_dataframe = dataframe[['Station ID', 'year', 'month', 'day', 'doy',\n 'sm_5cm', 'sm_10cm', 'sm_20cm', 'sm_50cm', 'sm_100cm']]\n \n output_dataframe['month'].replace({1: \"Jan\", 2: \"Feb\", 3: \"Mar\", \n 4: \"Apr\", 5: \"May\", 6: \"Jun\", \n 7: \"Jul\", 8: \"Aug\", 9: \"Sep\", \n 10: \"Oct\", 11: \"Nov\", 12: \"Dec\"}, \n inplace=True)\n \n cut_labels = ['decad0', 'decad1', 'decad2']\n cut_bins = [0, 10, 20, 31]\n output_dataframe['decad'] = pd.cut(output_dataframe['day'], bins=cut_bins, labels=cut_labels)\n \n cut_labels = ['pentad0', 'pentad1', 'pentad2', 'pentad3', 'pentad4', 'pentad5']\n cut_bins = [0, 5, 10, 15, 20, 25, 31]\n output_dataframe['pentad'] = pd.cut(output_dataframe['day'], bins=cut_bins, labels=cut_labels)\n \n dictionary.update({station_name: output_dataframe})", "def parse_station(station):\n if not station:\n return pd.DataFrame()\n header = get_header(station[0])\n header['ftime'] = get_fntime(station[1], station[2], header) \n df = get_rows(header, station)\n return df", "def get_weather_data():\n keys = ['1364038.csv',\n '1364041.csv',\n '1364042.csv',\n '1364043.csv',\n '1364044.csv',\n '1364046.csv',\n '1364047.csv',\n '1364048.csv',\n '1364051.csv',\n '1364052.csv',\n '1364053.csv',\n '1364054.csv',\n '1364055.csv',\n '1364058.csv',\n '1364059.csv',\n '1364060.csv',\n '1364061.csv',\n '1364062.csv',\n '1364063.csv',\n '1364064.csv',\n '1364066.csv']\n df_weather = import_weather(keys)\n df_weather_dist = df_weather[[\n 'LATITUDE', 'LONGITUDE', 'name']].drop_duplicates().reset_index()\n return df_weather, df_weather_dist", "def filter(df: pd.DataFrame = pd.DataFrame()):\n if df.empty:\n df = read()\n print('Filtering data...')\n df = df.dropna()\n df2 = pd.DataFrame()\n df2['Longitude'] = df['Longitude']\n df2['Latitude'] = df['Latitude']\n df2['Month'] = df['Date'].dt.strftime('%m').astype(int)\n df2['Day'] = df['Date'].dt.strftime('%d').astype(int)\n df2['Day_of_Week'] = df['Day_of_Week']\n df2['Time'] = np.array([t.timestamp() for t in df['Time']]) - df['Time'].min().timestamp()\n df2['Weather_Conditions'] = df['Weather_Conditions']\n return pd.get_dummies(df2)", "def correct_weather_data(df):\n\n columns = {'Date UTC': 'date',\n 'T° (C)': 'temperature',\n 'P (hPa)': 'pression',\n 'HR (%)': 'HR',\n 'P.rosée (°C)': 'rosee',\n 'Visi (km)': 'visibilite',\n 'Vt. moy. (km/h)': 'v_moy',\n 'Vt. raf. (km/h)': 'v_raf',\n 'Vt. dir (°)': 'v_dir',\n 'RR 3h (mm)': 'RR3h',\n 'Neige (cm)': 'neige',\n 'Nebul. (octats)': 'nebul'}\n\n df = df.rename(columns=columns)\n df['date'] = df['date'].str.replace('h', ':')\n df['date'] = pd.to_datetime(df['date'], dayfirst=True)\n\n return df", "def get_weather_data(weather_station):\n now = datetime.datetime.now()\n then = now - datetime.timedelta(days=7)\n\n query_date_start = (\"%d%02d%02d\" % (then.year, then.month, then.day))\n query_date_end = (\"%d%02d%02d\" % (now.year, now.month, now.day))\n\n api_key = '/api/%s' % WUNDERGROUND_KEY\n history_key = '/history_%s%s/lang:EN/units:english/bestfct:1/v:2.0' % (query_date_start, query_date_end)\n query = '/q/%s.json?showObs=0&ttl=120' % weather_station\n\n weather_url = (\"%s%s%s%s\" % (WUNDERGROUND_HOST, api_key, history_key, query))\n\n logger.info('Weather URL: %s', weather_url)\n response = requests.get(weather_url).text\n\n max_temp_avg = json.loads(response)['history']['summary']['max_temperature_avg']\n sum_precip = json.loads(response)['history']['summary']['precip_sum']\n\n return max_temp_avg, sum_precip", "def get_weather_data(lat='40.761440',lng='-73.981806'):\r\n key ='********************************'\r\n x = pd.DataFrame()\r\n unix_now = int((dt.datetime.now()- dt.datetime(1970,1,1)).total_seconds())\r\n for time in range(unix_now-86400, unix_now+604800, 86400):\r\n rsp = rq.get('https://api.darksky.net/forecast/{}/{},{},{}'.format(key, lat, lng, time))\r\n rsp_json = json.loads(rsp.text)\r\n row = json_normalize(rsp_json[\"daily\"]['data'])\r\n x = x.append(row)\r\n \r\n x = x[['icon','apparentTemperatureHigh','apparentTemperatureLow','cloudCover','humidity','precipProbability',\r\n 'pressure','visibility','windBearing','windGust','windSpeed']].reset_index(drop=True)\r\n return x", "def get_station_parameters2(stn_df, st_dt, end_dt, engine): \n # Get stn IDs\n assert len(stn_df) > 0, 'ERROR: Please select at least one station.'\n stn_df['station_id'].drop_duplicates(inplace=True)\n stn_ids = stn_df['station_id'].values.astype(int).tolist()\n\n # Convert dates\n st_dt = dt.datetime.strptime(st_dt, '%Y-%m-%d')\n end_dt = dt.datetime.strptime(end_dt, '%Y-%m-%d')\n \n # Query db\n bind_pars = ','.join(':%d' % i for i in range(len(stn_ids))) \n\n bind_pars = ','.join(':%d' % i for i in range(len(stn_ids)))\n sql = (\"SELECT DISTINCT parameter_id, \"\n \" name AS parameter_name, \"\n \" unit \"\n \"FROM nivadatabase.wcv_calk \"\n \"WHERE station_id IN (%s) \"\n \"AND sample_date >= :st_dt \"\n \"AND sample_date <= :end_dt \" \n \"ORDER BY name, \"\n \" unit\" % bind_pars)\n\n par_dict = {'end_dt':end_dt,\n 'st_dt':st_dt}\n bind_dict = {'%d' % idx:item for idx, item in enumerate(stn_ids)}\n par_dict.update(bind_dict) \n df = pd.read_sql(sql, params=par_dict, con=engine) \n \n return df", "def read_weather_data():\n # Check if UTC to gmt+1 conversion is being handled correctly\n weather = pd.read_csv('//datc//opschaler//weather_data//knmi_10_min_raw_data//output//df_combined_uncleaned.csv',\n delimiter='\\t', comment='#',\n parse_dates=['datetime'])\n weather = weather.set_index(['datetime'])\n return weather", "def load_data(fpath: str, station: Dict[str, Any]) -> pd.DataFrame:\n df = pd.read_csv(\n fpath,\n skiprows=station['header_line_num']-1,\n usecols=['date', 'rain'],\n )\n\n # format the date from a string to a proper datetime object\n df['date'] = pd.to_datetime(df['date'])\n\n # extract year, month, week, and day to separate columns\n df['year'] = df['date'].dt.year\n df['month'] = df['date'].dt.month\n df['day'] = df['date'].dt.dayofyear\n df['week'] = df['date'].dt.weekofyear\n df['year_month'] = df['date'].dt.to_period('M')\n\n return df", "def get_weather(latitude: float, longitude: float, year: int) -> DataFrame:\n # Set time period\n start = datetime(year, 1, 1)\n end = datetime(year, 12, 31)\n\n # Create Point for NYC\n location = Point(latitude, longitude)\n\n # Get daily data for the year\n data = Daily(location, start, end)\n return data.fetch()", "def streaming_weather_data(**kwargs):\n df = weather_data(['San Francisco'])\n df['time'] = [pd.Timestamp.now()]\n return df.set_index('time')", "def Wind_Prediction():\n model = pickle.load(open('wind_model.pkl','rb'))\n \n # Load DataFrame\n # Wind\n longitude = 53.556563\n latitude = 8.598084\n\n url = ('https://api.openweathermap.org/data/2.5/onecall?lat=8.598084&lon=53.556563&units=imperial&appid=43e49f2fb4d17b806dfff389f21f4d27')\n response = requests.get(url)\n\n weather = response.json()\n dailynorm = json_normalize(weather, 'daily')\n \n df = pd.DataFrame(dailynorm)\n wind_df = df[['dt', 'wind_speed', 'wind_deg']].copy()\n wind_df['date'] = pd.to_datetime(wind_df['dt'],unit='s')\n wind_df['day'] = wind_df['date'].dt.day\n wind_df['month'] = wind_df['date'].dt.month\n wind_df = wind_df.fillna(0)\n wind_df.rename(columns={'wind_speed':'wind speed', 'wind_deg':'direction'}, inplace=True)\n wind_df = wind_df.drop(['dt','date'], axis = 1)\n Xnew = wind_df.values\n p_pred = model.predict(Xnew)\n p_pred = pd.DataFrame(p_pred)\n p_pred.columns = ['Predicted Power']\n final_wind_df = pd.concat([wind_df, p_pred], axis = 1)\n dictionaryObject = final_wind_df.to_dict()\n \n return dictionaryObject", "def get_weather_timeseries_2017():\n weather_df = pd.read_csv(\"src/kumpula-weather-2017.csv\")\n\n # -1 value in columns \"Precipitation amount (mm)\" and \"Snow depth (cm)\" mean\n # that there was no absolutely no rain or snow that day, whereas 0 can mean\n # a little of either. Let's convert the -1 values to 0 to make the dataset\n # more logical to read.\n weather_df.loc[weather_df[\"Precipitation amount (mm)\"] == -1,\n \"Precipitation amount (mm)\"] = 0\n weather_df.loc[weather_df[\"Snow depth (cm)\"] == -1, \"Snow depth (cm)\"] = 0\n\n # Create datetime index\n weather_df[\"Month\"] = weather_df[\"m\"]\n weather_df[\"Day\"] = weather_df[\"d\"]\n weather_df[\"Date\"] = pd.to_datetime(weather_df[[\"Year\", \"Month\", \"Day\"]])\n\n # Reindex dataset\n weather_df = weather_df.set_index(\"Date\")\n\n # Drop redundant columns\n weather_df.drop([\"Time\", \"Time zone\", \"m\", \"d\", \"Year\",\n \"Month\", \"Day\"], axis=\"columns\", inplace=True)\n\n return weather_df", "def get_rows(header, station):\n df = pd.DataFrame(header, columns=list(header.keys()) + all_cols)\n for row in station[3:]:\n #cranky parsing issues\n var, vals = parse_row(row)\n # data type\n \n if var in categorical:\n #try:\n df[var] = np.array(vals, dtype='object')\n\n elif var in integer: # cast to int\n if (var == 'N/X'):\n df['X/N'] = np.array(vals, dtype='float64')\n else:\n #try:\n df[var] = np.array(vals, dtype='object')\n\n else:\n raise KeyError(f\"{var} parsing not supported\")\n \n return df", "def weather_data(cities, openweathermap_api_key=openweathermap_api_key):\n L = []\n for c in cities:\n res = requests.get(f'http://api.openweathermap.org/data/2.5/weather?q={c}&appid={openweathermap_api_key}&units=imperial')\n L.append(res.json())\n\n df = pd.DataFrame(L)\n df['lon'] = df['coord'].map(op.itemgetter('lon'))\n df['lat'] = df['coord'].map(op.itemgetter('lat'))\n df['Temprature'] = df['main'].map(op.itemgetter('temp'))\n df['Humidity'] = df['main'].map(op.itemgetter('humidity'))\n df['Wind Speed'] = df['wind'].map(op.itemgetter('speed'))\n return df[['name','lon', 'lat','Temprature','Humidity','Wind Speed']]", "def forecast_weather(self):\n pass", "def data_frame(dict_cycle, number):\n list1, list2 = (list(dict_cycle.get('cycle_'+str(number)).items()))\n zipped_list = list(zip(list1[1], list2[1]))\n data = pd.DataFrame(zipped_list, columns=['Potential', 'Current'])\n return data", "def prepare_for_influxdb(df):\n df = df.drop(columns=\"landkreis\", errors=\"ignore\") # prevent name collision in get_ags()\n df = get_ags(df)\n df[\"time\"] = df.apply(lambda x: 1000000000*int(datetime.timestamp((pd.to_datetime(x[\"timestamp\"])))), 1)\n df[\"measurement\"] = \"hystreet\"\n df[\"origin\"] = \"https://hystreet.com\"\n df = df.rename(columns={\n 'station_id': '_id',\n 'pedestrians_count': 'pedestrian_count',\n 'state': 'bundesland'\n })\n df['ags'] = pd.to_numeric(df['ags'])\n # import pdb; pdb.set_trace()\n return df", "def get_all_stations(engine): \n # Query db\n sql = (\"SELECT DISTINCT a.station_id, \"\n \" a.station_code, \"\n \" a.station_name, \"\n \" c.station_type, \"\n \" d.latitude, \"\n \" d.longitude \"\n \"FROM nivadatabase.projects_stations a, \"\n \" nivadatabase.stations b, \"\n \" nivadatabase.station_types c, \"\n \" niva_geometry.sample_points d \"\n \"WHERE a.station_id = b.station_id \"\n \"AND b.station_type_id = c.station_type_id \"\n \"AND b.geom_ref_id = d.sample_point_id \"\n \"ORDER BY a.station_id\")\n df = pd.read_sql(sql, engine)\n\n return df", "def get_closest_station(df_hike, df_weather):\n closest_station = []\n station_distance = []\n for hike_idx in df_hike.index:\n hike_long = df_hike.loc[hike_idx, 'long']\n hike_lat = df_hike.loc[hike_idx, 'lat']\n distances = []\n for stat_idx in df_weather.index:\n stat_long = df_weather.loc[stat_idx, 'LONGITUDE']\n stat_lat = df_weather.loc[stat_idx, 'LATITUDE']\n distance = get_hike_distance(\n hike_lat, hike_long, stat_lat, stat_long)\n distances.append(distance)\n shortest_idx = np.argmax(distances)\n distance = max(distances)\n station = df_weather.loc[int(shortest_idx), 'name']\n closest_station.append(station)\n station_distance.append(distance)\n df_hike['closet_station'] = closest_station\n df_hike['station_distance'] = station_distance", "def Solar_Prediction():\n model = pickle.load(open('solar_model.pkl','rb'))\n \n # Load DataFrame\n # Solar\n longitude = 142.110216\n latitude = -19.461907\n\n url = ('https://api.openweathermap.org/data/2.5/onecall?lat=-19.461907&lon=142.110216&units=imperial&appid=43e49f2fb4d17b806dfff389f21f4d27')\n response = requests.get(url)\n\n weather = response.json()\n dailynorm = json_normalize(weather, 'daily')\n \n df = pd.DataFrame(dailynorm)\n solar_df = df[['dt', 'temp.min', 'temp.max', 'clouds']].copy()\n solar_df['date'] = pd.to_datetime(solar_df['dt'],unit='s')\n solar_df['day'] = solar_df['date'].dt.day\n solar_df['month'] = solar_df['date'].dt.month\n solar_df = solar_df.fillna(0)\n solar_df.rename(columns={'temp.min':'Temp Low',\n 'temp.max':'Temp Hi',\n 'clouds':'Cloud Cover Percentage'}, \n inplace=True)\n solar_df = solar_df.drop(['dt','date'], axis = 1)\n Xnew = solar_df.values\n p_predi = model.predict(Xnew)\n p_pred = pd.DataFrame(p_predi)\n p_pred.columns = ['Predicted Power']\n final_solar_df = pd.concat([solar_df, p_pred], axis = 1)\n dictionaryObject = final_solar_df.to_dict()\n \n return dictionaryObject", "def get_station_stats(self):\n try:\n names, status, places, power = zip(*[(p.name, p.status,\n p.available_places, p.power)\n for p in self.station_agents.values()])\n except ValueError:\n names, status, places, power = [], [], [], []\n\n df = pd.DataFrame.from_dict({\"name\": names, \"status\": status, \"available_places\": places, \"power\": power})\n return df", "def temperatures():\n\n return station_9281", "def gatherStationData():\n flist = list_files()\n station_dics = {}\n print(\"Reading in csv data...\")\n for f_in in flist:\n start,end = find_timespan(f_in)\n station = station_name(f=f_in)\n print(\"File: {0} Station: {1} {2}--{3}\".format(f_in, \n station, start, end))\n station_dics[station] = read_precip(fname=f_in, \n label=station, start_year=start, end_year=end)\n data_list = []\n for s in station_dics:\n data_list.append(station_dics[s]) \n return pd.concat(data_list,axis=1)", "def clean_weather_csv(df: pd.DataFrame) -> pd.DataFrame:\n if 'Min_VisibilitykM' in df.columns:\n df.rename(columns={'Min_VisibilitykM': 'Min_VisibilityKm'},\n inplace=True)\n if 'Min_DewpointC' in df.columns:\n df.rename(columns={'Min_DewpointC': 'MinDew_pointC'}, inplace=True)\n\n cols = map(convert_to_snake_case, df.columns)\n df.columns = cols\n\n for col in ['max_visibility_km', 'min_visibility_km', 'mean_visibility_km',\n 'max_gust_speed_km_h', 'cloud_cover']:\n df[col] = df[col].fillna(df[col].mean())\n\n df['events'] = df.events.fillna('No Events')\n return df", "def get_stock_price_df(info, symbols):\n\n df_l = []\n\n for num, i in enumerate(info):\n df = pd.DataFrame.from_dict(i, orient='index')\n df['Symbol'] = symbols[num]\n df_l.append(df)\n\n df_full = pd.concat(df_l)\n df_full = df_full.rename(columns={'1. open': 'Open',\n '2. high': 'High',\n '3. low': 'Low',\n '4. close': 'Close',\n '5. volume': 'Volume'})\n\n return df_full", "def _obtain_data(self):\n (self.data_df, self.column_df, self.station_name, self.log_file, self.station_lat, self.station_lon,\n self.station_elev, self.ws_anemometer_height, self.missing_fill_value, self.script_mode,\n self.auto_mode, self.fill_mode, self.metadata_mode, self.generate_bokeh, self.metadata_df,\n metadata_series) = input_functions.obtain_data(self.config_path, self.metadata_path)\n\n if self.script_mode == 1: # correcting data\n self.mc_iterations = 1000 # Number of iters for MC simulation of thornton running solar radiation gen\n else:\n self.mc_iterations = 50 # if we're not correcting data then only do a few iterations to save time\n\n print(\"\\nSystem: Raw data successfully extracted from station file.\")\n\n # Extract individual variables from data frame back into to numpy arrays.\n self.data_year = np.array(self.data_df.year)\n self.data_month = np.array(self.data_df.month)\n self.data_day = np.array(self.data_df.day)\n self.data_tavg = np.array(self.data_df.tavg)\n self.data_tmax = np.array(self.data_df.tmax)\n self.data_tmin = np.array(self.data_df.tmin)\n self.data_tdew = np.array(self.data_df.tdew)\n self.data_ea = np.array(self.data_df.ea)\n self.data_rhavg = np.array(self.data_df.rhavg)\n self.data_rhmax = np.array(self.data_df.rhmax)\n self.data_rhmin = np.array(self.data_df.rhmin)\n self.data_rs = np.array(self.data_df.rs)\n self.data_ws = np.array(self.data_df.ws)\n self.data_precip = np.array(self.data_df.precip)\n\n self.output_file_path = \"correction_files/\" + self.station_name + \"_output\" + \".xlsx\"", "def generate_weather_data(self):\n months = pd.to_datetime(self.output['Local Time']).dt.month\n self.output['Month'] = months # set month values for later joins\n\n # merge output data frame with historical data to get ranges\n keys = ['Location', 'Month']\n m = pd.merge(self.output, self.histdata, how='left',\n left_on=keys, right_on=keys)\n\n # uniformly select random pressure, temperature\n # and humidity values between the historical max and min ranges\n r = np.random.rand(m.shape[0])\n m['Temperature'] = ((m['Tmean_high'] - m['Tmean_low']\n ) * r + m['Tmean_low']).round(1)\n m['Pressure'] = ((m['Pmax'] - m['Pmin']) * r + m['Pmin']).round(1)\n m['Humidity'] = ((m['Hmax'] - m['Hmin']) * r + m['Hmin']).astype(int)\n\n # drop redundant columns and assign to output\n dcols = ['Month', 'Timezone', 'Pmax', 'Pmin',\n 'Hmax', 'Hmin', 'Tmean_high', 'Tmean_low']\n m.drop(columns=dcols, inplace=True)\n self.output = m" ]
[ "0.64943063", "0.6317849", "0.6268697", "0.62601906", "0.621405", "0.6126189", "0.60920346", "0.6080956", "0.5973115", "0.5948292", "0.5899673", "0.58927464", "0.58731025", "0.58682513", "0.58575284", "0.5856938", "0.5856862", "0.57481647", "0.570413", "0.5686568", "0.56827986", "0.56786686", "0.56518227", "0.56386733", "0.5625455", "0.5597012", "0.5590995", "0.5537603", "0.552949", "0.55125326" ]
0.63292754
1
Retrieve weather for written keys,prep two dataframes. Input parameters None. Retreives data internally. Output
def get_weather_data(): keys = ['1364038.csv', '1364041.csv', '1364042.csv', '1364043.csv', '1364044.csv', '1364046.csv', '1364047.csv', '1364048.csv', '1364051.csv', '1364052.csv', '1364053.csv', '1364054.csv', '1364055.csv', '1364058.csv', '1364059.csv', '1364060.csv', '1364061.csv', '1364062.csv', '1364063.csv', '1364064.csv', '1364066.csv'] df_weather = import_weather(keys) df_weather_dist = df_weather[[ 'LATITUDE', 'LONGITUDE', 'name']].drop_duplicates().reset_index() return df_weather, df_weather_dist
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def import_weather(keys):\n # imports weather and cleans\n df_all_weather = get_weather_as_df(keys)\n return clean_weather_df(df_all_weather)", "def get_weather(address, update = ''):\n \n def proceed_with_method():\n if update == 'forecast':\n precip_hist_dict = historic_weather_data(address, \"P\")\n temp_hist_dict = historic_weather_data(address, \"T\") \n else:\n precip_hist_dict = historic_weather_data(address, \"P\", update)\n temp_hist_dict = historic_weather_data(address, \"T\", update) \n \n if update == 'history':\n forecast_dict = get_weather_forecast(address)\n else:\n forecast_dict = get_weather_forecast(address, update)\n\n \n precip_forecast_dict = {}\n temp_forecast_dict = {}\n for key, item in forecast_dict.items():\n precip_forecast_dict[key] = item[1]\n temp_forecast_dict[key] = item[0]\n \n precip_dict = join_historic_forecast(precip_hist_dict, precip_forecast_dict)\n #use adj join for temp, forecast is not accurate, this at least gives a shape\n temp_dict = adj_join_historic_forecast(temp_hist_dict, temp_forecast_dict)\n return [precip_dict, temp_dict]\n \n title = \"weather_dict_temp\"\n if weather_profile(address, title) == None or update != '':\n print(\"/t-Adding/refreshing data...\")\n data = proceed_with_method()\n weather_profile(address, title, data[1], update)\n else:\n print(\"There is existing data for: \" + str(title))\n \n title = \"weather_dict_precip\"\n if weather_profile(address, title) == None or update != '':\n print(\"/t-Adding/refreshing data...\")\n data = proceed_with_method()\n weather_profile(address, title, data[0], update)\n return [weather_profile(address, title),weather_profile(address, \"weather_dict_temp\")]\n else:\n return [weather_profile(address, title),weather_profile(address, \"weather_dict_temp\")]\n print(\"There is existing data for: \" + str(title))", "def compute_aggregate_weather_data():\n\n # get a list of all the csv files names in the 'weather_data' directory\n files = get_all_csv_files_in_directory('weather_data')\n\n # Todo: if the number of csv files doesn't match the expected value, unzip remaining using the 'os' module\n\n if len(files) == 0:\n\n # Unzip all files in current directory and subdirectories\n print \"unzipping weather files...\"\n os.system(\"unzip 'weather_data/*.zip' -d weather_data\")\n\n\n # Try again to get files\n files = get_all_csv_files_in_directory('weather_data')\n\n # Throw exception if still missing csv files\n if len(files) == 0:\n raise ValueError(\"Missing weather data in csv format in the 'weather_data' directory\")\n\n # convert the list of csv file names to a list of corresponding DataFrames\n dallas_files = filter(lambda file_name : \"KDAL\" in file_name, files)\n houston_files = filter(lambda file_name : \"KHOU\" in file_name, files)\n san_antonio_files = filter(lambda file_name : \"KSAT\" in file_name, files)\n\n print \"Retrieved weather data files...\"\n print \"\\t# of Dallas weather files found: \", len(dallas_files)\n print \"\\t# of Houston weather files found: \", len(houston_files)\n print \"\\t# of San Antonio weather files found: \", len(san_antonio_files)\n\n dallas_dfs = map(lambda file_name: read_weather_data_from_csv(\"./weather_data/\" + file_name), dallas_files)\n houston_dfs = map(lambda file_name: read_weather_data_from_csv(\"./weather_data/\" + file_name), houston_files)\n san_antonio_dfs = map(lambda file_name: read_weather_data_from_csv(\"./weather_data/\" + file_name), san_antonio_files)\n\n dallas_df = pd.concat(dallas_dfs)\n houston_df = pd.concat(houston_dfs)\n san_antonio_df = pd.concat(san_antonio_dfs)\n\n print \"Aggregating all of the weather data...\"\n # fold the list of data frames into a single data frame\n aggregate_df = reduce(lambda df1, df2: pd.merge(df1, df2, on=\"Date\", how=\"outer\"), [dallas_df, houston_df, san_antonio_df]).sort_values(\"Date\")\n\n return aggregate_df", "def combine_weather(weather):\n\n weather1 = weather[weather[\"Station\"] == 1]\n weather2 = weather[weather[\"Station\"] == 2]\n\n\n pass", "def make_dataframe(self):\n logging.info('*** Creating the dataframes from the source files ' )\n \n for k in self.datasets_keys:\n #for k in ['igra2' , 'ncar']:\n \n logging.info('*** Creating the dataframe for the dataset: %s ' , k ) \n \n p_levels = self.data[k]['df']['observations_table']['z_coordinate'][:]\n logging.debug(' Loaded the z_coordinate')\n \n z_type = self.data[k]['df']['observations_table']['z_coordinate_type'][:]\n logging.debug(' Loaded the z_coordinate_type')\n \n obs_variable = self.data[k]['df']['observations_table']['observed_variable'][:]\n logging.debug(' Loaded the observed_variable')\n \n obs_values = self.data[k]['df']['observations_table']['observation_value'][:]\n logging.debug(' Loaded the observation_value')\n \n observation_id = self.data[k]['df']['observations_table']['observation_id'][:]\n logging.debug(' Loaded the observation_id')\n \n units = self.data[k]['df']['observations_table']['units'][:].astype(int)\n logging.debug(' Loaded the units') \n \n report_id = self.data[k]['df']['observations_table']['report_id'][:] \n logging.debug(' Loaded the report_id')\n \n date_time = self.data[k]['df']['observations_table']['date_time'][:]\n logging.debug(' Loaded the date_time (deltas)')\n \n lat , lon = self.data[k]['df']['observations_table']['latitude'][:] , self.data[k]['df']['observations_table']['longitude'][:]\n logging.debug(' Loaded the lat,lon ')\n \n \n self.obs_table_columns = list(self.data[k]['df']['observations_table'].keys() )\n \n self.data[k]['df'].close()\n \n \"\"\" Creating a dataframe \"\"\"\n columns = ['date_time', 'z_coordinate' , 'z_coordinate_type', 'observed_variable' , 'observation_value' , 'report_id' , 'observation_id' , 'latitude' , 'longitude', 'units']\n logging.info(' Loaded the data, creating dataframe ')\n \n df = pd.DataFrame( list(zip( date_time, p_levels, z_type, obs_variable , obs_values, report_id, observation_id , lat , lon, units ) ) , columns = columns ) \n \n \n \"\"\" Storing the dataframe \"\"\" ### try using xarrays ??? \n logging.debug('Storing the DF ' ) \n self.data[k]['dataframe'] = df\n \n logging.debug(' PD dataframe created !!! ')", "def get_weather_data(lat='40.761440',lng='-73.981806'):\r\n key ='********************************'\r\n x = pd.DataFrame()\r\n unix_now = int((dt.datetime.now()- dt.datetime(1970,1,1)).total_seconds())\r\n for time in range(unix_now-86400, unix_now+604800, 86400):\r\n rsp = rq.get('https://api.darksky.net/forecast/{}/{},{},{}'.format(key, lat, lng, time))\r\n rsp_json = json.loads(rsp.text)\r\n row = json_normalize(rsp_json[\"daily\"]['data'])\r\n x = x.append(row)\r\n \r\n x = x[['icon','apparentTemperatureHigh','apparentTemperatureLow','cloudCover','humidity','precipProbability',\r\n 'pressure','visibility','windBearing','windGust','windSpeed']].reset_index(drop=True)\r\n return x", "def get_gis_historical_data():\n logging.info(\"Generating baseline reference and historical weather data.\")\n \n # Initialising function variables\n fake = Faker()\n geolocator = Nominatim()\n config_data = get_config()\n locations = config_data[\"location\"]\n \n # Check if there are no duplicate locations in the config.yaml file.\n if len(locations) != len(set(locations)):\n logging.error(\"Duplicate location found. Please check config.yaml file.\")\n raise ValueError\n \n # Initialise pandas dataframe column name for baseline reference\n # and historical data.\n df_ref = pd.DataFrame(columns=[\"Location\", \"Latitude\"\n ,\"Longitude\", \"Elevation\"\n ,\"Timezone\"])\n df_hist = pd.DataFrame(columns=[\"Location\", \"Date\"\n ,\"Month\", \"Temperature_Min\"\n ,\"Temperature_Max\", \"Humidity\"\n ,\"Pressure\"])\n \n # Generate weather data for each location.\n for idx, loc in enumerate(locations):\n \n logging.info(\"Retrieving geolocation data for {}.\".format(loc))\n \n # Retrieving geolocation data from geopy library.\n loc_data = geolocator.geocode(loc)\n \n logging.info(\"Check if the location {} is valid.\".format(loc))\n if loc_data is None:\n logging.error(\"Invalid location value supplied ({}). Please check config.yaml file.\".format(loc))\n raise ValueError\n logging.info(\"The location {} is valid.\".format(loc))\n \n city = get_city(loc)\n lat = loc_data.latitude\n lon = loc_data.longitude\n \n # Retrieving elevation data for the location.\n elev = get_elevation_data(lat, lon)\n \n for month in range(1, 13):\n \n logging.info(\"Retrieving {} weather data for month {}.\".format(loc, month))\n \n for sample in range(config_data[\"gis\"][\"sampling_number\"]):\n \n temp_min = None\n temp_max = None\n humidity = None\n pressure = None\n \n while temp_min is None or temp_max is None or humidity is None or pressure is None:\n \n year = random.randint(config_data[\"gis\"][\"year_start\"], config_data[\"gis\"][\"year_end\"])\n\n _, last_day = calendar.monthrange(year, month)\n\n datetime_start = datetime.datetime(year, month, 1)\n datetime_end = datetime.datetime(year, month, last_day)\n\n date_gen = fake.date_time_between_dates(datetime_start=datetime_start\n ,datetime_end=datetime_end)\n\n forecast = forecastio.load_forecast(config_data[\"forecastio_api_key\"]\n ,lat\n ,lon\n ,time=date_gen\n ,units=\"si\")\n\n historical_data = forecast.json[\"daily\"][\"data\"][0]\n \n timezone = forecast.json.get(\"timezone\", None)\n temp_min = historical_data.get(\"temperatureMin\", None)\n temp_max = historical_data.get(\"temperatureMax\", None)\n humidity = historical_data.get(\"humidity\", None) * 100\n pressure = historical_data.get(\"pressure\", None)\n \n df_temp_hist = pd.Series(dict(zip(df_hist.columns\n ,[city, date_gen\n ,date_gen.month, temp_min\n ,temp_max, humidity\n ,pressure])))\n \n df_hist = df_hist.append(df_temp_hist, ignore_index=True)\n \n df_temp_ref = pd.Series(dict(zip(df_ref.columns\n ,[city, lat\n ,lon, elev\n ,timezone])))\n df_ref = df_ref.append(df_temp_ref, ignore_index=True)\n \n logging.info(\"Generating position to consolidate latitude, longitude and elevation data\")\n df_pos = df_ref[[\"Latitude\", \"Longitude\", \"Elevation\"]].round(2)\n df_pos[\"Elevation\"] = df_pos[\"Elevation\"].astype(int) \n df_ref[\"Position\"] = df_pos.astype(str).apply(lambda x: \",\".join(x), axis=1)\n \n logging.info(\"Saving baseline reference data.\")\n df_ref.to_csv(get_file_path(folder_name=\"data\"\n ,subdirectory=config_data[\"gis\"][\"output_subdirectory\"]\n ,file_name=config_data[\"gis\"][\"output_base_reference_file_name\"])\n ,index=False)\n logging.info(\"Completed saving baseline reference data.\")\n\n logging.info(\"Saving baseline historical data.\")\n df_hist.to_csv(get_file_path(folder_name=\"data\"\n ,subdirectory=config_data[\"gis\"][\"output_subdirectory\"]\n ,file_name=config_data[\"gis\"][\"output_base_historical_file_name\"])\n ,index=False)\n logging.info(\"Completed saving baseline historical data.\")", "def join_daily_cweeds_wy2_and_wy3(wy2_df, wy3_df):\n assert wy2_df['CWEEDS Format'] == 'WY2'\n assert wy3_df['CWEEDS Format'] == 'WY3'\n assert wy2_df['Time Format'] == wy3_df['Time Format']\n\n time_wy23 = np.hstack([wy2_df['Time'], wy3_df['Time']])\n time_wy23 = np.unique(time_wy23)\n time_wy23 = np.sort(time_wy23)\n\n wy23_df = {}\n wy23_df['Time Format'] = wy3_df['Time Format']\n wy23_df['CWEEDS Format'] = 'WY2+WY3'\n\n # Copy the header info from WY3 dataset :\n\n for key in ['HORZ version', 'Location', 'Province', 'Country',\n 'Station ID', 'Latitude', 'Longitude', 'Time Zone',\n 'Elevation']:\n wy23_df[key] = wy3_df[key]\n\n # Merge the two datasets :\n\n wy23_df['Time'] = time_wy23\n wy23_df['Years'] = np.empty(len(time_wy23)).astype(int)\n wy23_df['Months'] = np.empty(len(time_wy23)).astype(int)\n wy23_df['Days'] = np.empty(len(time_wy23)).astype(int)\n wy23_df['Hours'] = np.empty(len(time_wy23)).astype(int)\n wy23_df['Irradiance'] = np.empty(len(time_wy23)).astype('float64')\n\n for dataset in [wy2_df, wy3_df]:\n indexes = np.digitize(dataset['Time'], time_wy23, right=True)\n for key in ['Years', 'Months', 'Days', 'Hours', 'Irradiance']:\n wy23_df[key][indexes] = dataset[key]\n\n return wy23_df", "def read_weather_data():\n # Check if UTC to gmt+1 conversion is being handled correctly\n weather = pd.read_csv('//datc//opschaler//weather_data//knmi_10_min_raw_data//output//df_combined_uncleaned.csv',\n delimiter='\\t', comment='#',\n parse_dates=['datetime'])\n weather = weather.set_index(['datetime'])\n return weather", "def Collect_data(clo, cla, FD, LD, ZC, idx_time, cntry, TZ):\r\n #initiate the console response\r\n rep = \"\"\r\n global ddf\r\n \r\n #define the noaa server access\r\n server_noaa = \"https://www.ncei.noaa.gov/data/global-hourly/access/\"\r\n \r\n #Initate dateframe\r\n data = pd.DataFrame()\r\n \r\n #Convert date from specified timezone to UTC\r\n FDc = Date_calibration(FD, 1, TZ)\r\n LDc = Date_calibration(LD, 1, TZ)\r\n \r\n #define timestep\r\n timestep = \"1 H\"\r\n \r\n #Loop on the range time by each year\r\n for y in range(FDc.year, (LDc.year + 1)):\r\n rep += '--- Collect Year ['+str(y) + '] --- \\n' \r\n \r\n #Loop on each weather station while the ouput data is good\r\n #weather station in the year instancied dataframe \r\n for i in range(len(ddf[y])) :\r\n \r\n #Define the memory key : year_zipcode\r\n key_d_z = str(y)+'_'+str(ZC)\r\n \r\n #Verify if the data is already in the memory\r\n if(key_d_z in memory_df.keys()) :\r\n #The data is already in the memory :\r\n #Collect the data and go next (save compute time and server solicitation)\r\n ext_data = memory_df[key_d_z]\r\n NS, DO = memory_NS_DO[key_d_z].split('_')[0], memory_NS_DO[key_d_z].split('_')[1]\r\n break\r\n else:\r\n \r\n #The data isn't in the memory :\r\n \r\n #Collect information about the nearest weather station from the zip code\r\n rs, NS, DO = Fetch_station(clo, cla, y)\r\n \r\n #Generate the ftp key weather station\r\n code_station = str(ddf[y]['USAF'][rs])+str(ddf[y]['WBAN'][rs])\r\n \r\n #Define the server access\r\n url = server_noaa+str(y)+'/'+code_station+'.csv'\r\n \r\n #Get the data\r\n req = requests.get(url)\r\n \r\n #The server answer\r\n if(req.status_code == 200):\r\n \r\n #Extract the data (only date and temperature)\r\n ext_data = pd.read_csv(url, usecols=['DATE','TMP'])\r\n \r\n #Check if the data isn't empty (1000 is arbitrary)\r\n if(len(ext_data) > 1000):\r\n \r\n #Format data\r\n ext_data, qual = Data_formatting(ext_data, y, timestep, TZ)\r\n \r\n #Check if the data quality respect the quality rule\r\n if(qual > quality_rule):\r\n \r\n #Save the date in the memory\r\n memory_df[key_d_z] = ext_data\r\n memory_NS_DO[key_d_z] = str(NS)+'_'+str(DO)\r\n \r\n #Response for the GUI\r\n rep += \"# Station [\"+str(NS)+\"] valid : \\n\"\r\n rep += \"- Quality density data : \"+str(round(qual, 2))+\"% \\n\"\r\n rep += \"- Great circle distance : \"+str(round(DO,2))+\"km \\n\"\r\n break\r\n else:\r\n #The data quality is too bad\r\n #Response for the GUI\r\n rep += \"# Station [\"+str(NS)+\"] invalid : \\n\"\r\n rep += \"- Quality density data : \"+str(round(qual,2))+\"% \\n\"\r\n rep += \"> Quality criterion unsatisfied \\n\"\r\n \r\n #Delete the weather station in the dataframe (instancied by year)\r\n ddf[y] = ddf[y].drop(rs).reset_index(drop=True)\r\n continue\r\n \r\n else:\r\n #The data density is too low\r\n \r\n #Response for the GUI\r\n rep += \"# Station [\"+str(NS)+\"] invalid : \\n\"\r\n rep += \"> Low data volume \\n\"\r\n \r\n #Delete the weather station in the dataframe (instancied by year)\r\n ddf[y] = ddf[y].drop(rs).reset_index(drop=True)\r\n\r\n continue\r\n else:\r\n #The NOAA doesn't answer for the code station\r\n rep += \"# Station [\"+str(NS)+\"] invalid : \\n\"\r\n rep += \"> Server doesn't answer\\n\"\r\n \r\n #Delete the weather station in the dataframe (instancied by year)\r\n ddf[y] = ddf[y].drop(rs).reset_index(drop=True)\r\n\r\n continue\r\n #Add data in the Dataframe\r\n data = data.append(ext_data)\r\n \r\n #Define a new dataframe mark out by the specified time range\r\n range_time = pd.DataFrame(index=pd.DatetimeIndex(start=FD, end=LD, freq=timestep))\r\n \r\n #Paste data in the time marked out Dataframe\r\n range_time['Temp'] = data['TMP']\r\n \r\n #Calculate the amount of NaN (global)\r\n nb_nan = range_time['Temp'].isnull().sum()\r\n \r\n #Calculate the global quality\r\n quality = (1 - (nb_nan) / len(range_time)) * 100\r\n \r\n #Fill the gap data by temporal interpolation\r\n data = range_time.interpolate(method='time')\r\n data = data.ffill().bfill()\r\n data['Temp'] = round(data['Temp'], 2)\r\n \r\n \r\n #If specified index time, cut the data for it\r\n if(len(idx_time)> 2):\r\n final_data = pd.DataFrame(index = pd.to_datetime(idx_time))\r\n final_data['Temp'] = round(data['Temp'], 2)\r\n #final_data = final_data.resample(rule = str(timestep)).mean()\r\n #final_data = final_data.dropna()\r\n else:\r\n final_data = data\r\n \r\n return final_data, quality, NS, DO, rep", "def Wind_Prediction():\n model = pickle.load(open('wind_model.pkl','rb'))\n \n # Load DataFrame\n # Wind\n longitude = 53.556563\n latitude = 8.598084\n\n url = ('https://api.openweathermap.org/data/2.5/onecall?lat=8.598084&lon=53.556563&units=imperial&appid=43e49f2fb4d17b806dfff389f21f4d27')\n response = requests.get(url)\n\n weather = response.json()\n dailynorm = json_normalize(weather, 'daily')\n \n df = pd.DataFrame(dailynorm)\n wind_df = df[['dt', 'wind_speed', 'wind_deg']].copy()\n wind_df['date'] = pd.to_datetime(wind_df['dt'],unit='s')\n wind_df['day'] = wind_df['date'].dt.day\n wind_df['month'] = wind_df['date'].dt.month\n wind_df = wind_df.fillna(0)\n wind_df.rename(columns={'wind_speed':'wind speed', 'wind_deg':'direction'}, inplace=True)\n wind_df = wind_df.drop(['dt','date'], axis = 1)\n Xnew = wind_df.values\n p_pred = model.predict(Xnew)\n p_pred = pd.DataFrame(p_pred)\n p_pred.columns = ['Predicted Power']\n final_wind_df = pd.concat([wind_df, p_pred], axis = 1)\n dictionaryObject = final_wind_df.to_dict()\n \n return dictionaryObject", "def get_data():\n \n \"\"\" Prepare variables\"\"\"\n urls = {\"cases\": \"https://github.com/CSSEGISandData/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Confirmed.csv\",\n \"deaths\": \"https://github.com/CSSEGISandData/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Deaths.csv\",\n \"recovered\": \"https://github.com/CSSEGISandData/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Recovered.csv\"}\n\n localnames = {\"cases\": \"Cases.csv\",\n \"deaths\": \"Deaths.csv\",\n \"recovered\": \"Recovered.csv\"}\n\n dfs = {\"cases\": None,\n \"deaths\": None,\n \"recovered\": None}\n\n \"\"\" Download\"\"\"\n for key in urls.keys():\n url = urls[key]\n localname = localnames[key]\n urllib.request.urlretrieve(url, localname)\n\n \"\"\" Load variables\"\"\"\n for key in dfs.keys():\n dfs[key] = pd.read_csv(localnames[key])\n \n \"\"\" Return\"\"\"\n return(dfs)", "def get_outdoor_data(temp_dir,site):\n if site == 'berk':\n files_od = glob(join(temp_dir,'outdoor','20*.xlsx'))\n elif site == 'bus':\n files_od = glob(join(temp_dir,'outdoor','Busara*.csv'))\n else:\n raise NameError(site)\n\n dfs = []\n for f in files_od:\n if site == 'berk':\n this_df = pd.read_excel(f,sheet_name=0,usecols='B:D',index_col=0,parse_dates=True, header=1)\n elif site == 'bus':\n this_df = pd.read_csv(f,usecols=[0,1,2],index_col=0,parse_dates=True,header=2)\n \n # drop missing values that prevented conversion to float type\n if this_df.iloc[:,0].dtype != np.float64:\n this_df = this_df[this_df.iloc[:,0] != ' ']\n this_df = this_df.astype(np.float64)\n\n # correct for weird timezones in berkeley datalogger\n this_df = correct_tz(this_df,site)\n \n this_df.columns = ['T','RH']\n this_df.index.name = 'time'\n\n # convert to celsius\n this_df['T'] = (this_df['T'] - 32) * 5/9\n dfs.append(this_df)\n \n df_od = pd.concat(dfs)\n\n # drop duplicated measurements\n df_od = df_od[~df_od.index.duplicated(keep='last')].sort_index()\n \n # separate out into daily min,mean,max\n groups = df_od.groupby(df_od.index.date)\n dfs_od = {'all':df_od,\n 'min': groups.min(),\n 'mean': groups.mean(),\n 'max': groups.max()}\n \n for i in ['min','mean','max']:\n # remove first and last day to ignore days where we did not get full recording\n dfs_od[i] = dfs_od[i].iloc[1:-1,:]\n \n # name index so that we can merge onto multiIndex'd dataframe\n dfs_od[i].index.name = 'date'\n \n return dfs_od", "def get_data(table_name, end, num, start=None):\n if start == None:\n if table_name == \"days\": start = end - timedelta(days=num-1) \n if table_name == \"weeks\": start = end - timedelta(weeks=num-1) \n if table_name == \"months\": start = end - relativedelta(months=+num-1) \n if table_name == \"years\": start = end - relativedelta(years=+num-1) \n else: \n start = days.get_entry(table_name, start).date\n \n dates = []\n data = []\n weather = []\n density = []\n \n while start <= end:\n entry = days.get_entry(table_name, start)\n data.append(entry.sentiment)\n \n if table_name == \"days\": \n dates.append(entry.date.strftime(\"%B %d, %Y\"))\n start = start + timedelta(days=1)\n if table_name == \"weeks\": \n dates.append(entry.date.strftime(\"%B %d, %Y\"))\n start = start + timedelta(weeks=1) \n if table_name == \"months\": \n dates.append(entry.date.strftime(\"%B %Y\"))\n start = start + relativedelta(months=+1) \n if table_name == \"years\": \n dates.append(entry.date.strftime(\"%Y\"))\n start = start + relativedelta(years=+1) \n\n # 7/15/15 is the last entry in the current weather dictionary\n num_days = (min(start, date(2015,7,15)) - entry.date).days\n temp = {entry.date + timedelta(days=i): weather_dict[entry.date + timedelta(days=i)] for i in range(num_days)}\n weather.append(float(sum(temp.values()))/float(len(temp)))\n\n if density_dict != None:\n d = max(entry.date, date(2014,7,1))\n num_days = (min(start, date(2015,7,28)) - d).days\n rho = {d + timedelta(days=i): density_dict[d + timedelta(days=i)] for i in range(num_days)}\n density.append(float(sum(rho.values()))/float(len(rho)))\n\n return dates, data, weather, density", "def get_data(temp_estimate_source='historic'):\n\n print 'get data from files'\n load = process_load_data(datafoldername+loadfilename_train)\n load_test = process_load_data(datafoldername+loadfilename_test)\n temp = process_temp_data(datafoldername+tempfilename_train)\n holidays = process_holiday_data(datafoldername+holidayfilename)\n\n print 'merge load with temp data'\n X_train_df = load.merge(temp, on='datetime', how='left')\n X_test_df = load_test.merge(temp, on='datetime', how='left')\n\n print 'estimate missing temps'\n # find rows with missing temperatures\n missingtemp = X_test_df[X_test_df.isnull().any(axis=1)][['datetime', 'zone_id']].copy()\n\n # source estimates for missing periods\n if temp_estimate_source == 'arima':\n # use preprocessed arima estimates\n estimatedtemps = process_arima_temp_data(datafoldername+arimafilename)\n elif temp_estimate_source == 'actuals':\n # use actual temperatures - as provided after conclusion of kaggle competition\n estimatedtemps = process_temp_data(datafoldername+tempfilename_solution)\n else:\n # use means of historical temps at same day/time.\n estimatedtemps = get_estimated_temps(missingtemp[['datetime']].drop_duplicates(), temp)\n\n # merge estimates against missing rows, and use to update original dataframe in place\n replacementtemps = missingtemp.merge(estimatedtemps, left_on='datetime', right_on='datetime', how='left')\n replace_unknown_temps(X_test_df, replacementtemps)\n\n print 'merge in holiday dates'\n X_train_df = X_train_df.merge(holidays, on='datetime', how='left')\n X_train_df['holiday'].fillna(0, inplace=True)\n X_test_df = X_test_df.merge(holidays, on='datetime', how='left')\n X_test_df['holiday'].fillna(0, inplace=True)\n\n print 'add datetime categorical variables'\n X_train_df = add_datetime_categories(X_train_df)\n X_test_df = add_datetime_categories(X_test_df)\n\n return X_train_df, X_test_df", "def get_weather_data(weather_station):\n now = datetime.datetime.now()\n then = now - datetime.timedelta(days=7)\n\n query_date_start = (\"%d%02d%02d\" % (then.year, then.month, then.day))\n query_date_end = (\"%d%02d%02d\" % (now.year, now.month, now.day))\n\n api_key = '/api/%s' % WUNDERGROUND_KEY\n history_key = '/history_%s%s/lang:EN/units:english/bestfct:1/v:2.0' % (query_date_start, query_date_end)\n query = '/q/%s.json?showObs=0&ttl=120' % weather_station\n\n weather_url = (\"%s%s%s%s\" % (WUNDERGROUND_HOST, api_key, history_key, query))\n\n logger.info('Weather URL: %s', weather_url)\n response = requests.get(weather_url).text\n\n max_temp_avg = json.loads(response)['history']['summary']['max_temperature_avg']\n sum_precip = json.loads(response)['history']['summary']['precip_sum']\n\n return max_temp_avg, sum_precip", "def read_training(index_columns=None, both=False, weather=False):\n if weather:\n raw_X_train = pd.read_csv('data\\\\train_X.csv', parse_dates=['date'])\n raw_weather = pd.read_csv('data\\\\weather_data.csv', parse_dates=['date'])\n\n raw_X_train = ffill_nans(raw_X_train)\n raw_X_train = raw_X_train.merge(raw_weather, how='left', on=['date','hour'])\n raw_X_train = raw_X_train.set_index(index_columns)\n\n else:\n raw_X_train = pd.read_csv(\n 'data\\\\train_X.csv',\n parse_dates=['date'],\n index_col=index_columns)\n if both:\n raw_y_train = pd.read_csv(\n 'data\\\\train_y.csv',\n parse_dates=['date'],\n index_col=index_columns)\n\n return raw_X_train, raw_y_train\n \n return raw_X_train", "def getTodaysWeather(self, keyword, temp):\n\n\t\t# Variables\n\t\tweather = {} \n\t\tfio = self.helper.getFio(keyword, temp) # Getting fio object\n\t\t\n\t\t# Getting todays weather data and populating the dictionary\n\t\tif fio.has_daily() is True and fio.has_hourly() is True:\n\t\t daily = FIODaily.FIODaily(fio)\n\t\t hourly = FIOHourly.FIOHourly(fio)\n\t\t for day in xrange(0, 1):\n\t\t\t\tfor item in daily.get_day(day).keys():\n\t\t\t\t\tif item == \"temperatureMin\":\n\t\t\t\t\t\tweather[item] = str(daily.get_day(day)[item]).split(\".\")[0]\n\t\t\t\t\tif item == \"summary\":\n\t\t\t\t\t\tweather[item] = unicode(daily.get_day(day)[item])\n\t\t\t\t\tif item == \"temperatureMax\":\n\t\t\t\t\t\tweather[item] = str(daily.get_day(day)[item]).split(\".\")[0]\n\t\t\t\t\tif item == \"windSpeed\":\n\t\t\t\t\t\twindSpeed = unicode(daily.get_day(day)[item])\n\t\t\t\t\tif item == \"windBearing\":\n\t\t\t\t\t\twindBearing = unicode(daily.get_day(day)[item])\n\t\t\t\t\t\twindBearing = self.helper.convertWindBearing(windBearing)\n\t\t\t\t\tif item == \"sunsetTime\":\n\t\t\t\t\t\tweather[item] = self.helper.getDateForWeather(daily.get_day(day)[item])\n\t\t\t\t\tif item == \"sunriseTime\":\n\t\t\t\t\t\tweather[item] = self.helper.getDateForWeather(daily.get_day(day)[item])\n\t\t\t\t\tif item == \"precipProbability\":\n\t\t\t\t\t\tweather[item] = str(daily.get_day(day)[item] * 100).split(\".\")[0] + \"%\"\n\t\t\t\tweather[\"wind\"] = windBearing + \" \" + windSpeed + \" mph\"\n\t\t\t\tfor item in hourly.get_hour(day).keys():\n\t\t\t\t\tif item == \"summary\":\n\t\t\t\t\t\tweather[\"current\"] = unicode(hourly.get_hour(0)[item])\n\t\t\t\t\tif item == \"temperature\":\n\t\t\t\t\t\tweather[item] = str(hourly.get_hour(0)[item]).split(\".\")[0]\n\t\t\t\t\tif item == \"icon\":\n\t\t\t\t\t\tweather[item] = unicode(hourly.get_hour(0)[item])\n\t\t\t\t\tif item == \"cloudCover\":\n\t\t\t\t\t\tweather[item] = str(hourly.get_hour(0)[item] * 100).split(\".\")[0] + \"%\"\n\t\t\t\tweather[\"town\"] = self.helper.getCoords(keyword)[2]\n\t\telse:\n\t\t\treturn 'No Todays data'\n\n\t\treturn weather", "def get_weather_data():\n get_pronto_data()\n zp = zipfile.ZipFile('open_data_year_one.zip')\n file_handle = zp.open('2015_weather_data.csv')\n return pd.read_csv(file_handle)", "def weather():\r\n def weather_api_call():\r\n with open('config.json', 'r') as conf:\r\n conf = json.load(conf)\r\n # Gets the API key from the config.json file\r\n weather_api_key = conf[\"weather_api_key\"]\r\n weather_city_name = conf['weather_city_name']\r\n response = requests.get(\r\n 'http://api.openweathermap.org/data/2.5/weather?'\r\n 'q=' + weather_city_name + '&units=metric&appid=' + weather_api_key)\r\n resp_json = response.json()\r\n with open('weather.json', 'w') as outfile:\r\n # Uses the data from the API to overwrite the weather data\r\n json.dump(resp_json, outfile)\r\n outfile.close()\r\n\r\n def weather_data_extractor():\r\n with open('weather.json', 'r') as weather_json:\r\n weather_json = json.load(weather_json)\r\n temp = weather_json[\"main\"]\r\n weather_item = weather_json[\"weather\"]\r\n desc = weather_item[0]\r\n current_temperature = \"The current temperature is: \" + \\\r\n str(int(temp[\"temp\"])) + \"C\"\r\n current_feels_like = \"Feels like: \" + \\\r\n str(int(temp[\"feels_like\"])) + \"C\"\r\n forecast = desc[\"main\"]\r\n return current_feels_like, current_temperature, forecast\r\n\r\n weather_api_call()\r\n return weather_data_extractor()", "def get_city_weather_and_dispatch(city):\n # accumulate weather record for city\n check_path(exp_data_path + os.sep + 'weather')\n check_path(exp_data_path + os.sep + 'weather' + os.sep + city)\n time_index = np.load(exp_data_path + os.sep + 'station_list' + os.sep + 'time_index.npy', allow_pickle=True)\n time_index = dict(time_index.tolist())\n with open(exp_data_path + os.sep + 'weather' + os.sep + city + os.sep + 'whole_{}.csv'.format(city), \"w\") as f:\n writer = csv.writer(f)\n res = []\n for file in os.listdir(spider_data_path + os.sep + 'weather' + os.sep + city):\n with open(spider_data_path + os.sep + 'weather' + os.sep + city + os.sep + file) as day:\n reader = csv.reader(day)\n for line in reader:\n line[0] = line[0].replace(\"\\ufeff\", \"\")\n if line[0] in time_index['rev_index']:\n line.insert(0, time_index['rev_index'][line[0]])\n res.append(line)\n res = sorted(res, key=lambda x : x[0])\n writer.writerows(res)\n\n # replace index and divide into concrete matter\n name_pos = {'weather_type': 2, 'temperature': 3, 'air': 4, 'wind': 6}\n con_res = {}\n with open(exp_data_path + os.sep + 'weather' + os.sep + city + os.sep + 'whole_{}.csv'.format(city)) as f:\n reader = csv.reader(f)\n for line in reader:\n for name, index in name_pos.items():\n if name not in con_res:\n con_res[name] = []\n con_res[name].append([line[0], line[index]])\n\n for name, index in name_pos.items():\n with open(exp_data_path + os.sep + 'weather' + os.sep + city + os.sep + '{}_{}.csv'.format(city, name), \"w\") as f:\n writer = csv.writer(f)\n for line in con_res[name]:\n writer.writerow(line)", "def transform(self, y=None):\n df1 = self.join_dfs(self.X, self.weather)\n df2 = self.join_dfs(df1, self.us_holidays)\n df3 = self.join_dfs(df2, self.islamic_holidays)\n df4 = self.join_dfs(df3, self.jewish_holidays)\n df5 = self.join_dfs(df4, self.events)\n df6 = self.join_dfs(df5, self.seahawks)\n df7 = self.join_dfs(df6, self.huskies)\n df8 = self.join_dfs(df7, self.sounders)\n return df8.fillna(0)", "def populate_weather(connection):\n metadata = load_metadata('weather')\n cursor = connection.cursor()\n water_defs = get_water_definitions()\n\n # Check if tables are already populated.\n cursor.execute('SELECT count(*) FROM weather')\n weather_count = cursor.fetchone()[0]\n\n if weather_count:\n print('Weather tables already populated!')\n return\n\n print('WEATHER:')\n\n # Darksky data\n for dir_name, location in metadata.items():\n print(f'\\tPopulating weather: \"{location[\"name\"]}\".')\n\n # Insert location.\n cursor.execute(f'''INSERT INTO locations(name, lat, lng)\n VALUES ('{location['name']}', {location['lat']}, {location['lng']})''')\n location_id = cursor.lastrowid\n\n # Set weather locations for watercourses/aquifers.\n for water_body in [d['body'] for d in water_defs.values()]:\n if water_body in location:\n cursor.execute(f'''UPDATE {water_body}s\n SET location_id = {location_id}\n WHERE name IN ('{\"','\".join(location[water_body])}')''')\n break\n\n dir_path = get_data_path('weather', 'raw', dir_name)\n for json_file_name in os.listdir(dir_path):\n json_path = os.path.join(dir_path, json_file_name)\n with open(json_path, 'r', encoding='utf-8') as json_file:\n print(f'\\t\\tPopulating year: {json_file_name[0:-5]}')\n year_forecasts = json.load(json_file)\n for date, date_forecast in year_forecasts.items():\n hourly_forecasts = date_forecast['hourly']\n\n if not hourly_forecasts:\n print(f'\\t\\tNo hourly forecasts for {date}!')\n continue\n\n daily_forecast = {\n 'location_id': location_id,\n 'time': date_forecast['time'],\n 'day_time': date_forecast['sunset_time'] - date_forecast['sunrise_time'],\n 'precipitation': 0,\n 'snow_accumulation': 0\n }\n # List of value names with `avg`, `min` and `max` values\n value_names = {\n 'temperature': 'temperature',\n 'cloud_cover': 'cloudCover',\n 'dew_point': 'dewPoint',\n 'humidity': 'humidity',\n 'pressure': 'pressure',\n 'uv_index': 'uvIndex',\n 'precipitation_probability': 'precipProbability',\n 'precipitation_intensity': 'precipIntensity'\n }\n # Value name counters, which indicate how many times (out of 24)\n # certain value appears in hourly data.\n value_counts = {k: 0 for k in value_names.keys()}\n\n for value_name in value_names.keys():\n daily_forecast[f'{value_name}_avg'] = 0.0\n daily_forecast[f'{value_name}_min'] = float('inf')\n daily_forecast[f'{value_name}_max'] = float('-inf')\n\n # Calculate daily forecast values from hourly forecasts.\n for hourly_forecast in hourly_forecasts:\n for value_name in value_names.keys():\n orig_value_name = value_names[value_name]\n if is_forecast_number(orig_value_name, hourly_forecast):\n daily_forecast[f'{value_name}_avg'] += hourly_forecast[orig_value_name]\n daily_forecast[f'{value_name}_min'] = min(\n hourly_forecast[orig_value_name],\n daily_forecast[f'{value_name}_min']\n )\n daily_forecast[f'{value_name}_max'] = max(\n hourly_forecast[orig_value_name],\n daily_forecast[f'{value_name}_max']\n )\n value_counts[value_name] += 1\n\n if is_forecast_number('precipAccumulation', hourly_forecast) \\\n and hourly_forecast['precipType'] == 'snow':\n daily_forecast['snow_accumulation'] += hourly_forecast['precipAccumulation']\n elif is_forecast_number('precipIntensity', hourly_forecast) \\\n and is_forecast_number('precipProbability', hourly_forecast):\n daily_forecast['precipitation'] += \\\n hourly_forecast['precipIntensity'] * hourly_forecast['precipProbability']\n\n for value_name, value_count in value_counts.items():\n if value_count:\n # Calculate average.\n daily_forecast[f'{value_name}_avg'] = daily_forecast[f'{value_name}_avg'] / value_count\n else:\n # If value never appeared\n daily_forecast[f'{value_name}_avg'] = 'NULL'\n daily_forecast[f'{value_name}_min'] = 'NULL'\n daily_forecast[f'{value_name}_max'] = 'NULL'\n\n cursor.execute(f'''INSERT INTO weather({', '.join(daily_forecast.keys())})\n VALUES ({', '.join([str(v) for v in daily_forecast.values()])})''')\n\n # IOT data:\n for location in SETTINGS['weather_locations_iot']:\n print(f'\\tPopulating weather: \"{location[\"name\"]}\".')\n\n # Insert location.\n cursor.execute(f'''INSERT INTO locations(name, lat, lng)\n VALUES ('{location['name']}', {location['lat']}, {location['lng']})''')\n location_id = cursor.lastrowid\n\n # Set weather locations for watercourses/aquifers.\n for water_body in [d['body'] for d in water_defs.values()]:\n if water_body in location:\n cursor.execute(f'''UPDATE {water_body}s\n SET location_id = {location_id}\n WHERE name IN ('{\"', '\".join(location[water_body])}')''')\n\n # Set locations for all stations on given water body to match its location.\n cursor.execute(f'''SELECT id\n FROM {water_body}s\n WHERE location_id = {location_id}''')\n ids = [row[0] for row in cursor.fetchall()]\n if len(ids):\n cursor.execute(f'''UPDATE {water_body}_stations\n SET location_id = {location_id}\n WHERE {water_body}_id IN ({', '.join([str(v) for v in ids])})''')\n\n break \n \n file_name = f'''{location['lat']}-{location['lng']}.json'''\n json_path = get_data_path('weather', 'raw', file_name)\n\n # If data file doesn't exist, download it first.\n if not os.path.isfile(json_path):\n with open(json_path, 'wb', encoding=\"utf-8\") as file:\n file.write(read_from_url(location['url'], decode=False))\n \n with open(json_path, 'r', encoding='utf-8') as json_file:\n row_names = {\n \"Sun_duration\": \"sun_duration\",\n \"CloudCover\": \"cloud_cover_avg\",\n \"Percipitation\": \"precipitation\",\n \"New_snow_blanket\": \"snow_accumulation\",\n \"Snow_blanket\": \"snow_depth\",\n \"TemperatureAvg\": \"temperature_avg\",\n \"TemperatureMin\": \"temperature_min\",\n \"TemperatureMax\": \"temperature_max\"\n }\n forecasts = json.load(json_file)\n for forecast in forecasts:\n f = {row_names[k]: forecast[k] for k in row_names.keys()}\n f['location_id'] = location_id\n f['time'] = round(forecast['LastUpdatedEpoch'] / 1000)\n cursor.execute(f'''INSERT INTO weather({', '.join(f.keys())})\n VALUES ({', '.join([str(v) for v in f.values()])})''')", "def dataframe():\n\t#allows function to access station, gmt, and miss_station functions\n global stations\n\tglobal gmt\n\tglobal miss_station\n\t\n\t#read predictor file\n\tcontrol = cfg.read_yaml('../registry/graphs.yaml')\n\tpred_ctrl = cfg.read_yaml(cfg.get_config_path(control.pred_file))\n\tpredd_ctrl = cfg.read_yaml(cfg.get_config_path(control.predd_file))\n\n\t#get file paths and update database\n\tpredictor_file_path = control.predictor_file_path\n\tpredictand_file_path = control.predictand_file_path\n\tpred_file_id = update(predictor_file_path)\n\tpredd_file_id = update(predictand_file_path)\n\t\n\t#store lead time and date range\n\tlead_time = control.lead_time\n\tdate_range = control.date_range\n\n\t#get info for fetch many dates\n\tstart,end,stride = read_pred.parse_range(date_range)\n\tfcst_ref_time = control.date_range[0].split('-')[0][-2:]\n\t\n\t#initialize list of predictors\n\tpred_list = pred_ctrl.predictors\n\tpredictor = []\n\n\t#loops through predictors to build camps data objects\n\tfor entry_dict in pred_list:\n\t\t#formats metadata\n\t\tpred = create.preprocess_entries(entry_dict, fcst_ref_time)\n\t\t\n\t\t#adds info to metadata that's not currently being stored\n\t\tpred.search_metadata['reserved2'] = lead_time*3600\n pred.search_metadata['file_id'] = pred_file_id\n\t\tpred.search_metadata['reserved1'] = 'vector'\n\n\t\t#build camps data objects for each day\n\t\tvariable = fetch_many_dates(predictor_file_path,start,end,stride,pred.search_metadata)\n\t\t\n\t\t#appends all data to single camps object\n\t\tif variable[0] is not None:\n\t\t\tvar = variable[0]\n\t\t\tarrs = []\n\t\t\tfor i in range(len(variable)):\n\t\t\t\tarrs.append(variable[i].data)\n\t\t\tvar.data = np.stack(arrs)\n\t\t\tpredictor.append(var)\n\n\t#initializes list of predictands\n\tpredd_list = predd_ctrl.predictands\n predictand = []\n\t\n\t#loops through predictands to build camps data objects\n for entry_dict in predd_list:\n\t\t#formats metadata\n \tvertical_coordinate = entry_dict.pop('Vertical_Coordinate')\n\t\tentry_dict['file_id'] = predd_file_id\n\n\t\t#build camps objects for each day\n variable = fetch_many_dates(predictand_file_path,start, end, stride, entry_dict)\n\n\t\t#append all data to single camps object\n var = variable[0]\n arrs = []\n for i in range(len(variable)):\n arrs.append(variable[i].data)\n try:\n\t\t\tvar.data = np.stack(arrs)\n\t\t\tpredictand.append(var)\n\t\texcept:\n\t\t\tprint(\"Can't read \" + variable.name)\n\n\t#getting predictor station and time data\n\tpredr = Dataset(predictor_file_path[0])\n\tpredr_stat = predr.variables['station'][:]\n\tif lead_time == 3:\n\t\tpredr_time = predr.variables['OM__phenomenonTimeInstant'][:]\n\telif lead_time == 6:\n\t\tpredr_time = predr.variables['OM__phenomenonTimeInstant1'][:]\n\telif lead_time == 12:\n\t\tpredr_time = predr.variables['OM__phenomenonTimeInstant2'][:]\n\tpredr.close()\n\n\t#reformatting predictor station and time data\n\tpredr_stations = stations(predr_stat)\n\tpredr_gmt = gmt(predr_time)\n\t\n\t#getting predictand station and time data\n\tpredd = Dataset(predictand_file_path[0])\n\tpredd_stat = predd.variables['station'][:]\n\tpredd_time = predd.variables['OM__resultTime'][:]\n\tpredd.close()\n\t\n\t#reformatting predictand station and time data\n\tpredd_stations = stations(predd_stat)\n\tpredd_gmt = gmt(predd_time)\n\n\t#choosing predictand observations that line up with predictor time\n\thour = (predictor[0].metadata['FcstTime_hour']/3600) + lead_time\n\tdays = len(predd_gmt)/24\n\tpredd_hours = [0]*days\n k=0\n for i in range(len(predd_gmt)):\n if i%24 == hour:\n\t\t\tpredd_hours[k]=predd_gmt[i]\n\t\t\tk+=1\n\t\n\t#catches when GFS data doesn't cover the last day of the month\n\tif len(predr_gmt) < len(predd_hours):\n\t\tpredd_hours = predd_hours[:-1]\t\n\t\n\t#find missing stations\n\tmiss_stations = miss_station(predr_stations,predd_stations)\n\tstations = predd_stations\n\t\n\t#station and time array\n\tinfo = [['',''] for k in range(len(predr_gmt)*len(stations))]\n\tfor i in range(len(predr_gmt)):\n\t\tfor j in range(len(stations)):\n\t\t\tk = i*len(stations)+j\n\t\t\tinfo[k][0]=predr_gmt[i]\n\t\t\tinfo[k][1]=stations[j]\n\n\t#create column names\n\tnames = ['']*(len(predictor)+len(predictand)+2)\n\tnames[0]='Time'\n\tnames[1]='Station'\n\n\t#creating array\n\tarr = np.zeros((len(stations)*len(predr_gmt),len(predictor)+len(predictand)))\n\t\n\t#adding predictor data\n\tfor i in range(len(predictor)):\n\t\t#remove lead time and forecast reference time from variable name\n\t\t#and add variable name to column list of final dataframe\n\t\tif lead_time == 12:\n\t\t\tnames[i+2]='GFS_'+predictor[i].get_variable_name()[:-11]\n\t\telse:\n\t\t\t names[i+2]='GFS_'+predictor[i].get_variable_name()[:-10]\n\n\t\t#create pandas dataframe of data and sort alphabetically by station name\n\t\tpredictor[i].data = np.squeeze(predictor[i].data,axis=2)\n\t\tpredictor[i].data = pd.DataFrame(predictor[i].data,columns=predr_stations,index=predr_gmt)\n\t\tpredictor[i].data = predictor[i].data.reindex(sorted(predictor[i].data.columns),axis=1)\n\t\t\n\t\t#remove stations with no predictand data\n\t\tk=0\n\t\ta=miss_stations[:]\n\t\tfor j in predictor[i].data.columns:\n\t\t\tif not a:\n\t\t\t\tbreak\n\t\t\tif j==a[k]:\n\t\t\t\tpredictor[i].data=predictor[i].data.drop(j,axis=1)\n\t\t\t\tdel a[k]\n\t\t\n\t\t#add data to final dataframe\n\t\tfor b in range(len(predr_gmt)):\n\t\t\tfor c in range(len(stations)):\n\t\t\t\tk = b*len(stations)+c\n\t\t\t\tarr[k][i] = predictor[i].data.iloc[b][c]\n\n\t#add predictand data\n\tfor i in range(len(predictand)):\n\t\t#removing extra underscore, adding variable name to column names\n\t\tnames[len(predictor)+2+i]='METAR_'+predictand[i].get_variable_name()[:-1]\n\t\n\t\t#resize array and create pandas dataframe\n\t\tpredictand[i].data = np.squeeze(predictand[i].data,axis=2)\n\t\tpredictand[i].data = pd.DataFrame(predictand[i].data,columns=predd_stations,index=predd_hours)\n\t\tpredictand[i].data = predictand[i].data.reindex(sorted(predictand[i].data.columns),axis=1)\n\t\t\n\t\t#remove extra days of predictand data\n\t\tpredictand[i].data = predictand[i].data.iloc[0:len(predr_time),:]\n\t\t\t\n\t\t#add predictand data to array\n\t\tfor b in range(len(predr_gmt)):\n\t\t\tfor c in range(len(stations)):\n\t\t\t\tk = b*len(stations)+c\n\t\t\t\tval = predictand[i].data.iloc[b][c]\n\t\t\t\t\n\t\t\t\t#catch metar fill data\n\t\t\t\tif val == 9999: \n\t\t\t\t\tval = np.nan\n\t\t\t\tarr[k][len(predictor)+i]=val\n\t\n\t#add station and time data to array and save as csv\n\tdata = np.concatenate([info,arr],axis = 1)\n\tto_save = pd.DataFrame(data,columns=names)\n\tto_save.to_csv(str(start)+'_'+str(end)+'_'+str(lead_time)+'hrs.csv')", "def weather_data(cities, openweathermap_api_key=openweathermap_api_key):\n L = []\n for c in cities:\n res = requests.get(f'http://api.openweathermap.org/data/2.5/weather?q={c}&appid={openweathermap_api_key}&units=imperial')\n L.append(res.json())\n\n df = pd.DataFrame(L)\n df['lon'] = df['coord'].map(op.itemgetter('lon'))\n df['lat'] = df['coord'].map(op.itemgetter('lat'))\n df['Temprature'] = df['main'].map(op.itemgetter('temp'))\n df['Humidity'] = df['main'].map(op.itemgetter('humidity'))\n df['Wind Speed'] = df['wind'].map(op.itemgetter('speed'))\n return df[['name','lon', 'lat','Temprature','Humidity','Wind Speed']]", "def merge_weather_trails(df_weather, df_hike):\n df_trail_year = pd.merge(\n df_hike, df_weather, how='left', left_on=[\n 'closet_station', 'last_year'], right_on=[\n 'name', 'DATE'])\n df_all_clean = df_trail_year.drop(['DATE', 'name'], axis=1)\n return df_all_clean", "def get_weight_df(self) -> pd.DataFrame:\n\n day_to_week = self.calendar_df.set_index(\"d\")[\"wm_yr_wk\"].to_dict()\n weight_df = self.train_df[[\"item_id\", \"store_id\"] + self.weight_columns].set_index([\"item_id\", \"store_id\"])\n weight_df = (weight_df.stack().reset_index().rename(columns = {\"level_2\": \"d\", 0: \"value\"}))\n weight_df[\"wm_yr_wk\"] = weight_df[\"d\"].map(day_to_week)\n weight_df = weight_df.merge(self.sell_prices_df, how = \"left\", on = [\"item_id\", \"store_id\", \"wm_yr_wk\"])\n weight_df[\"value\"] = weight_df[\"value\"] * weight_df[\"sell_price\"]\n weight_df = weight_df.set_index([\"item_id\", \"store_id\", \"d\"]).unstack(level = 2)[\"value\"]\n weight_df = weight_df.loc[zip(self.train_df.item_id, self.train_df.store_id), :].reset_index(drop = True)\n weight_df = pd.concat([self.train_df[self.id_columns], weight_df], axis = 1, sort = False)\n\n weights_map_lst = []\n for group_id in self.group_ids:\n if type(group_id) == str:\n group_id = [group_id]\n\n lv_weight = weight_df.groupby(group_id)[self.weight_columns].sum().sum(axis = 1)\n lv_weight = lv_weight / lv_weight.sum()\n \n if len(group_id) == 2:\n lv_weight.index = pd.Series(lv_weight.index.values).apply(lambda x: \"--\".join(x))\n\n weights_map_lst.append(lv_weight)\n\n weights_df = pd.concat(weights_map_lst) / len(self.group_ids)\n\n return weights_df", "def get_wind_data(zone):\n\n zone = zone[1:len(zone)-1]\n wind_response = {}\n conn = sqlite3.connect(os.path.abspath('database.db'))\n\n # get wind data\n query = \"Select wind_date, wind_speed From wind_velocity Left join fire_danger_zone on wind_velocity.wind_station=fire_danger_zone.fdz_station Where fire_danger_zone.fdz_station == '\" + zone + \"' and wind_velocity.wind_date >= date('2010-01-01') Order by wind_velocity.wind_date;\"\n dataframe = pd.read_sql_query(query, conn) \n wind = dataframe['wind_speed'].values.tolist()\n\n # get dates\n dates = dataframe['wind_date'].values.tolist()\n \n # add data in dictionary \n data_name = 'wind_'+zone\n wind_response[data_name] = wind\n wind_response['labels'] = dates\n \n # return data\n response = jsonify(wind_response)\n response.headers.add('Access-Control-Allow-Origin', '*')\n \n # close database connection\n conn.close()\n return response", "def _get_weather_data(self, lat, long):\n return {}\n try:\n # get the data\n forecast = self.ds.get_forecast(\n lat, long,\n exclude=[weather.HOURLY, weather.MINUTELY,\n weather.DAILY, weather.ALERTS, weather.FLAGS])\n\n # add lat & long to the hourly weather data for composite key in db\n data = forecast.currently\n data.latitude = lat\n data.longitude = long\n data = data.__dict__\n data.pop(\"time\")\n return data\n except Exception as e:\n print(e)\n return None", "def getDataDict(self):\n #code begins here \n return self.__dflst,self.__dfwells" ]
[ "0.62621945", "0.625129", "0.6238696", "0.6196839", "0.61660135", "0.61178386", "0.6031832", "0.60268205", "0.5993915", "0.59827983", "0.59796125", "0.5978958", "0.59702134", "0.5938743", "0.587933", "0.58601356", "0.5849098", "0.5810455", "0.5792647", "0.5791266", "0.5774107", "0.5739626", "0.5733585", "0.5733062", "0.5730819", "0.57010967", "0.5688028", "0.56785464", "0.56747514", "0.56692463" ]
0.7046636
0
Validates an XML document against a schema instance. This function builds an
def validate(xml_document, schema=None, cls=None, path=None, schema_path=None, use_defaults=True, namespaces=None, locations=None, base_url=None, defuse='remote', timeout=300, lazy=False): source, schema = get_context( xml_document, schema, cls, locations, base_url, defuse, timeout, lazy ) schema.validate(source, path, schema_path, use_defaults, namespaces)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def validate(self):\n import os\n\n if self.kind == KDM.INTEROP:\n with open(os.path.join(os.path.dirname(__file__), 'xsd', 'interop.xsd'), 'r') as f:\n schema = f.read()\n elif self.kind == KDM.SMPTE:\n with open(os.path.join(os.path.dirname(__file__), 'xsd', 'smpte.xsd'), 'r') as f:\n schema = f.read()\n\n base_dir = os.getcwd()\n os.chdir(os.path.join(os.path.dirname(__file__), 'xsd'))\n try:\n schema = ET.XMLSchema(ET.XML(schema))\n xmlparser = ET.XMLParser(schema=schema)\n ET.fromstring(self.raw, xmlparser)\n finally:\n os.chdir(base_dir)", "def validate(self, schema=os.path.join(os.path.dirname(__file__), 'am.xsd')):\n return validate_xml(schema, self.path, from_path=True)", "def validate(self, doc, schemaloc=False):\n if not (schemaloc or self._schemalocs):\n raise errors.ValidationError(\n \"No schemas to validate against! Try instantiating \"\n \"XmlValidator with use_schemaloc=True or setting the \"\n \"schema_dir param in __init__\"\n )\n\n root = utils.get_etree_root(doc)\n xsd = self._build_uber_schema(root, schemaloc)\n is_valid = xsd.validate(root)\n\n return XmlValidationResults(is_valid, xsd.error_log)", "def validate_etree(self, etree_xml):\n valid = self.xml_schema.validate(etree_xml)\n return SchemaValidationResult(valid, self.xml_schema.error_log)", "def _validateXML(self, to_be_validated, xsd_model):\n #We parse the XSD model\n xsd_model = StringIO.StringIO(xsd_model)\n xmlschema_doc = etree.parse(xsd_model)\n xmlschema = etree.XMLSchema(xmlschema_doc)\n\n string_to_validate = StringIO.StringIO(to_be_validated)\n\n try:\n document = etree.parse(string_to_validate)\n except (etree.XMLSyntaxError, etree.DocumentInvalid) as e: # pylint: disable=catching-non-exception\n LOG('SlapTool::_validateXML', INFO, \n 'Failed to parse this XML reports : %s\\n%s' % \\\n (to_be_validated, e))\n return False\n\n if xmlschema.validate(document):\n return True\n\n return False", "def validate(self):\n\n # clear any previous xml errors\n clear_error_log()\n if self.schema_file is not None:\n try:\n # Attempt parsing the schema file\n schdoc = parse(self.schema_file)\n except XMLSyntaxError as e:\n # The schema was not parsable XML\n logging.warning('The schema XML file could not be parsed.')\n for item in e.error_log:\n logging.info(item)\n\n return False\n\n try:\n schema = XMLSchema(schdoc)\n except XMLSchemaParseError as e:\n # The schema document is XML, but it's not a schema\n logging.warning(\n 'The schema XML file was parsed, but it does not appear to be a valid XML Schema document.'\n )\n for item in e.error_log:\n logging.info(item)\n\n return False\n\n try:\n # Attempt parsing the data file\n data = parse(self.datafile)\n except XMLSyntaxError as e:\n # The data was not parsable XML\n logging.warning('The data XML file could not be parsed.')\n for item in e.error_log:\n logging.info(item)\n\n return False\n\n if self.schema_file is not None:\n if schema.validate(data):\n self.data = data\n return True\n\n logging.warning(\n 'The data does not conform to the provided schema.')\n for item in schema.error_log:\n logging.info(item)\n\n return False\n\n self.data = data\n\n return True", "def schemaValidateDoc(self, doc):\n if doc is None: doc__o = None\n else: doc__o = doc._o\n ret = libxml2mod.xmlSchemaValidateDoc(self._o, doc__o)\n return ret", "def validate_schema(doc_xml, schema_xml=None):\n doc_dml = deepcopy(doc_xml)\n\n doc_new = etree.Element(doc_xml.tag, nsmap={None: 'http://www.sii.cl/SiiDte'})\n doc_new[:] = doc_xml[:] # move children into new root\n doc_new.attrib.update(doc_xml.attrib) # copy attributes of the root node\n\n # reload xml\n buff = BytesIO(etree.tostring(doc_new, method='c14n'))\n xml = etree.parse(buff).getroot()\n\n if not schema_xml:\n schema_pth = resolve_schema(doc_xml)\n\n with open(schema_pth, 'rb') as fh:\n schema_dml = etree.parse(fh)\n\n schema = etree.XMLSchema(schema_xml)\n schema.assertValid(dml)\n\n return True # if no assertion gets thrown above, we can safely assume a `True` validity. ", "def validate_XML(xml):\n tree = etree.XML(xml)\n schema_tree = etree.XML(SCHEMA_TEMPLATE)\n # Find all unique instances of 'xsi:schemaLocation=\"<namespace> <path-to-schema.xsd> ...\"'\n schema_locations = set(tree.xpath(\"//*/@xsi:schemaLocation\", namespaces={'xsi': XSI}))\n for schema_location in schema_locations:\n # Split namespaces and schema locations ; use strip to remove leading\n # and trailing whitespace.\n namespaces_locations = schema_location.strip().split()\n # Import all found namspace/schema location pairs\n for namespace, location in zip(*[iter(namespaces_locations)] * 2):\n xs_import = etree.Element(XS + \"import\")\n xs_import.attrib['namespace'] = namespace\n xs_import.attrib['schemaLocation'] = location\n schema_tree.append(xs_import)\n # Contstruct the schema\n schema = etree.XMLSchema(schema_tree)\n # Validate!\n schema.assertValid(tree)", "def validate(self, xmlfilename):\n\t\tdata = open(self.xsdfilename, 'rb') \n\t\tschema_root = etree.XML(data.read())\n\t\tschema = etree.XMLSchema(schema_root)\n\t\txmlparser = etree.XMLParser(schema=schema)\n\t\ttry:\n\t\t\twith open(xmlfilename, 'rb') as f:\n\t\t\t\tetree.fromstring(f.read(), xmlparser)\n\t\t\tprint(\"XML file was parsed without errors\")\n\t\t\treturn True\n\t\texcept etree.XMLSchemaError:\n\t\t\tprint(\"Error parsing XML file\")\n\t\t\ttraceback.print_tb()\n\t\t\treturn False", "def validate(self) :\n\t\tif self.doc is not None :\n\t\t\tparser = etree.XMLParser(recover=True, strip_cdata=True)\n\t\t\ttree = etree.XML(self.doc.toxml(), parser)\n\t\t\tdtdFile = self._getDTDFile()\n\t\t\tif dtdFile is not None :\n\t\t\t\tif _existFile(dtdFile) :\n\t\t\t\t\tdtd = etree.DTD(dtdFile)\n\t\t\t\t\tif dtd.validate(tree) :\n\t\t\t\t\t\tself._enrichXML()\n\t\t\t\t\t\treturn True\n\t\t\t\t\telse :\n\t\t\t\t\t\tprint(dtd.error_log.filter_from_errors()[0])\n\t\t\t\t\t\treturn False\n\t\t\t\telse :\n\t\t\t\t\tprint('Unable to find the DTD file ',dtdFile)\n\t\t\t\t\treturn False\n\t\t\telse:\n\t\t\t\tself._enrichXML()\n\t\t\t\treturn True\n\t\telse :\n\t\t\treturn False", "def validate(self, doc):\n return self.schema.validate(doc)", "def schemaValidateDoc(self, ctxt):\n if ctxt is None: ctxt__o = None\n else: ctxt__o = ctxt._o\n ret = libxml2mod.xmlSchemaValidateDoc(ctxt__o, self._o)\n return ret", "def __validate_and_compile(self):\n self.__validate_file(self.__schema_path, \"RNG\")\n\n with open(self.__schema_path) as relax_file_handler:\n\n # Parse schema file\n relax_parsed = etree.parse(relax_file_handler)\n\n # Compile schema file\n self.__compiled = etree.RelaxNG(relax_parsed)", "def validateDocument(self, doc):\n if doc is None: doc__o = None\n else: doc__o = doc._o\n ret = libxml2mod.xmlValidateDocument(self._o, doc__o)\n return ret", "def validate_xml(content, schema_content):\n xml_schema_doc = etree.parse(schema_content)\n xml_schema = etree.XMLSchema(xml_schema_doc)\n xml = etree.parse(StringIO.StringIO(content))\n\n # Validate the content against the schema.\n try:\n xml_schema.assertValid(xml)\n except etree.DocumentInvalid:\n return xml_schema.error_log\n\n return ''", "def xml_validator(self,xml_string):\r\n\r\n try:\r\n schema = etree.XMLSchema(file=XSD_FILE_PATH)\r\n parser = objectify.makeparser(schema=schema)\r\n objectify.fromstring(xml_string, parser)\r\n print(\"XML file has been validated.\")\r\n return True\r\n except XMLSyntaxError:\r\n #handle exception here\r\n print(\"XML file cannot be validated.\")\r\n return False", "def schema_check(self):\n\n try:\n self.schema.assertValid(self.get_content())\n except lxml.etree.DocumentInvalid:\n logger.error(\"PDU failed schema check\")\n for line in self.pretty_print_content().splitlines():\n logger.warning(line)\n raise", "def test_validate_invalid(self):\r\n self.assertEqual(get_tree_and_validate(self.invalid_xml, open(self.SCHEMA, 'r').read()), 0)", "def SchemaValidate(self, xsd):\n ret = libxml2mod.xmlTextReaderSchemaValidate(self._o, xsd)\n return ret", "def validate(cls,corpus,target):\n printWarning(cls,inspect.stack()[0][3],\n \"Preparing data for xsd validation..\")\n xmlstring = corpus.writeToString()\n printWarning(cls,inspect.stack()[0][3],\n \"Prepared\")\n xsd = Validator.validateXSD(xmlstring,target)\n semantic = Validator.validateSemantic(corpus,target)\n valid = (xsd and semantic)\n if not valid:\n printError(cls,inspect.stack()[0][3],\n \"Data not valid\")\n return(valid)", "def validate(self, document):\n self.validator.validate(document)", "def validate(file_in) :\n\tname = str(file_in.name)\n\tif name[-4:] != \".xml\" and name[-4:] != \".XML\" :\n\t\treturn False\n\txsd = open('wcdb/WorldCrises.xsd.xml', 'r')\n\txmlFile = open('wcdb/temp.xml', 'w')\n\txmlFile.write(file_in.read())\n\txmlFile = open('wcdb/temp.xml', 'r')\n\ttry:\n\t\tpsvi = pyxsval.parseAndValidate(\"wcdb/temp.xml\",\n\t\t\t\"wcdb/WorldCrises.xsd.xml\", xmlIfClass=pyxsval.XMLIF_ELEMENTTREE)\n\t\ttree = psvi.getTree()\n\texcept pyxsval.XsvalError, e:\n\t\treturn 'Validation aborted. ' + str(e)\n\texcept GenXmlIfError, e:\n\t\treturn 'Parsing aborted. ' + str(e)\n\texcept Exception as e:\n\t\t# catch all\n\t\treturn 'Exception. ' + str(e)\n\t#handle invalid case\n\treturn tree", "def schemaIsValid(self):\n ret = libxml2mod.xmlSchemaIsValid(self._o)\n return ret", "def validateXSD(cls,xmlstring,target):\n printMessage(cls,inspect.stack()[0][3],\n \"Validating against '%s' XSD..\"%(target))\n\n curdir = os.path.dirname(globals()['__file__'])\n if target==\"new\":\n xsd=\"%s/../bioinfer.xsd\"%curdir\n elif target==\"relaxed\":\n xsd=\"%s/../bioinfer.relaxed.xsd\"%curdir\n elif target==\"compatible\":\n xsd=\"%s/../bioinfer.relaxed.xsd\"%curdir\n else:\n printError(cls,inspect.stack()[0][3],\"Cannot validate '%s' format\"%target)\n return(False)\n \n doc = L.parseDoc(xmlstring)\n schemaCtxt = L.schemaNewParserCtxt(xsd)\n schema = schemaCtxt.schemaParse()\n validatorCtxt = schema.schemaNewValidCtxt()\n\n exitstatus = validatorCtxt.schemaValidateDoc(doc)\n valid = (exitstatus==0)\n if valid:\n printMessage(cls,inspect.stack()[0][3],\"Valid XML\")\n else:\n printError(cls,inspect.stack()[0][3],\"Invalid XML\")\n return(valid)", "def validate(self, schema=None, callback=None):\n return hxl.schema(schema, callback).validate(self)", "def assertValid(self, doc):\n return self.schema.assertValid(doc)", "def validate(self):\n self.logger.debug(\"In validate.\")\n\n document = self._get_raw_doc()\n\n session = iHMPSession.get_session()\n self.logger.info(\"Got iHMP session.\")\n\n (valid, error_message) = session.get_osdf().validate_node(document)\n\n problems = []\n\n if not valid:\n self.logger.info(\"Validation did not succeed for %s.\", __name__)\n problems.append(error_message)\n\n if 'prepared_from' not in self._links.keys():\n problems.append(\"Must add a 'prepared_from' link to a sample.\")\n\n self.logger.debug(\"Number of validation problems: %s.\", len(problems))\n return problems", "def validate():\n description = f\"Validate XML metadata.\"\n parser = argparse.ArgumentParser(\n description=description,\n formatter_class=argparse.ArgumentDefaultsHelpFormatter\n )\n\n help = \"XML file or URL\"\n parser.add_argument('infile', help=help)\n\n help = (\n \"Format ID for metadata standard. If this argument is supplied, \"\n \"only that format ID will be checked. If not, all format IDs will be \"\n \"checked.\"\n )\n parser.add_argument('--format-id',\n help=help,\n choices=d1_scimeta.util.get_supported_format_id_list())\n\n help = \"Verbosity of log messages.\"\n choices = ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL']\n parser.add_argument('-v', '--verbosity', help=help, choices=choices,\n default='INFO')\n\n args = parser.parse_args()\n\n validator = XMLValidator(verbosity=args.verbosity)\n validator.validate(args.infile, format_id=args.format_id)", "def xsd_validator(self):\n return XSDValidator(self.schema)" ]
[ "0.72821254", "0.718917", "0.71431804", "0.7091836", "0.7014281", "0.6909555", "0.6883875", "0.6824659", "0.68070483", "0.6800165", "0.6686416", "0.6628976", "0.66033053", "0.65844876", "0.65131754", "0.6499602", "0.64913964", "0.64175576", "0.6344497", "0.63355154", "0.62918144", "0.6242078", "0.6231448", "0.620066", "0.6188478", "0.61795413", "0.6150463", "0.61201215", "0.6114646", "0.60779333" ]
0.7310048
0
Creates an iterator for the errors generated by the validation of an XML document.
def iter_errors(xml_document, schema=None, cls=None, path=None, schema_path=None, use_defaults=True, namespaces=None, locations=None, base_url=None, defuse='remote', timeout=300, lazy=False): source, schema = get_context( xml_document, schema, cls, locations, base_url, defuse, timeout, lazy ) return schema.iter_errors(source, path, schema_path, use_defaults, namespaces)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def iter_errors(self, obj: ST,\n use_defaults: bool = True,\n namespaces: Optional[NamespacesType] = None,\n max_depth: Optional[int] = None,\n extra_validator: Optional[ExtraValidatorType] = None) \\\n -> Iterator[XMLSchemaValidationError]:\n kwargs: Dict[str, Any] = {\n 'use_defaults': use_defaults,\n 'namespaces': namespaces,\n }\n if max_depth is not None:\n kwargs['max_depth'] = max_depth\n if extra_validator is not None:\n kwargs['extra_validator'] = extra_validator\n\n for result in self.iter_decode(obj, **kwargs):\n if isinstance(result, XMLSchemaValidationError):\n yield result\n else:\n del result", "def test_Validator_iter_errors_two_arguments(self):\n\n validator = validators.Draft7Validator({})\n with self.assertWarns(DeprecationWarning) as w:\n error, = validator.iter_errors(\"foo\", {\"type\": \"number\"})\n\n self.assertEqual(error.validator, \"type\")\n self.assertEqual(w.filename, __file__)\n self.assertTrue(\n str(w.warning).startswith(\n \"Passing a schema to Validator.iter_errors is deprecated \",\n ),\n )", "def test_iter_errors_valid_resume(self):\n errors = list(resumeschema.iter_errors(self.valid_resume))\n self.assertEqual(len(errors), 0)", "def get_style_errors(self):\n # type: () -> Iterable[Tuple[Callable, Tuple[int, int]]]\n if not self.root:\n return\n for node in self.root.in_order_traverse():\n for annotation in node.annotations:\n if issubclass(annotation, DarglintError):\n yield annotation, node.line_numbers", "def validate(self):\n self.logger.debug(\"In validate.\")\n\n document = self._get_raw_doc()\n\n session = iHMPSession.get_session()\n self.logger.info(\"Got iHMP session.\")\n\n (valid, error_message) = session.get_osdf().validate_node(document)\n\n problems = []\n\n if not valid:\n self.logger.info(\"Validation did not succeed for %s.\", __name__)\n problems.append(error_message)\n\n if 'prepared_from' not in self._links.keys():\n problems.append(\"Must add a 'prepared_from' link to a sample.\")\n\n self.logger.debug(\"Number of validation problems: %s.\", len(problems))\n return problems", "def get_errors(self, cases: list) -> iter:\n\t\tfor i, err in zip(self.error_case_indices, self.errors):\n\t\t\t# Default for list is -1\n\t\t\tif i < 0:\n\t\t\t\tbreak\n\t\t\tyield {\"index\": i, \"arguments\": cases[i][0], \"error\": ID_TO_ERROR[err]}", "def run(self) -> Generator[CheckResult, None, None]:\n for visitor_class in self._visitors:\n visiter = visitor_class()\n visiter.visit(self.tree)\n\n for error in visiter.errors:\n lineno, col_offset, message = error.node_items()\n yield lineno, col_offset, message, type(self)", "def validate(self):\n self.logger.debug(\"In validate.\")\n\n document = self._get_raw_doc()\n\n session = iHMPSession.get_session()\n self.logger.info(\"Got iHMP session.\")\n\n (valid, error_message) = session.get_osdf().validate_node(document)\n\n problems = []\n if not valid:\n self.logger.info(\"Validation did not succeed.\")\n problems.append(error_message)\n\n if 'associated_with' not in self._links.keys():\n problems.append(\"Must have a 'associated_with' link to a subject.\")\n\n self.logger.debug(\"Number of validation problems: %s.\", len(problems))\n return problems", "def test_iter_errors_invalid_resume(self):\n errors = list(resumeschema.iter_errors(self.invalid_resume))\n self.assertEqual(len(errors), 3)\n\n self.assertEqual(list(errors[0].path), ['basics'])\n self.assertEqual(\n errors[0].message, 'Additional properties are not allowed (u\\'first_name\\', u\\'last_name\\' were unexpected)'\n )\n\n self.assertEqual(list(errors[1].path), ['basics', 'profiles'])\n self.assertEqual(\n errors[1].message,\n '{u\\'username\\': u\\'neutralthoughts\\', u\\'network\\': u\\'Facebook\\'} is not of type u\\'array\\''\n )\n\n self.assertEqual(list(errors[2].path), ['work'])\n self.assertEqual(\n errors[2].message,\n ('{u\\'website\\': u\\'http://piedpiper.com\\', u\\'startDate\\': u\\'2013-12-01\\', u\\'highlights\\': '\n '[u\\'Build an algorithm\\'], u\\'company\\': u\\'Pied Piper\\', u\\'summary\\': '\n 'u\\'Pied Piper is a multi-platform technology.\\', u\\'position\\': u\\'CEO/President\\'} '\n 'is not of type u\\'array\\'')\n )", "def get_validation_iterator(self) -> tf.contrib.data.Iterator:\n return self.validation.make_initializable_iterator()", "def all_errors(self) -> List[XMLSchemaParseError]:\n errors = []\n for comp in self.iter_components():\n if comp.errors:\n errors.extend(comp.errors)\n return errors", "def test_validate_invalid(self):\r\n self.assertEqual(get_tree_and_validate(self.invalid_xml, open(self.SCHEMA, 'r').read()), 0)", "def errors(self) -> List[Error]:", "def getErrors(self) -> java.util.Collection:\n ...", "def _get_validation_generator(self):\n for data_element in self.validation:\n if self.debug: \n print(\"validating on: {}\".format(data_element))\n \n image, heatmap = self._generate_input_tuple(data_element)\n \n yield (image, heatmap)", "def validate(self):\n for child in self:\n yield from child.validate()", "def validate_etree(self, etree_xml):\n valid = self.xml_schema.validate(etree_xml)\n return SchemaValidationResult(valid, self.xml_schema.error_log)", "def on_validate(\n self,\n ) -> AsyncIteratorOrIterator[None]: # pragma: no cover # pyright: ignore\n yield None", "def get_validation_errors(self):\n return [err.to_dict() for err in self._schema.validator.validation_errors]", "def __next__(self):\n validation_errors = []\n def callback(error):\n \"\"\"\n Collect validation errors\n \"\"\"\n validation_errors.append(error)\n self.schema.callback = callback\n\n \"\"\"\n Read rows until we find an error (unless we're printing all rows)\n \"\"\"\n row = next(self.source)\n while row:\n if self.show_all or not self.schema.validateRow(row):\n # append error data to row\n error_row = copy(row)\n messages = \"\\n\".join(map(lambda e: e.message, validation_errors))\n tags = \"\\n\".join(map(lambda e: e.rule.hxlTag if e.rule else '', validation_errors))\n rows = \"\\n\".join(map(lambda e: str(e.row.sourceRowNumber) if e.row else '', validation_errors))\n columns = \"\\n\".join(map(lambda e: str(e.column.sourceColumnNumber) if e.column else '', validation_errors))\n error_row.values = error_row.values + [messages, tags, rows, columns]\n return error_row\n else:\n row = next(self.source)", "def assert_errors():\n def factory(visitor: BaseVisitor, errors: Sequence[str]):\n assert len(errors) == len(visitor.violations)\n\n for index, error in enumerate(visitor.violations):\n assert error.code == errors[index].code\n\n return factory", "def validate(self):\n try:\n # update _resource to have default values from the schema\n self._resource = self.schema(self._resource)\n except MultipleInvalid as e:\n errors = [format_error(err, self.resource_type) for err in e.errors]\n raise exceptions.ValidationError({'errors': errors})\n\n yield self.check_unique()", "def get_validation_errors(\n self,\n schema_version: Optional[str] = None,\n devel_debug: bool = False,\n ) -> list[ValidationResult]:\n ...", "def validate(self, document):\n self.validator.validate(document)", "def is_failed(doc_dict):\n\n results_xml = os.listdir(os.path.join(config.TOC_OCR_RESULTS, doc_dict['name']))\n \n print(f\"{format(datetime.now(), '%Y-%m-%d %H:%M:%S')} INFO (OCR): Results directory contents for {os.path.join(config.TOC_OCR_RESULTS,doc_dict['name'])}:\")\n print(f\"{format(datetime.now(), '%Y-%m-%d %H:%M:%S')} INFO (OCR): {results_xml}\")\n\n if len(results_xml) == 0:\n raise IOError(f\"{format(datetime.now(), '%Y-%m-%d %H:%M:%S')} ERROR (OCR): Result XML files not found in {os.path.join(config.TOC_OCR_RESULTS, doc_dict['name'])}...\")\n\n for item in results_xml:\n # open XML file and parse it as an ordered dict\n print(f\"{format(datetime.now(), '%Y-%m-%d %H:%M:%S')} INFO (OCR): Found result file: {item}\")\n print(f\"{format(datetime.now(), '%Y-%m-%d %H:%M:%S')} INFO (OCR): Opening result file {os.path.join(config.TOC_OCR_RESULTS, doc_dict['name'], item)}...\")\n with open(os.path.join(config.TOC_OCR_RESULTS, doc_dict['name'], item), mode='rb') as f:\n xml = xmltodict.parse(xml_input=f)\n # print(\"OCR XML: \", xml)\n\n # find XmlResult in the ordered dictionary created by parsing XML file\n result_generator = utility.find_item_in_response(data=xml, key='@IsFailed')\n\n # find IsFailed property in XmlResult ordered dict\n for found_value in result_generator:\n # is_failed_generator = utility.find_item_in_response(data=result, key='@IsFailed')\n #\n # # check the value of IsFailed property\n # for found_value in is_failed_generator:\n # print(\"IS FAILED: \", found_value)\n if found_value == 'true':\n print(f\"{format(datetime.now(), '%Y-%m-%d %H:%M:%S')} INFO (OCR): TRUE RESULT FOUND VALUE: {found_value}\")\n return True\n else:\n print(f\"{format(datetime.now(), '%Y-%m-%d %H:%M:%S')} INFO (OCR ): FALSE RESULT FOUND VALUE: {found_value}\")\n return False", "def is_document_related(err):\r\n errors = xml.parsers.expat.errors\r\n err_str = xml.parsers.expat.ErrorString(err.code)\r\n\r\n # All errors in the expat.errors-module in Python 2.7.2, with\r\n # those that seem related to internal errors commented away.\r\n return err_str in (\r\n #errors.XML_ERROR_ABORTED,\r\n #errors.XML_ERROR_ASYNC_ENTITY,\r\n errors.XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF,\r\n errors.XML_ERROR_BAD_CHAR_REF,\r\n errors.XML_ERROR_BINARY_ENTITY_REF,\r\n #errors.XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING,\r\n errors.XML_ERROR_DUPLICATE_ATTRIBUTE,\r\n #errors.XML_ERROR_ENTITY_DECLARED_IN_PE,\r\n #errors.XML_ERROR_EXTERNAL_ENTITY_HANDLING,\r\n #errors.XML_ERROR_FEATURE_REQUIRES_XML_DTD,\r\n #errors.XML_ERROR_FINISHED,\r\n errors.XML_ERROR_INCOMPLETE_PE,\r\n errors.XML_ERROR_INCORRECT_ENCODING,\r\n errors.XML_ERROR_INVALID_TOKEN,\r\n errors.XML_ERROR_JUNK_AFTER_DOC_ELEMENT,\r\n errors.XML_ERROR_MISPLACED_XML_PI,\r\n #errors.XML_ERROR_NOT_STANDALONE,\r\n #errors.XML_ERROR_NOT_SUSPENDED,\r\n errors.XML_ERROR_NO_ELEMENTS,\r\n #errors.XML_ERROR_NO_MEMORY,\r\n errors.XML_ERROR_PARAM_ENTITY_REF,\r\n errors.XML_ERROR_PARTIAL_CHAR,\r\n errors.XML_ERROR_PUBLICID,\r\n errors.XML_ERROR_RECURSIVE_ENTITY_REF,\r\n #errors.XML_ERROR_SUSPENDED,\r\n #errors.XML_ERROR_SUSPEND_PE,\r\n errors.XML_ERROR_SYNTAX,\r\n errors.XML_ERROR_TAG_MISMATCH,\r\n #errors.XML_ERROR_TEXT_DECL,\r\n #errors.XML_ERROR_UNBOUND_PREFIX,\r\n errors.XML_ERROR_UNCLOSED_CDATA_SECTION,\r\n errors.XML_ERROR_UNCLOSED_TOKEN,\r\n #errors.XML_ERROR_UNDECLARING_PREFIX,\r\n errors.XML_ERROR_UNDEFINED_ENTITY,\r\n #errors.XML_ERROR_UNEXPECTED_STATE,\r\n errors.XML_ERROR_UNKNOWN_ENCODING,\r\n errors.XML_ERROR_XML_DECL)", "def run(self):\n validator_predicates = {\n validator_predicate\n for constraint_block in self._validator_predicates_deriver()\n for validator_predicate in constraint_block\n }\n for node in ast.walk(self.__ast):\n if all([validator_predicate(\n node=node, knowledge=self.__knowledge_template\n ) for validator_predicate in validator_predicates]):\n try:\n yield Result(\n name=self.__name,\n line=node.lineno, column=node.col_offset\n )\n except AttributeError:\n pass", "def validation_errors(self):\n return self._validation_errors", "def errors(self):\n raise NotImplementedError", "def test_invalid_xml(self):\r\n with self.assertRaises(Exception):\r\n self.build_problem(type=\"invalidtextgroup\")" ]
[ "0.65945137", "0.6228645", "0.62281376", "0.608026", "0.60769504", "0.59669846", "0.59493446", "0.59328353", "0.5893584", "0.5766017", "0.57601035", "0.57579696", "0.5728756", "0.5700199", "0.55876803", "0.5542821", "0.5485655", "0.54817843", "0.5470813", "0.54597706", "0.54509056", "0.54370064", "0.54354614", "0.5435178", "0.5392728", "0.5374179", "0.5367362", "0.53573596", "0.5331072", "0.52863425" ]
0.7550698
0
Decodes an XML document to a Python's nested dictionary. The decoding is based on an XML Schema class instance. For default the document is validated during
def to_dict(xml_document, schema=None, cls=None, path=None, process_namespaces=True, locations=None, base_url=None, defuse='remote', timeout=300, lazy=False, **kwargs): source, schema = get_context( xml_document, schema, cls, locations, base_url, defuse, timeout, lazy ) return schema.decode(source, path=path, process_namespaces=process_namespaces, **kwargs)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def load(self, xml):\n\n # If the argument is a etree Element, use it as the tree root. This allows nesting of schemas\n if isinstance(xml, etree._Element):\n tree = xml\n\n # If the argument is a string, parse it using lxml.etree.fromstring()\n else:\n tree = etree.fromstring(xml)\n\n # Extract data using the schema's fields\n data = self.dict_type()\n ignore_missing = self.ignore_missing\n\n for name, field in self._fields.items():\n try:\n data[name] = field.load(tree)\n except MissingFieldError as e:\n # Note the use of \"is True\" below, this on purpose\n if field.required is True or not ignore_missing:\n raise e\n\n # Post-processing\n data = self.post_load(data)\n if not isinstance(data, (self.dict_type, dict)):\n raise TypeError(f'post_load() must return a dict or dict-like object, not {type(data)}')\n\n return data", "def load_xml_doc_as_object(xml_path, schema_path):\n root_element = load_xml_from_file(xml_path, schema_path)\n if root_element is None:\n return None\n else:\n return convert_element_to_object(root_element)", "def xml2dict( xml, sanitize=True, prefix=None):\n \n \n #Decode to avert parsing errors as some software dump large text\n #fields into the file that occasionally contain erronious chars\n xml=xml.decode('utf-8', errors='ignore')\n\n \n return etree2dict(etree.fromstring(xml), sanitize, prefix)", "def from_etree(self, data):\r\n if data.tag == 'request':\r\n # if \"object\" or \"objects\" exists, return deserialized forms.\r\n elements = data.getchildren()\r\n for element in elements:\r\n if element.tag in ('object', 'objects'):\r\n return self.from_etree(element)\r\n return dict((element.tag, self.from_etree(element)) for element in elements)\r\n elif data.tag == 'object' or data.get('type') == 'hash':\r\n return dict((element.tag, self.from_etree(element)) for element in data.getchildren())\r\n elif data.tag == 'objects' or data.get('type') == 'list':\r\n return [self.from_etree(element) for element in data.getchildren()]\r\n else:\r\n type_string = data.get('type')\r\n if type_string in ('string', None):\r\n return data.text\r\n elif type_string == 'integer':\r\n return int(data.text)\r\n elif type_string == 'float':\r\n return float(data.text)\r\n elif type_string == 'boolean':\r\n if data.text == 'True':\r\n return True\r\n else:\r\n return False\r\n else:\r\n return None", "def dict(self):\n return xmltodict.parse(str(self))", "def convert_xml_to_object(file_content):\n object = xmltodict.parse(file_content, dict_constructor=dict)\n print(object)\n return object", "def test_xml_to_dict_and_back(self):\n # etree_to_dict(e) and dict_to_etree(d)\n e = open(EXAMPLE_SECTION_FILENAME, 'r').read()\n e = ET.XML(e)\n d = etree_to_dict(e)\n\n if SHOW_RESULTS:\n print(d)\n\n e = dict_to_xml_str(d)\n e = prettify(e)\n\n if SHOW_RESULTS:\n print(e)\n\n xml_file = StringIO(unicode(e))\n self.assertEqual(verify_files(xml_file, open(SECTION_DTD_FILENAME, 'r')), True)", "def _decode_dictionary(data, sub=False):\n\n main_dict = {}\n\n if sub:\n # We are decoding a sub-dictionary, XML is assumed compliant\n tree = data\n else:\n fixed_data = XML_Fix(data)\n tree = ET.fromstring(fixed_data) \n\n for child in tree:\n for pair in child:\n if len(pair) == 2:\n key = _decode_value(pair[0].attrib['Value'])\n val = None\n if 'Type' in pair[1].attrib: \n collection_type = pair[1].attrib['Type']\n if collection_type == 'elsystem.collections.dictionary': # Handle sub-dictionary\n val = _decode_dictionary(data=pair[1], sub=True)\n elif collection_type == 'elsystem.collections.vector': # Handle sub-vector\n val = _decode_vector(data=pair[1], sub=True)\n else: # Handle normal pair\n val = _decode_value( pair[1].attrib['Value'] )\n main_dict[key] = val\n\n return main_dict", "def test_parser_to_dict(self):\n xml = \"\"\"\\\n<foo>\n <bar>baz</bar>\n <quz>\n <wow>works!</wow>\n </quz>\n</foo>\n\"\"\"\n d = x.to_dict(xml, {})\n assert d.bar.text_ == u'baz'\n assert d.quz.wow.text_ == u'works!'", "def load_schema(self):\n\n schema = {\n \"type\": \"object\",\n \"properties\": {}\n }\n\n msd = self.parse_xml(self.schema_path)\n for concept in msd.findall('.//Concept'):\n concept_id = self.alter_key(concept.attrib['id'])\n self.add_item_to_field_order(concept_id)\n concept_name = concept.find('./Name').text\n concept_description = concept.find('./Description').text\n parent = concept.find('./Parent/Ref')\n key_parts = [concept_id, concept_id] if parent is None else [parent.attrib['id'], concept_id]\n translation_key = '.'.join(key_parts)\n jsonschema_field = {\n 'type': ['string', 'null'],\n 'title': concept_name,\n 'description': concept_description,\n 'translation_key': translation_key,\n }\n if self.scope is not None:\n jsonschema_field['scope'] = self.scope\n schema['properties'][concept_id] = jsonschema_field\n\n self.schema = schema", "def test_xml_to_dict(self):\n xml = \"\"\"\n <a\n xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"\n xmlns:nm=\"s\"\n >\n <b m=\"g\">\n b\n </b>\n <c nm:nm=\"update\">\n <f>1</f>\n <e>str</e>\n <d>1</d>\n <d>2</d>\n <d>3</d>\n </c>\n </a>\n \"\"\"\n xmlns = {\n \"_\": utils.NETCONF_NAMESPACE\n }\n result = utils.generate_dict_node(etree.XML(xml), xmlns)\n # check dict\n self.assertDictEqual(\n self.SIMPLE_DICT,\n result\n )\n # check xmlns\n self.assertEqual(\n {\n '_': utils.NETCONF_NAMESPACE,\n 'nm': 's'\n }, xmlns\n )", "def iter_decode(self, elem, validation='lax', **kwargs):\n if self.abstract:\n reason = \"cannot use an abstract element for validation\"\n yield self.validation_error(validation, reason, elem, **kwargs)\n\n try:\n namespaces = kwargs['namespaces']\n except KeyError:\n namespaces = None\n\n try:\n level = kwargs['level']\n except KeyError:\n level = kwargs['level'] = 0\n\n try:\n identities = kwargs['identities']\n except KeyError:\n identities = kwargs['identities'] = {}\n\n self.start_identities(identities)\n\n try:\n converter = kwargs['converter']\n except KeyError:\n converter = kwargs['converter'] = self.schema.get_converter(**kwargs)\n else:\n if converter is not None and not isinstance(converter, XMLSchemaConverter):\n converter = kwargs['converter'] = self.schema.get_converter(**kwargs)\n\n try:\n pass # self.check_dynamic_context(elem, **kwargs) TODO: dynamic schema load\n except XMLSchemaValidationError as err:\n yield self.validation_error(validation, err, elem, **kwargs)\n\n inherited = kwargs.get('inherited')\n value = content = attributes = None\n nilled = False\n\n # Get the instance effective type\n xsd_type = self.get_type(elem, inherited)\n if XSI_TYPE in elem.attrib:\n type_name = elem.attrib[XSI_TYPE].strip()\n try:\n xsd_type = self.maps.get_instance_type(type_name, xsd_type, namespaces)\n except (KeyError, TypeError) as err:\n yield self.validation_error(validation, err, elem, **kwargs)\n else:\n if self.identities:\n xpath_element = XPathElement(self.name, xsd_type)\n for identity in self.identities.values():\n context = IdentityXPathContext(self.schema, item=xpath_element)\n for e in identity.selector.token.select_results(context):\n if e not in identity.elements:\n identity.elements[e] = None\n\n if xsd_type.is_blocked(self):\n reason = \"usage of %r is blocked\" % xsd_type\n yield self.validation_error(validation, reason, elem, **kwargs)\n\n if xsd_type.abstract:\n yield self.validation_error(validation, \"%r is abstract\", elem, **kwargs)\n if xsd_type.is_complex() and self.xsd_version == '1.1':\n kwargs['id_list'] = [] # Track XSD 1.1 multiple xs:ID attributes/children\n\n content_decoder = xsd_type.content if xsd_type.is_complex() else xsd_type\n\n # Decode attributes\n attribute_group = self.get_attributes(xsd_type)\n for result in attribute_group.iter_decode(elem.attrib, validation, **kwargs):\n if isinstance(result, XMLSchemaValidationError):\n yield self.validation_error(validation, result, elem, **kwargs)\n else:\n attributes = result\n\n if self.inheritable and any(name in self.inheritable for name in elem.attrib):\n if inherited:\n inherited = inherited.copy()\n inherited.update((k, v) for k, v in elem.attrib.items() if k in self.inheritable)\n else:\n inherited = {k: v for k, v in elem.attrib.items() if k in self.inheritable}\n kwargs['inherited'] = inherited\n\n # Checks the xsi:nil attribute of the instance\n if XSI_NIL in elem.attrib:\n xsi_nil = elem.attrib[XSI_NIL].strip()\n if not self.nillable:\n reason = \"element is not nillable.\"\n yield self.validation_error(validation, reason, elem, **kwargs)\n elif xsi_nil not in {'0', '1', 'false', 'true'}:\n reason = \"xsi:nil attribute must have a boolean value.\"\n yield self.validation_error(validation, reason, elem, **kwargs)\n elif xsi_nil in ('0', 'false'):\n pass\n elif self.fixed is not None:\n reason = \"xsi:nil='true' but the element has a fixed value.\"\n yield self.validation_error(validation, reason, elem, **kwargs)\n elif elem.text is not None or len(elem):\n reason = \"xsi:nil='true' but the element is not empty.\"\n yield self.validation_error(validation, reason, elem, **kwargs)\n else:\n nilled = True\n\n if xsd_type.is_empty() and elem.text and xsd_type.normalize(elem.text):\n reason = \"character data is not allowed because content is empty\"\n yield self.validation_error(validation, reason, elem, **kwargs)\n\n if nilled:\n pass\n elif xsd_type.model_group is not None:\n for assertion in xsd_type.assertions:\n for error in assertion(elem, **kwargs):\n yield self.validation_error(validation, error, **kwargs)\n\n for result in content_decoder.iter_decode(elem, validation, **kwargs):\n if isinstance(result, XMLSchemaValidationError):\n yield self.validation_error(validation, result, elem, **kwargs)\n else:\n content = result\n\n if len(content) == 1 and content[0][0] == 1:\n value, content = content[0][1], None\n\n if self.fixed is not None and \\\n (len(elem) > 0 or value is not None and self.fixed != value):\n reason = \"must have the fixed value %r\" % self.fixed\n yield self.validation_error(validation, reason, elem, **kwargs)\n\n else:\n if len(elem):\n reason = \"a simple content element can't have child elements.\"\n yield self.validation_error(validation, reason, elem, **kwargs)\n\n text = elem.text\n if self.fixed is not None:\n if text is None:\n text = self.fixed\n elif text == self.fixed:\n pass\n elif not strictly_equal(xsd_type.text_decode(text),\n xsd_type.text_decode(self.fixed)):\n reason = \"must have the fixed value %r\" % self.fixed\n yield self.validation_error(validation, reason, elem, **kwargs)\n\n elif not text and self.default is not None and kwargs.get('use_defaults'):\n text = self.default\n\n if xsd_type.is_complex():\n for assertion in xsd_type.assertions:\n for error in assertion(elem, value=text, **kwargs):\n yield self.validation_error(validation, error, **kwargs)\n\n if text and content_decoder.is_list():\n value = text.split()\n else:\n value = text\n\n elif xsd_type.is_notation():\n if xsd_type.name == XSD_NOTATION_TYPE:\n msg = \"cannot validate against xs:NOTATION directly, \" \\\n \"only against a subtype with an enumeration facet\"\n yield self.validation_error(validation, msg, text, **kwargs)\n elif not xsd_type.enumeration:\n msg = \"missing enumeration facet in xs:NOTATION subtype\"\n yield self.validation_error(validation, msg, text, **kwargs)\n\n if text is None:\n for result in content_decoder.iter_decode('', validation, **kwargs):\n if isinstance(result, XMLSchemaValidationError):\n yield self.validation_error(validation, result, elem, **kwargs)\n if 'filler' in kwargs:\n value = kwargs['filler'](self)\n else:\n for result in content_decoder.iter_decode(text, validation, **kwargs):\n if isinstance(result, XMLSchemaValidationError):\n yield self.validation_error(validation, result, elem, **kwargs)\n elif result is None and 'filler' in kwargs:\n value = kwargs['filler'](self)\n else:\n value = result\n\n if 'value_hook' in kwargs:\n value = kwargs['value_hook'](value, xsd_type)\n elif isinstance(value, (int, float, list)) or value is None:\n pass\n elif isinstance(value, str):\n if value.startswith('{') and xsd_type.is_qname():\n value = text\n elif isinstance(value, Decimal):\n try:\n value = kwargs['decimal_type'](value)\n except (KeyError, TypeError):\n pass\n elif isinstance(value, (AbstractDateTime, Duration)):\n if not kwargs.get('datetime_types'):\n value = str(value) if text is None else text.strip()\n elif isinstance(value, AbstractBinary):\n if not kwargs.get('binary_types'):\n value = str(value)\n\n if converter is not None:\n element_data = ElementData(elem.tag, value, content, attributes)\n yield converter.element_decode(element_data, self, xsd_type, level)\n elif not level:\n yield ElementData(elem.tag, value, None, attributes)\n\n if content is not None:\n del content\n\n # Collects fields values for identities that refer to this element.\n for identity, counter in identities.items():\n if not counter.enabled:\n continue\n elif self in identity.elements:\n xsd_element = self\n elif self.ref in identity.elements:\n xsd_element = self.ref\n else:\n continue\n\n try:\n if xsd_type is self.type:\n xsd_fields = identity.elements[xsd_element]\n if xsd_fields is None:\n xsd_fields = identity.get_fields(xsd_element)\n identity.elements[xsd_element] = xsd_fields\n else:\n xsd_element = self.copy()\n xsd_element.type = xsd_type\n xsd_fields = identity.get_fields(xsd_element)\n\n if all(x is None for x in xsd_fields):\n continue\n fields = identity.get_fields(elem, namespaces, decoders=xsd_fields)\n except (XMLSchemaValueError, XMLSchemaTypeError) as err:\n yield self.validation_error(validation, err, elem, **kwargs)\n else:\n if any(x is not None for x in fields) or nilled:\n try:\n counter.increase(fields)\n except ValueError as err:\n yield self.validation_error(validation, err, elem, **kwargs)\n\n # Apply non XSD optional validations\n if 'extra_validator' in kwargs:\n try:\n result = kwargs['extra_validator'](elem, self)\n except XMLSchemaValidationError as err:\n yield self.validation_error(validation, err, elem, **kwargs)\n else:\n if isinstance(result, GeneratorType):\n for error in result:\n yield self.validation_error(validation, error, elem, **kwargs)\n\n # Disable collect for out of scope identities and check key references\n if 'max_depth' not in kwargs:\n for identity in self.identities.values():\n counter = identities[identity]\n counter.enabled = False\n if isinstance(identity, XsdKeyref):\n for error in counter.iter_errors(identities):\n yield self.validation_error(validation, error, elem, **kwargs)\n elif level:\n self.stop_identities(identities)", "def test_etree_to_dict(self):\r\n person_d = importer.etree_to_dict(self.person_tree.getroot())\r\n assert person_d == {\r\n 'world-crises': [\r\n {'crises': []},\r\n {'organizations': []},\r\n {'people': [\r\n {'person': [\r\n {'name': 'Bob TestPerson'},\r\n {'alternate-names': 'TestDude'},\r\n {'kind': 'TestPersonKind'},\r\n {'description': 'PersonTestDescription'},\r\n {'location': [\r\n {'city': 'Test Person City'},\r\n {'country': 'United States'}]},\r\n {'images': [\r\n {'image': [\r\n {'source': 'http://www.testimage.com'},\r\n {'description': 'Description of TestImage'}]}]},\r\n {'maps': [\r\n {'map': [\r\n {'source': 'http://maps.google.com'},\r\n {'description': 'Map Description'}]}]},\r\n {'videos': [{'youtube': 'r_8om4dsEmw'}]},\r\n {'social': [{'twitter': '@billgates'}]},\r\n {'citations': [\r\n {'citation': [\r\n {'source': 'http://en.wikipedia.org/wiki/Test'},\r\n {'description': 'Wiki'}]}]},\r\n {'external-links': [\r\n {'external-link': [\r\n {'source': 'http://www.zombo.com/'},\r\n {'description': 'Test Link'}]}]}],\r\n 'id': 'p-algore'}]}]}", "def to_dict(self):\n result = {}\n\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n if issubclass(AutodetectDocumentValidationResult, dict):\n for key, value in self.items():\n result[key] = value\n\n return result", "def _deserialize(self):\n try:\n self._as_dict = yaml.load(self.path)\n except ScannerError as e:\n raise exc.ContentSerializeError(self, self.path, e.problem)", "def _deserialize_record(self, schema, annotated_datum):\n if not isinstance(annotated_datum, dict):\n raise AvroTypeException(schema, annotated_datum)\n\n result = {}\n for field in schema.fields:\n val = self._deserialize_data(field.type, annotated_datum.get(field.name))\n if val:\n result[field.name] = val\n return result", "def feedparser_to_dict(self, nested_dict):\n if type(nested_dict) == bytes:\n return str(nested_dict)\n if type(nested_dict) == list:\n return [self.feedparser_to_dict(thing) for thing in nested_dict]\n if not type(nested_dict) == feedparser.FeedParserDict:\n return nested_dict\n return {k: self.feedparser_to_dict(v) for k, v in nested_dict.items()}", "def parse_book_record(root) -> dict:\n\n doc = {\n \"abstract\": \"\",\n \"pmid\": \"\",\n \"title\": \"\",\n \"authors\": [],\n \"pub_date\": \"\",\n \"journal_iso_title\": \"\",\n \"journal_title\": \"\",\n \"doi\": \"\",\n \"compounds\": [],\n \"mesh\": [],\n }\n\n doc[\"pmid\"] = root.xpath(\".//PMID/text()\")[0]\n\n doc[\"title\"] = next(iter(root.xpath(\".//BookTitle/text()\")))\n\n doc[\"authors\"] = []\n for author in root.xpath(\".//Author\"):\n last_name = next(iter(author.xpath(\"LastName/text()\")), \"\")\n first_name = next(iter(author.xpath(\"ForeName/text()\")), \"\")\n initials = next(iter(author.xpath(\"Initials/text()\")), \"\")\n if not first_name and initials:\n first_name = initials\n doc[\"authors\"].append(f\"{last_name}, {first_name}\")\n\n pub_year = next(iter(root.xpath(\".//Book/PubDate/Year/text()\")), None)\n pub_mon = next(iter(root.xpath(\".//Book/PubDate/Month/text()\")), \"Jan\")\n pub_day = next(iter(root.xpath(\".//Book/PubDate/Day/text()\")), \"01\")\n medline_date = next(\n iter(root.xpath(\".//Journal/JournalIssue/PubDate/MedlineDate/text()\")), None\n )\n\n pub_date = process_pub_date(pub_year, pub_mon, pub_day, medline_date)\n\n doc[\"pub_date\"] = pub_date\n\n for abstracttext in root.xpath(\".//Abstract/AbstractText\"):\n abstext = node_text(abstracttext)\n\n label = abstracttext.get(\"Label\", None)\n if label:\n doc[\"abstract\"] += f\"{label}: {abstext}\\n\"\n else:\n doc[\"abstract\"] += f\"{abstext}\\n\"\n\n doc[\"abstract\"] = doc[\"abstract\"].rstrip()\n\n return doc", "def ingest_xml_body(request):\n try:\n data = xmltodict.parse(str(request.body, encoding='utf-8'))\n except Exception as e:\n log.error(log.exc(e))\n return None\n return data", "def parseDocument(self):\n ret = libxml2mod.xmlParseDocument(self._o)\n return ret", "def _decode_struct(\n data_type, obj, alias_validators, strict, old_style, for_msgpack):\n if obj is None and data_type.has_default():\n return data_type.get_default()\n elif not isinstance(obj, dict):\n raise bv.ValidationError('expected object, got %s' %\n bv.generic_type_name(obj))\n if strict:\n for key in obj:\n if (key not in data_type.definition._all_field_names_ and\n not key.startswith('.tag')):\n raise bv.ValidationError(\"unknown field '%s'\" % key)\n ins = data_type.definition()\n _decode_struct_fields(\n ins, data_type.definition._all_fields_, obj, alias_validators, strict,\n old_style, for_msgpack)\n # Check that all required fields have been set.\n data_type.validate_fields_only(ins)\n return ins", "def to_xml_dict(self):\n self._check_required_fields()\n\n root = odict[\n \"r:import\": odict[\n \"@xmlns:r\": \"http://resolver.nkp.cz/v3/\",\n \"r:monograph\": odict[\n \"r:titleInfo\": odict[\n \"r:title\": self.title,\n ],\n ],\n ]\n ]\n mono_root = root[\"r:import\"][\"r:monograph\"]\n\n # subtitle\n MonographComposer._assign_pattern(\n mono_root[\"r:titleInfo\"],\n \"r:subTitle\",\n self.subtitle\n )\n\n # handle ccnb, isbn, uuid\n self._add_identifier(mono_root, \"ccnb\")\n self._add_identifier(mono_root, \"isbn\")\n self._add_identifier(mono_root, \"other_id\", out=\"otherId\")\n\n # add form of the book\n MonographComposer._assign_pattern(\n mono_root,\n \"r:documentType\",\n self.document_type\n )\n\n mono_root[\"r:digitalBorn\"] = \"true\" if self.digital_born else \"false\"\n\n if self.author:\n mono_root[\"r:primaryOriginator\"] = odict[\n \"@type\": \"AUTHOR\",\n \"#text\": self.author\n ]\n\n if any([self.place, self.publisher, self.year]):\n publ = odict()\n\n MonographComposer._assign_pattern(\n publ,\n \"r:publisher\",\n self.publisher\n )\n MonographComposer._assign_pattern(publ, \"r:place\", self.place)\n MonographComposer._assign_pattern(publ, \"r:year\", self.year)\n\n mono_root[\"r:publication\"] = publ\n\n if self.format:\n format_dict = MonographComposer._create_path(\n root,\n odict,\n [\n \"r:import\",\n \"r:digitalDocument\",\n \"r:technicalMetadata\",\n \"r:format\",\n ]\n )\n\n format_dict[\"#text\"] = self.format\n\n return root", "def voc_xml_to_dict(xml_path):\n\n xml = etree.parse(xml_path)\n root = xml.getroot()\n image_name = root.find('filename').text\n labels = []\n boxes = []\n\n for obj in root.findall('object'):\n labels.append(obj.find('name').text)\n bbox = obj.find('bndbox')\n bounds = [\n float(bbox.find('xmin').text),\n float(bbox.find('ymin').text),\n float(bbox.find('xmax').text),\n float(bbox.find('ymax').text)\n ]\n boxes.append(bounds)\n\n return {\n 'image': image_name,\n 'labels': labels,\n 'boxes': boxes,\n }", "def recursive_parse_xml_to_dict(xml):\n if not xml:\n return {xml.tag: xml.text}\n result = {}\n for child in xml:\n child_result = recursive_parse_xml_to_dict(child)\n if child.tag != 'object':\n result[child.tag] = child_result[child.tag]\n else:\n if child.tag not in result:\n result[child.tag] = []\n result[child.tag].append(child_result[child.tag])\n return {xml.tag: result}", "def xmlToValidateObject(validateXML):\n\n entryRoot = etree.XML(validateXML)\n if entryRoot is None:\n raise ValueError(\"Unable to parse uploaded XML\")\n # parse XML\n contentElement = entryRoot.xpath(\"*[local-name() = 'content']\")[0]\n validateXML = contentElement.xpath(\"*[local-name() = 'validate']\")[0]\n identifier = validateXML.xpath(\n \"*[local-name() = 'identifier']\")[0].text.strip()\n\n last_verified = validateXML.xpath(\n \"*[local-name() = 'last_verified']\")[0].text.strip()\n last_verified = parser.parse(last_verified)\n\n last_verified_status = validateXML.xpath(\n \"*[local-name() = 'last_verified_status']\")[0].text.strip()\n\n priority_change_date = validateXML.xpath(\n \"*[local-name() = 'priority_change_date']\")[0].text.strip()\n priority_change_date = parser.parse(priority_change_date)\n\n priority = validateXML.xpath(\n \"*[local-name() = 'priority']\")[0].text.strip()\n\n server = validateXML.xpath(\"*[local-name() = 'server']\")[0].text.strip()\n\n # make the object and return\n validate = Validate(\n identifier=identifier,\n last_verified=last_verified,\n last_verified_status=last_verified_status,\n priority_change_date=priority_change_date,\n priority=priority,\n server=server,\n )\n return validate", "def _deserialize_map(self, schema, annotated_datum):\n if not isinstance(annotated_datum, dict):\n raise AvroTypeException(schema, annotated_datum)\n deserialize = functools.partial(self._deserialize_data, schema.values)\n return dict((key, deserialize(value)) for key, value in six.iteritems(annotated_datum))", "def deserialize(self, data, schema, **kwargs):\n return self.serializer.load(data, schema, **kwargs)", "def validate(self):\n import os\n\n if self.kind == KDM.INTEROP:\n with open(os.path.join(os.path.dirname(__file__), 'xsd', 'interop.xsd'), 'r') as f:\n schema = f.read()\n elif self.kind == KDM.SMPTE:\n with open(os.path.join(os.path.dirname(__file__), 'xsd', 'smpte.xsd'), 'r') as f:\n schema = f.read()\n\n base_dir = os.getcwd()\n os.chdir(os.path.join(os.path.dirname(__file__), 'xsd'))\n try:\n schema = ET.XMLSchema(ET.XML(schema))\n xmlparser = ET.XMLParser(schema=schema)\n ET.fromstring(self.raw, xmlparser)\n finally:\n os.chdir(base_dir)", "def recursive_parse_xml_to_dict(xml):\n if not xml:\n return {xml.tag: xml.text}\n result = {}\n for child in xml:\n child_result = recursive_parse_xml_to_dict(child)\n if child.tag != 'object':\n result[child.tag] = child_result[child.tag]\n else:\n if child.tag not in result:\n result[child.tag] = []\n result[child.tag].append(child_result[child.tag])\n return {xml.tag: result}", "def schemaParse(self):\n ret = libxml2mod.xmlSchemaParse(self._o)\n if ret is None:raise parserError('xmlSchemaParse() failed')\n __tmp = Schema(_obj=ret)\n return __tmp" ]
[ "0.5854179", "0.58091354", "0.56237924", "0.5511665", "0.5475656", "0.54162705", "0.5331637", "0.53209865", "0.52236366", "0.51572007", "0.5124347", "0.50794935", "0.50342417", "0.5022833", "0.49436992", "0.49308828", "0.4928609", "0.49279907", "0.49251303", "0.49134055", "0.4910086", "0.4892274", "0.48854613", "0.4866924", "0.48540968", "0.4848987", "0.48438644", "0.48086712", "0.4806509", "0.48021236" ]
0.72029346
0
Load a PLY file.
def load_plyfile(filename): plydata = plyfile.PlyData.read(filename) return plydata
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def load_source(filename):\n with open(filename, 'r') as f:\n lexer.input(f.read())\n lexer.lineno = 1\n lexer.provenance = f'file \"{filename}\"'", "def load(self, path):\n parameters = paddle.load(path)\n self.set_dict(parameters)", "def load(path):\n pass", "def load_ply(ply_file):\n reader = vtk.vtkPLYReader()\n reader.SetFileName(ply_file)\n reader.Update()\n\n ply_mapper = vtk.vtkPolyDataMapper()\n ply_mapper.SetInputConnection(reader.GetOutputPort())\n\n actor = vtk.vtkActor()\n actor.SetMapper(ply_mapper)\n return actor", "def _load_parser_file(self, filename: str, protocol: Protocol):\n with open(filename) as fp:\n grammar = fp.read()\n self._load_parser(grammar, protocol)", "def load(self, p):\n return", "def load_pt_file(fname):\n fname = str(Path(fname).expanduser())\n data = torch.load(fname)\n if \"history\" not in data:\n data[\"history\"] = {}\n return data", "def load(self, path: str = './src/phase_net/phase_net.pt'):\n self.core.load_state_dict(torch.load(path))", "def load(self, file_path):\n get_base().scene_parser.load(file_path)", "def load(filename):\n path = Path(__file__).parent / \"resources\" / filename\n with path.open() as file:\n return lkml.load(file)", "def loadFromFile(self,filename):\n path = os.path.dirname(__file__)+\"/\"+filename\n if os.path.exists(path) and os.path.isfile(path):\n self.load(yaml.load(open(path, 'r')))", "def load_pkl_file(p):\n pkl_file = open(p, 'rb')\n obj = pickle.load(pkl_file)\n pkl_file.close()\n return obj", "def load_file(*args, **kwargs): # real signature unknown\n pass", "def load_pth(filename, **kwargs):\n import torch\n return torch.load(filename, **kwargs)", "def load(self, path):\n pass", "def load(self, path):\n pass", "def load(self, path: str):\n pass", "def loadFromFile(self, path):\n\n if \"~\" in path:\n path = os.path.expanduser(path)\n f = open(path)\n body = f.read()\n f.close()\n self._path = path\n self.loadFromString(body)", "def load_pkl(file_name):\n with open(file_name) as fp:\n data = pkl.load(fp)\n return data", "def load_preprocess():\n with open('preprocess.p', mode='rb') as in_file:\n return pickle.load(in_file)", "def rw_loadPLFile(self):\n print \"loadFile\"\n filename = tkFileDialog.askopenfilename()\n filename = self.filenameparser(filename)\n self.rw_PLFile = filename", "def load(self, filename):\n raise NotImplementedError", "def load(self, filename):\n pass", "def load_pkl_file(path):\n with open(path, 'rb') as pkl_file:\n return pickle.load(pkl_file)", "def load(self, file_path):\n self.model = load_model(file_path)", "def load(self, file_path):\n self.model = load_model(file_path)", "def load(self, file_path):\n self.model = load_model(file_path)", "def load(self, file_name):\n try:\n [self.add_word(w) for w in open(file_name).read().splitlines()]\n except IOError as e:\n print(e)", "def do_load(self, line):\n cmd_args = io.parse_cmd_args(line, io.load_cmd_pattern)\n if cmd_args:\n success = self.manager.load(**cmd_args)\n if success:\n self.console_print(\"Yippee! load successful!\", settings.INFO_FORMAT)\n else:\n self.console_print(\"Sorry, the data could not be loaded from file.\", settings.ERROR_FORMAT)\n else:\n self.console_print(settings.COMMMAND_ARGS_ERROR_MSG, settings.ERROR_FORMAT)", "def load(self, file):\n\n with open(file, 'r') as f:\n self._lines = Lines(f.read().splitlines())\n\n self._parse()" ]
[ "0.6621814", "0.6576751", "0.6483502", "0.6446349", "0.64047724", "0.62122035", "0.61944896", "0.61372703", "0.61213183", "0.6107111", "0.6103134", "0.60965335", "0.6090405", "0.6023209", "0.60031086", "0.60031086", "0.6003008", "0.59753203", "0.5966112", "0.59193975", "0.5874618", "0.58628047", "0.58135074", "0.58133256", "0.5794039", "0.5794039", "0.5794039", "0.5792904", "0.578883", "0.5713329" ]
0.74070543
0
Load vertices from PLY file and return as dict with x, y, z keys. To increase loading speed dramatically, this function creates an HDF5 cache file when loading a PLY file for the first time. When the cache exists (it has the same path as the PLY file, except for the extension, which is replaced by ".cache.ecto"), this function will load the data from there instead of from the PLY file.
def vertex_dict_from_plyfile(filename): path = pathlib.Path(filename) cache_path = path.with_suffix('.cache.ecto') if cache_path.is_file(): with h5py.File(cache_path, "r") as hdf5file: x = hdf5file["x"]["arr"][:] y = hdf5file["y"]["arr"][:] z = hdf5file["z"]["arr"][:] else: plydata = load_plyfile(filename) x = plydata['vertex']['x'] y = plydata['vertex']['y'] z = plydata['vertex']['z'] with h5py.File(cache_path, "w") as hdf5file: g_x = hdf5file.create_group('x') g_x.create_dataset('arr', data=x) g_y = hdf5file.create_group('y') g_y.create_dataset('arr', data=y) g_z = hdf5file.create_group('z') g_z.create_dataset('arr', data=z) return dict(x=x, y=y, z=z)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def loadallvertices(self):\n if self.filedb is None:\n return\n vertices = dict()\n line_pattern = r\"[A-Z]{3},[A-Z]{3},[\\d]+$\"\n try:\n with open(self.filedb) as f:\n for line in f:\n # Recover origin, destiny and cost\n if bool(re.match(line_pattern, line)):\n start, finish, cost = line.rstrip('\\n\\r').split(\",\")\n # Create route entry\n route = {finish: int(cost)}\n origin_dict = vertices.get(start)\n if origin_dict is not None:\n origin_dict.update(route)\n vertices[start] = origin_dict\n else:\n vertices[start] = route\n\n with open(self.filedb) as f:\n for line2 in f:\n if bool(re.match(line_pattern, line2)):\n # Recover origin, destiny and cost\n start, finish, cost = line2.rstrip('\\n\\r').split(\",\")\n # Finish must be a vertice also\n if vertices.get(finish) is None:\n vertices[finish] = {finish: 0}\n\n except Exception as e:\n logging.error(\"File open error.\" + str(e))\n return None\n\n return vertices", "def vaex_vertices_from_plyfile(filename):\n xyz = vertex_dict_from_plyfile(filename)\n return vx.from_dict(xyz)", "def read_ply_xyz(filename):\n assert(os.path.isfile(filename))\n with open(filename, 'rb') as f:\n plydata = PlyData.read(f)\n num_verts = plydata['vertex'].count\n vertices = np.zeros(shape=[num_verts, 3], dtype=np.float32)\n vertices[:,0] = plydata['vertex'].data['x']\n vertices[:,1] = plydata['vertex'].data['y']\n vertices[:,2] = plydata['vertex'].data['z']\n return vertices", "def pandas_vertices_from_plyfile(filename):\n xyz = vertex_dict_from_plyfile(filename)\n return pd.DataFrame(xyz)", "def _load_vertices_from_path(self, path):\n logging.info(\"Loading vertices from %r\", path)\n sorted_to_import = sorted(\n _search_for_vertex_id(path),\n key=lambda x: x[0]\n )\n\n for ident, label, prop_file in sorted_to_import:\n properties = json.load(open(prop_file)) if prop_file else {}\n\n # reset the id to the id being loaded.\n self._id_tracker.vid = ident\n vertex = super(PersistentGraph, self).add_vertex(\n label, **properties\n )\n # due to pylint bug https://github.com/PyCQA/pylint/issues/379, we\n # need to disable assigning-non-slot errors\n vertex.path = os.path.join(path, label, str(ident)) # pylint: disable=assigning-non-slot", "def _load_serialized_mesh(filename):\n print 'Loading mesh data from NPZ file', filename\n npzfile = np.load(filename)\n\n k = npzfile['k'].item()\n initial_point = npzfile['initial_point']\n initial_face_index = npzfile['initial_face_index'].item()\n\n all_vertices = npzfile['all_vertices']\n triangles = npzfile['triangles']\n face_local_bases = npzfile['face_local_bases']\n neighbor_faces = npzfile['neighbor_faces']\n\n return [k, initial_point, initial_face_index,\n all_vertices, triangles, face_local_bases, neighbor_faces]", "def load_checkpoint(self, checkpoint_path: str, *args, **kwargs) -> Dict:\n return torch.load(checkpoint_path, *args, **kwargs)", "def load_checkpoint(self, checkpoint_path: str, *args, **kwargs) -> Dict:\n return torch.load(checkpoint_path, *args, **kwargs)", "def load_pt_file(fname):\n fname = str(Path(fname).expanduser())\n data = torch.load(fname)\n if \"history\" not in data:\n data[\"history\"] = {}\n return data", "def build_from_file(path):\n with open(path) as obj:\n raw_file = obj.read()\n file_lines = [line.split(\" \") for line in raw_file.split(\"\\n\")]\n\n vertices = {}\n faces = []\n for number, line in enumerate(file_lines):\n if line[0] == \"v\":\n vertices[number + 1] = tuple(map(float, line[1:]))\n if line[0] == \"f\":\n face = []\n for index in line[1:]:\n face.append(vertices[int(index)])\n face.append(vertices[int(line[1])])\n faces.append(face)\n return Object(points=faces)", "def construct_hypermap_from_file(path):\n r = {}\n with open(path, \"r\") as f:\n for line in f.readlines():\n id, theta, radius = line.split()\n p = HybolicPara(radius=float(radius), theta=float(theta))\n r[id] = p\n logging.debug(\"{} nodes and hyperbolic parameter loaded from {}.\".format\n (len(r), path))\n return r", "def load_checkpoint(self, checkpoint_path: Union[str, Path]) -> Dict[str, Any]:\n # TODO: move to CheckpointIO\n torch.cuda.empty_cache()\n checkpoint_path = inject_model_parallel_rank(checkpoint_path)\n return self.checkpoint_io.load_checkpoint(checkpoint_path)", "def load_verts(file_data, headers, scale_factor):\n\n\n def vert_from_pack(vert_data):\n return (\n (vert_data[0] * scale_factor, vert_data[1] * scale_factor, vert_data[2] * scale_factor,), #XYZ\n (vert_data[3], vert_data[4],), #UV1\n (vert_data[5], vert_data[6],), #UV2\n (vert_data[7], vert_data[8], vert_data[9],), #Normal\n (vert_data[10], vert_data[11], vert_data[12], vert_data[13],), #RGBA\n )\n\n vert_offset, vert_length = headers[10]\n vert_chunk = Struct(\"3f2f2f3f4B\") \n vert_size = vert_chunk.size\n vert_count = int(vert_length / vert_size)\n\n print (\"Found {} vertices\".format(vert_count))\n\n vertices = []\n\n for current_vert_idx in range(vert_count):\n vert_file_position = vert_offset + current_vert_idx * vert_size\n current_vert = vert_chunk.unpack(file_data[vert_file_position : vert_file_position+vert_size])\n vertices.append(vert_from_pack(current_vert))\n\n return vertices", "def load_evaluation_points(self, file_path):\n # Evaluation points are from coarse meshes, not from the ply file we created for our own training\n mesh_path = file_path.split('/')\n mesh_path[-2] = mesh_path[-2][:-6] + 'meshes'\n mesh_path = '/'.join(mesh_path)\n vertex_data, faces = read_ply(mesh_path[:-4] + '_mesh.ply', triangular_mesh=True)\n return np.vstack((vertex_data['x'], vertex_data['y'], vertex_data['z'])).T", "def load_n3d_coords(file_path): \n \n import core.nuc_io as io\n\n seq_pos_dict = {}\n coords_dict = {} \n \n with io.open_file(file_path) as file_obj:\n chromo = None\n \n for line in file_obj:\n \n data = line.split()\n n_items = len(data)\n \n if not n_items:\n continue\n \n elif data[0] == '#':\n continue\n \n elif n_items == 3:\n chromo, n_coords, n_models = data\n \n #if chromo.lower()[:3] == 'chr':\n # chromo = chromo[3:]\n \n if chromo in coords_dict:\n raise Exception('Duplicate chromosome \"%s\" records in file %s' % (chromo, file_path))\n \n n_coords = int(n_coords)\n n_models = int(n_models)\n \n chromo_seq_pos = np.empty(n_coords, int)\n chromo_coords = np.empty((n_models, n_coords, 3), float)\n \n coords_dict[chromo] = chromo_coords\n seq_pos_dict[chromo] = chromo_seq_pos\n \n check = (n_models * 3) + 1\n i = 0\n \n elif not chromo:\n raise Exception('Missing chromosome record in file %s' % file_path)\n \n elif n_items != check:\n msg = 'Data size in file %s does not match Position + Models * Positions * 3'\n raise Exception(msg % file_path)\n \n else:\n chromo_seq_pos[i] = int(data[0])\n \n coord = [float(x) for x in data[1:]]\n coord = np.array(coord).reshape(n_models, 3)\n chromo_coords[:,i] = coord\n i += 1\n \n return seq_pos_dict, coords_dict", "def read_texture_file(filename):\n \n # Deal with compressed files.\n import os\n if (os.path.splitext(filename)[1] == '.gz'):\n import gzip\n f = gzip.open(filename, 'rb')\n else:\n f = open(filename, 'r')\n\n # Stuff everything into a dict and a list\n # for now. Sort this out later (we will probably \n # want to have objects at some point\n header_data = {}\n particles = []\n\n header_lines = 5\n particle_header_lines = 9\n \n for line in f:\n if header_lines == 5:\n header_data['theia_lun'] = int(line)\n header_lines = header_lines - 1\n elif header_lines == 4:\n header_data['npartsallo'] = int(line)\n header_lines = header_lines - 1\n elif header_lines == 3:\n header_data['npartsused'] = int(line)\n header_lines = header_lines - 1\n elif header_lines == 2:\n header_data['n_expected_particles'] = int(line)\n header_lines = header_lines - 1\n elif header_lines == 1:\n header_data['nseen_particles'] = int(line)\n header_lines = header_lines - 1\n elif header_lines == 0:\n if particle_header_lines == 9:\n this_particle = {}\n this_particle['process_id'] = int(line)\n particle_header_lines = particle_header_lines - 1\n elif particle_header_lines == 8:\n this_particle['particle_id'] = int(line)\n particle_header_lines = particle_header_lines - 1\n elif particle_header_lines == 7:\n this_particle['old_particle_id'] = int(line)\n particle_header_lines = particle_header_lines - 1\n elif particle_header_lines == 6:\n this_particle['old_process_id'] = int(line)\n particle_header_lines = particle_header_lines - 1\n elif particle_header_lines == 5:\n this_particle['particle_class'] = line.strip()\n particle_header_lines = particle_header_lines - 1\n elif particle_header_lines == 4:\n this_particle['particle_position'] = np.array(\n [line[0:12], line[12:24], line[24:36]])\n particle_header_lines = particle_header_lines - 1\n elif particle_header_lines == 3:\n this_particle['idata_count'] = int(line)\n if this_particle['idata_count'] > 0:\n particle_header_lines = particle_header_lines - 1\n else:\n particle_header_lines = particle_header_lines - 2\n elif particle_header_lines == 2:\n this_particle['particle_idata'] = np.array(\n [line.rstrip('\\r\\n')[i:i+12] for i in xrange(0, len(line.rstrip('\\r\\n')), 12)]\n )\n particle_header_lines = particle_header_lines - 1\n elif particle_header_lines == 1:\n this_particle['rdata_count'] = int(line)\n if this_particle['rdata_count'] > 0:\n particle_header_lines = particle_header_lines - 1\n else:\n particles.append(this_particle)\n particle_header_lines = 9\n elif particle_header_lines == 0:\n this_particle['particle_rdata'] = np.array(\n [line.rstrip('\\r\\n')[i:i+14] for i in xrange(0, len(line.rstrip('\\r\\n')), 14)]\n )\n particles.append(this_particle)\n particle_header_lines = 9\n f.close()\n\n return header_data, particles", "def polyhedra_from_xyz(xyz_file: str,\n try_convex_hull: bool = True)\\\n -> Tuple[List[Polyhedron],\\\n List[VertexCollection],\\\n List[Union[Polyhedron,VertexCollection]]]:\n\n object_coordinates_dict: Dict[str, List[List[float]]] = {}\n polyhedron_list: List[Polyhedron] = []\n vertex_collection_list: List[VertexCollection] = []\n object_list: List[Union[Polyhedron,VertexCollection]] = []\n type_order: List[str] = []\n with open(xyz_file, 'r') as f:\n lines = f.readlines()\n for i in range(len(lines)):\n line = lines[i].strip()\n if i == 0:\n l = re.search(\"\\d+$\", line)\n assert l is not None\n n_points = int(l.group())\n elif i == 1:\n l = re.search(\"\\d+$\", line)\n assert l is not None\n dim = int(l.group())\n assert dim <= 3, 'We cannot visualise the fourth dimension and\\\n above.'\n else:\n if line == '':\n continue\n l = re.search(\"([A-Za-z]+[0-9]*)[\\s\\t]+\", line)\n assert l is not None\n point_type = l.group(1)\n l2 = re.findall(\"[+-]?\\d+\\.\\d*\", line)\n point_coordinates = []\n for coordinate in l2:\n point_coordinates.append(float(coordinate))\n assert len(point_coordinates) == dim\n if point_type not in object_coordinates_dict:\n object_coordinates_dict[point_type] = []\n object_coordinates_dict[point_type].append(point_coordinates)\n if point_type not in type_order:\n type_order.append(point_type)\n\n for point_type in type_order:\n object_coordinates = np.array(object_coordinates_dict[point_type])\n if try_convex_hull:\n try:\n print(\"Attempting to construct a convex hull for {}...\"\\\n .format(point_type))\n polyhedron = construct_convex_hull_from_coords\\\n (object_coordinates)\n polyhedron_list.append(polyhedron)\n object_list.append(polyhedron) \n except:\n print(\"Failed to construct a convex hull for {}.\"\\\n .format(point_type))\n print(\"Falling back to vertex collection for {}...\"\\\n .format(point_type))\n vertex_collection = construct_vertex_collection_from_coords\\\n (object_coordinates, 2)\n vertex_collection_list.append(vertex_collection)\n object_list.append(vertex_collection) \n else:\n print(\"Constructing a vertex collection for {}...\"\\\n .format(point_type))\n vertex_collection = construct_vertex_collection_from_coords\\\n (object_coordinates, 2)\n vertex_collection_list.append(vertex_collection)\n object_list.append(vertex_collection) \n\n return polyhedron_list,vertex_collection_list,object_list", "def _load(checkpoint_path):\n state_dict, optimizer_state = dg.load_persistables(dirname=checkpoint_path)\n return state_dict, optimizer_state", "def load_hypercube(fname):\n # Get header\n f = open(fname, 'r')\n hdr = f.readline()[2:-1].split(\" \")\n f.close()\n\n # Load data\n dat = np.loadtxt(fname).T\n\n # Build dict\n sample_points = {}\n for i in range(len(hdr)):\n sample_points[hdr[i]] = dat[i]\n return sample_points", "def _load(self):\n graph = self.context.parent.graph.get_context(self.context.identifier)\n data = {}\n for (_, p, o) in graph.triples((self.context.identifier, None, None)):\n if not p.startswith(META):\n continue\n name = p[len(META):]\n data[name] = o.toPython()\n return data", "def load_obj(file, **kwargs):\n v = []\n vt = []\n vn = []\n f = []\n for line in file:\n if line.startswith(\"v \"):\n v.append([float(x) for x in line[2:].split()])\n elif line.startswith(\"vt \"):\n vt.append([float(x) for x in line[3:].split()])\n elif line.startswith(\"vn \"):\n vn.append([float(x) for x in line[3:].split()])\n elif line.startswith(\"f \"):\n f.append([[int(x) for x in fv.split('/')] for fv in line[2:].split()])\n\n # now produce the full buffers\n f = np.array(f, dtype='i4')\n f[f > 0] -= 1\n v = np.array(v, dtype='f4')[f[:, :, 0].ravel()]\n vt = np.array(vt, dtype='f4')[f[:, :, 1].ravel()]\n vn = np.array(vn, dtype='f4')[f[:, :, 2].ravel()]\n\n # NOTE: we could identify unique vertices in f and shave off memory requirements. we could.\n\n return Geometry({'pos': v, 'uv': vt, 'normal': vn}, primitive=Primitives.TRIANGLES, **kwargs)", "def loadFromFile():\n try:\n f1 = open( \"friendshipMap.p\", \"rb\" )\n friendship_map = pickle.load(f1)\n f1.close()\n f2 = open( \"businessReviews.p\", \"rb\" )\n business_reviews = pickle.load(f2)\n f2.close()\n f3 = open( \"degreeCentrality.p\", \"rb\" )\n degree_centrality_map = pickle.load(f3)\n f3.close()\n f4 = open( \"closenessCentrality.p\", \"rb\" )\n closeness_centrality_map = pickle.load(f4)\n f4.close()\n f5 = open( \"betweennessCentrality.p\", \"rb\" )\n betweenness_centrality_map = pickle.load(f5)\n f5.close()\n except IOError as e:\n sys.stderr.write(\"I/O error({0}): {1}\".format(e.errno, e.strerror)+'\\n')\n sys.stderr.write('Try running with -buildClean = clean!\\n')\n\n return (friendship_map, business_reviews, degree_centrality_map, closeness_centrality_map, betweenness_centrality_map, YGraph)", "def load_plyfile(filename):\n plydata = plyfile.PlyData.read(filename)\n return plydata", "def load_data(self, f):\n D = {}\n P = {}\n v = 1\n with open(f) as fp:\n lines = fp.read().split(\"\\n\")\n for line in lines[1:]:\n if(len(line.strip()) > 0):\n parts = line.split(\" \")\n P[v] = (decimal.Decimal(parts[0]), decimal.Decimal(parts[1]))\n v += 1\n\n\n for p in P:\n D[p] = {}\n p1 = P[p]\n for d in P:\n #if d == p:\n # continue\n #else:\n p2 = P[d]\n D[p][d] = math.sqrt(math.pow(p1[0] - p2[0], 2) + math.pow(p1[1] - p2[1], 2))\n\n return P, D", "def load_checkpoint(self, file):\n \"\"\"Load \"\"\"\n chkpnt = torch.load(file)\n self.load_state_dict(chkpnt['model_state_dict'])", "def preload(self):\n # load the objects\n for otype, fname in self.TYPE2NAME.items():\n if fname:\n path = os.path.join(self.anodir, fname + \".gz\")\n if os.path.isfile(path):\n with gzip.open(path, \"rt\") as handler:\n for line in handler:\n omap = json.loads(line)\n cls = self.TYPE2CLASS[otype]\n item = cls.from_map(omap, self)\n self.caches[otype][item.id] = item", "def load_pkl(file_name):\n with open(file_name) as fp:\n data = pkl.load(fp)\n return data", "def load(self, data):\n points = data[\"points\"]\n normals = data[\"normals\"]\n labels = data[\"labels\"]\n primitives = data[\"primitives\"]\n primitives = copy.deepcopy(primitives)\n\n try:\n cluster_ids = data[\"seg_id_RANSAC\"]\n except:\n cluster_ids = data[\"seg_id\"]\n parameters = data[\"primitive_dict\"]\n\n rows, cols, unique_target, unique_pred = match(labels, cluster_ids)\n gtpoints = {}\n for k in range(rows.shape[0]):\n if not (parameters.get(k) is None):\n v = parameters[k]\n for index, j in enumerate(v):\n if index == 0:\n continue\n try:\n v[index] = torch.from_numpy(j.astype(np.float32)).cuda()\n except:\n v[index] = torch.tensor(j).cuda()\n indices = labels == cols[k]\n # only include the surface patches that are matched\n if np.sum(indices) > 0:\n gtpoints[k] = torch.from_numpy(points[indices].astype(np.float32)).cuda()\n else:\n parameters.pop(k)\n return parameters, gtpoints", "def load_pkl(self, name, file_object=None):\n if file_object:\n f = file_object\n else:\n f = gzip.open(name, 'rb')\n temp = pickle.load(f)\n if temp.ht_version < HT_OLD_COMPAT_VERSION:\n raise ValueError('Version of ' + name + ' is ' + str(temp.ht_version)\n + ' which is not at least ' +\n str(HT_OLD_COMPAT_VERSION))\n # assert temp.ht_version >= HT_COMPAT_VERSION\n params = temp.params\n self.hashbits = temp.hashbits\n self.depth = temp.depth\n if hasattr(temp, 'maxtimebits'):\n self.maxtimebits = temp.maxtimebits\n else:\n self.maxtimebits = _bitsfor(temp.maxtime)\n if temp.ht_version < HT_COMPAT_VERSION:\n # Need to upgrade the database.\n print(\"Loading database version\", temp.ht_version,\n \"in compatibility mode.\")\n # Offset all the nonzero bins with one ID count.\n temp.table += np.array(1 << self.maxtimebits).astype(np.uint32) * (\n temp.table != 0)\n temp.ht_version = HT_VERSION\n self.table = temp.table\n self.ht_version = temp.ht_version\n self.counts = temp.counts\n self.names = temp.names\n self.hashesperid = np.array(temp.hashesperid).astype(np.uint32)\n self.dirty = False\n self.params = params", "def load(self, path):\n parameters = paddle.load(path)\n self.set_dict(parameters)" ]
[ "0.6562875", "0.65216416", "0.6379117", "0.6048109", "0.5999355", "0.5958443", "0.5885186", "0.5885186", "0.58593446", "0.5858746", "0.56978995", "0.5648773", "0.5557919", "0.5538228", "0.5536446", "0.55337846", "0.5489507", "0.5448725", "0.54385227", "0.5429585", "0.5416992", "0.54080075", "0.5403936", "0.54037637", "0.5399742", "0.538905", "0.53691083", "0.5346826", "0.53231376", "0.52384204" ]
0.80517364
0
Load vertices from plyfile and return as pandas DataFrame.
def pandas_vertices_from_plyfile(filename): xyz = vertex_dict_from_plyfile(filename) return pd.DataFrame(xyz)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def vaex_vertices_from_plyfile(filename):\n xyz = vertex_dict_from_plyfile(filename)\n return vx.from_dict(xyz)", "def read_ply_xyz(filename):\n assert(os.path.isfile(filename))\n with open(filename, 'rb') as f:\n plydata = PlyData.read(f)\n num_verts = plydata['vertex'].count\n vertices = np.zeros(shape=[num_verts, 3], dtype=np.float32)\n vertices[:,0] = plydata['vertex'].data['x']\n vertices[:,1] = plydata['vertex'].data['y']\n vertices[:,2] = plydata['vertex'].data['z']\n return vertices", "def parse_data(self, path_to_file):\n\n line_dict, rel_dict = self.create_dicts(path_to_file)\n \n line_df = self.create_dataframe(line_dict, ['line'])\n rel_df = self.create_dataframe(rel_dict, ['relation'])\n\n line_df['relation'] = rel_df['relation']\n\n return (line_df, rel_df)", "def vertex_dict_from_plyfile(filename):\n path = pathlib.Path(filename)\n cache_path = path.with_suffix('.cache.ecto')\n if cache_path.is_file():\n with h5py.File(cache_path, \"r\") as hdf5file:\n x = hdf5file[\"x\"][\"arr\"][:]\n y = hdf5file[\"y\"][\"arr\"][:]\n z = hdf5file[\"z\"][\"arr\"][:]\n else:\n plydata = load_plyfile(filename)\n x = plydata['vertex']['x']\n y = plydata['vertex']['y']\n z = plydata['vertex']['z']\n with h5py.File(cache_path, \"w\") as hdf5file:\n g_x = hdf5file.create_group('x')\n g_x.create_dataset('arr', data=x)\n g_y = hdf5file.create_group('y')\n g_y.create_dataset('arr', data=y)\n g_z = hdf5file.create_group('z')\n g_z.create_dataset('arr', data=z)\n return dict(x=x, y=y, z=z)", "def _pq2df(data_file):\n df = pd.read_parquet(data_file)\n return df", "def load(file):\n return pq.read_table(file).to_pandas()", "def load_velodyne_points(filename):\n points = np.fromfile(filename, dtype=np.float32).reshape(-1, 4)\n points[:, 3] = 1.0 # homogeneous\n return points", "def parse_data(path_to_file):\n\n line_dict, rel_dict = create_dicts(path_to_file)\n \n line_df = create_dataframe(line_dict, ['line'])\n rel_df = create_dataframe(rel_dict, ['relation'])\n\n line_df['relation'] = rel_df['relation']\n\n return (line_df, rel_df)", "def load_edgl(fname):\n # Reads edges\n df = pd.read_csv(fname, sep=\" \", header=None, usecols=[0, 1])\n # Convert to list of tuples\n return list(df.itertuples(index=False, name=None))", "def load_plyfile(filename):\n plydata = plyfile.PlyData.read(filename)\n return plydata", "def load_evaluation_points(self, file_path):\n # Evaluation points are from coarse meshes, not from the ply file we created for our own training\n mesh_path = file_path.split('/')\n mesh_path[-2] = mesh_path[-2][:-6] + 'meshes'\n mesh_path = '/'.join(mesh_path)\n vertex_data, faces = read_ply(mesh_path[:-4] + '_mesh.ply', triangular_mesh=True)\n return np.vstack((vertex_data['x'], vertex_data['y'], vertex_data['z'])).T", "def read_polygon_shapefile(filename):\n result = cpp_read_polygon_shapefile(filename)\n return (\n DataFrame({\"f_pos\": result[0], \"r_pos\": result[1]}),\n DataFrame({\"x\": result[2], \"y\": result[3]}),\n )", "def transform_from_edgefile(filename, seed=None, dim=2):\n g = Graph.Read_Ncol(filename)\n\n layout = g.layout_drl(seed=seed,\n dim=dim,\n )\n\n xy = pd.DataFrame(vars(layout)[\"_coords\"], index=g.vs[\"name\"])\n\n return xy", "def load_file_to_dataframe(self, file_path: str) -> pd.DataFrame:\n return pd.read_csv(file_path, sep=\"\\t\")", "def Load_PositionFile(position_filename):\n positions = pd.read_table(position_filename, delimiter=',', header=None)\n positions.columns = ['x','y']\n return positions", "def gff3_to_dataframe( file ):\n result = _read_gff3_using_pandas( file )\n extract_attributes_to_columns( result, ['ID', 'Parent', 'Name' ] )\n return result", "def relation_df_creation(self, path: str) -> pyspark.sql.dataframe.DataFrame:\n try:\n relation_df = self.spark.read.parquet(path)\n except OSError:\n print('cannot open', path)\n relation_df = relation_df.withColumn(\"members_explode\", explode(relation_df.members))\\\n .filter(col('members_explode.role') == 'street')\n relation_df = relation_df.withColumn(\"street_name\", explode(relation_df.tags))\\\n .filter(col('street_name.key') == 'name').select('members_explode.id', 'street_name.value')\\\n .withColumnRenamed('value', 'street_name').withColumnRenamed('id', 'way_id')\n return relation_df", "def _get_position_data(file):\n return pd.read_csv(file)", "def loadData(fileName):\n with open(fileName, 'r') as openedFile:\n dataList = []\n for line in openedFile.readlines():\n line = line.rstrip('\\n').split('\\t')\n pt = Point(line[0], line[1], line[2])\n dataList.append(pt)\n return dataList", "def loadVTKPolydataFile(infile):\n\n lines = None\n\n with open(infile, 'rt') as f:\n lines = f.readlines()\n\n lines = [l.strip() for l in lines]\n\n if lines[3] != 'DATASET POLYDATA':\n raise ValueError('Only the POLYDATA data type is supported')\n\n nVertices = int(lines[4].split()[1])\n nPolygons = int(lines[5 + nVertices].split()[1])\n nIndices = int(lines[5 + nVertices].split()[2]) - nPolygons\n\n vertices = np.zeros((nVertices, 3), dtype=np.float32)\n polygonLengths = np.zeros( nPolygons, dtype=np.uint32)\n indices = np.zeros( nIndices, dtype=np.uint32)\n\n for i in range(nVertices):\n vertLine = lines[i + 5]\n vertices[i, :] = [float(w) for w in vertLine.split()]\n\n indexOffset = 0\n for i in range(nPolygons):\n\n polyLine = lines[6 + nVertices + i].split()\n polygonLengths[i] = int(polyLine[0])\n\n start = indexOffset\n end = indexOffset + polygonLengths[i]\n indices[start:end] = [int(w) for w in polyLine[1:]]\n\n indexOffset += polygonLengths[i]\n\n return vertices, polygonLengths, indices", "def parse_ply(file):\n if 'ply' != file.readline().strip():\n raise ('Not a valid PLY header', ImportError)\n\n while True:\n line = str(file.readline().strip())\n if line.startswith('element vertex'):\n n_verts = int(line.split()[-1]) # element vertex 290 --> 290\n if line.startswith('element face'):\n n_faces = int(line.split()[-1]) # element face 190 --> 190\n if line.startswith('property'):\n # performing check for valid XYZ structure\n if (line.split()[-1] == 'x' and\n str(file.readline().strip()).split()[-1] == 'y' and\n str(file.readline().strip()).split()[-1] == 'z' and\n not str(file.readline().strip()).startswith('property')):\n continue\n elif line == 'property list uchar int vertex_indices':\n continue\n else:\n raise ('Not a valid PLY header. Extra properties can not be evaluated.', ImportError)\n if line == 'end_header':\n break\n\n verts = [[float(s) for s in file.readline().strip().split(' ')] for i_vert in range(n_verts)]\n faces = [[int(s) for s in file.readline().strip().split(' ')] for i_face in range(n_faces)]\n\n return verts, faces, n_verts, n_faces", "def read_polygon_shapefile(filename):\n result = cpp_read_polygon_shapefile(filename)\n f_pos = Series(result[0], name=\"f_pos\")\n r_pos = Series(result[1], name=\"r_pos\")\n return (\n f_pos,\n r_pos,\n DataFrame({\"x\": result[2], \"y\": result[3]}),\n )", "def load_verts(file_data, headers, scale_factor):\n\n\n def vert_from_pack(vert_data):\n return (\n (vert_data[0] * scale_factor, vert_data[1] * scale_factor, vert_data[2] * scale_factor,), #XYZ\n (vert_data[3], vert_data[4],), #UV1\n (vert_data[5], vert_data[6],), #UV2\n (vert_data[7], vert_data[8], vert_data[9],), #Normal\n (vert_data[10], vert_data[11], vert_data[12], vert_data[13],), #RGBA\n )\n\n vert_offset, vert_length = headers[10]\n vert_chunk = Struct(\"3f2f2f3f4B\") \n vert_size = vert_chunk.size\n vert_count = int(vert_length / vert_size)\n\n print (\"Found {} vertices\".format(vert_count))\n\n vertices = []\n\n for current_vert_idx in range(vert_count):\n vert_file_position = vert_offset + current_vert_idx * vert_size\n current_vert = vert_chunk.unpack(file_data[vert_file_position : vert_file_position+vert_size])\n vertices.append(vert_from_pack(current_vert))\n\n return vertices", "def read_nodes_dmp(fname):\n df = pd.read_csv(fname, sep=\"|\", header=None, index_col=False,\n names=['tax_id', \n 'parent_tax_id',\n 'rank', \n 'embl_code',\n 'division_id', \n 'inherited_div_flag', # 1 or 0\n 'genetic_code_id', \n 'inherited_GC_flag', # 1 or 0\n 'mitochondrial_genetic_code_id', \n 'inherited_MGC_flag', # 1 or 0\n 'GenBank_hidden_flag',\n 'hidden_subtree_root_flag', # 1 or 0 \n 'comments'])\n return df.assign(rank = lambda x: x['rank'].str.strip(),\n embl_code = lambda x: x['embl_code'].str.strip(),\n comments = lambda x: x['comments'].str.strip())", "def read_to_df(path):\n return pd.DataFrame.from_records(map(lambda x: typed_line(x, parse_normalized), read_lines(path, header=False)),\n columns=['user', 'item', 'rating'])", "def _load_serialized_mesh(filename):\n print 'Loading mesh data from NPZ file', filename\n npzfile = np.load(filename)\n\n k = npzfile['k'].item()\n initial_point = npzfile['initial_point']\n initial_face_index = npzfile['initial_face_index'].item()\n\n all_vertices = npzfile['all_vertices']\n triangles = npzfile['triangles']\n face_local_bases = npzfile['face_local_bases']\n neighbor_faces = npzfile['neighbor_faces']\n\n return [k, initial_point, initial_face_index,\n all_vertices, triangles, face_local_bases, neighbor_faces]", "def load_npz_model(filename) -> tuple:\n # load_row_cols_json\n js = load_json2py(filename)\n # print(js)\n # print(type(js['rows']))\n rows = js['rows']\n # print(type(js['cols']))\n documents = js['cols']\n\n loaded_matrix = pd.DataFrame(sparse.load_npz(resources_folder(filename) + \".npz\").toarray(),\n index=rows,\n columns=documents)\n\n return loaded_matrix, rows, documents, js['args']", "def get_file_df(filepath):\n dd = [json.loads(f) for f in open(filepath).readlines()]\n return pd.DataFrame(dd)", "def gp_dataframe_import(filename):\n path = os.path.join('..', 'data', filename)\n frame = pd.read_csv(path)\n return frame", "def nodes_df_creation(self, path: str) -> pyspark.sql.dataframe.DataFrame:\n try:\n nodes_df = self.spark.read.parquet(path)\n except OSError:\n print('cannot open', path)\n nodes_df = nodes_df.select('id', 'tags').filter(size(col('tags')) > 0)\n nodes_df = nodes_df.select(col('id'), explode(col('tags')).name('exploded_tags'))\\\n .filter(col('exploded_tags.key') == 'amenity')\n nodes_df = nodes_df.select(\"id\", 'exploded_tags.value').withColumnRenamed('id', 'nodeId')\\\n .withColumnRenamed('value', 'amenity_type')\n return nodes_df" ]
[ "0.7197238", "0.7079626", "0.6208079", "0.6169289", "0.61148095", "0.6112198", "0.6111613", "0.60534364", "0.5996844", "0.59725636", "0.59572744", "0.58987105", "0.58955765", "0.5881835", "0.583922", "0.5792205", "0.5782929", "0.5780073", "0.57574993", "0.57506347", "0.57475257", "0.5730439", "0.5699839", "0.5692363", "0.5669713", "0.5629672", "0.56228715", "0.5620634", "0.56164724", "0.55940425" ]
0.8667049
0
Load vertices from plyfile and return as vaex DataFrame.
def vaex_vertices_from_plyfile(filename): xyz = vertex_dict_from_plyfile(filename) return vx.from_dict(xyz)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def pandas_vertices_from_plyfile(filename):\n xyz = vertex_dict_from_plyfile(filename)\n return pd.DataFrame(xyz)", "def read_ply_xyz(filename):\n assert(os.path.isfile(filename))\n with open(filename, 'rb') as f:\n plydata = PlyData.read(f)\n num_verts = plydata['vertex'].count\n vertices = np.zeros(shape=[num_verts, 3], dtype=np.float32)\n vertices[:,0] = plydata['vertex'].data['x']\n vertices[:,1] = plydata['vertex'].data['y']\n vertices[:,2] = plydata['vertex'].data['z']\n return vertices", "def load_velodyne_points(filename):\n points = np.fromfile(filename, dtype=np.float32).reshape(-1, 4)\n points[:, 3] = 1.0 # homogeneous\n return points", "def vertex_dict_from_plyfile(filename):\n path = pathlib.Path(filename)\n cache_path = path.with_suffix('.cache.ecto')\n if cache_path.is_file():\n with h5py.File(cache_path, \"r\") as hdf5file:\n x = hdf5file[\"x\"][\"arr\"][:]\n y = hdf5file[\"y\"][\"arr\"][:]\n z = hdf5file[\"z\"][\"arr\"][:]\n else:\n plydata = load_plyfile(filename)\n x = plydata['vertex']['x']\n y = plydata['vertex']['y']\n z = plydata['vertex']['z']\n with h5py.File(cache_path, \"w\") as hdf5file:\n g_x = hdf5file.create_group('x')\n g_x.create_dataset('arr', data=x)\n g_y = hdf5file.create_group('y')\n g_y.create_dataset('arr', data=y)\n g_z = hdf5file.create_group('z')\n g_z.create_dataset('arr', data=z)\n return dict(x=x, y=y, z=z)", "def load_evaluation_points(self, file_path):\n # Evaluation points are from coarse meshes, not from the ply file we created for our own training\n mesh_path = file_path.split('/')\n mesh_path[-2] = mesh_path[-2][:-6] + 'meshes'\n mesh_path = '/'.join(mesh_path)\n vertex_data, faces = read_ply(mesh_path[:-4] + '_mesh.ply', triangular_mesh=True)\n return np.vstack((vertex_data['x'], vertex_data['y'], vertex_data['z'])).T", "def load_verts(file_data, headers, scale_factor):\n\n\n def vert_from_pack(vert_data):\n return (\n (vert_data[0] * scale_factor, vert_data[1] * scale_factor, vert_data[2] * scale_factor,), #XYZ\n (vert_data[3], vert_data[4],), #UV1\n (vert_data[5], vert_data[6],), #UV2\n (vert_data[7], vert_data[8], vert_data[9],), #Normal\n (vert_data[10], vert_data[11], vert_data[12], vert_data[13],), #RGBA\n )\n\n vert_offset, vert_length = headers[10]\n vert_chunk = Struct(\"3f2f2f3f4B\") \n vert_size = vert_chunk.size\n vert_count = int(vert_length / vert_size)\n\n print (\"Found {} vertices\".format(vert_count))\n\n vertices = []\n\n for current_vert_idx in range(vert_count):\n vert_file_position = vert_offset + current_vert_idx * vert_size\n current_vert = vert_chunk.unpack(file_data[vert_file_position : vert_file_position+vert_size])\n vertices.append(vert_from_pack(current_vert))\n\n return vertices", "def parse_vertex(lines):\n print \" * Parsing vertex\"\n return _parse_vn(lines, \"v %.6f %.6f %.6f\")", "def load_viewpoint(viewpoint_file):\n with open(viewpoint_file) as viewpoints:\n for line in viewpoints.readlines():\n yield VP(*line.strip().split())", "def _pq2df(data_file):\n df = pd.read_parquet(data_file)\n return df", "def loadVTKPolydataFile(infile):\n\n lines = None\n\n with open(infile, 'rt') as f:\n lines = f.readlines()\n\n lines = [l.strip() for l in lines]\n\n if lines[3] != 'DATASET POLYDATA':\n raise ValueError('Only the POLYDATA data type is supported')\n\n nVertices = int(lines[4].split()[1])\n nPolygons = int(lines[5 + nVertices].split()[1])\n nIndices = int(lines[5 + nVertices].split()[2]) - nPolygons\n\n vertices = np.zeros((nVertices, 3), dtype=np.float32)\n polygonLengths = np.zeros( nPolygons, dtype=np.uint32)\n indices = np.zeros( nIndices, dtype=np.uint32)\n\n for i in range(nVertices):\n vertLine = lines[i + 5]\n vertices[i, :] = [float(w) for w in vertLine.split()]\n\n indexOffset = 0\n for i in range(nPolygons):\n\n polyLine = lines[6 + nVertices + i].split()\n polygonLengths[i] = int(polyLine[0])\n\n start = indexOffset\n end = indexOffset + polygonLengths[i]\n indices[start:end] = [int(w) for w in polyLine[1:]]\n\n indexOffset += polygonLengths[i]\n\n return vertices, polygonLengths, indices", "def p2vertices(self, p):\n h = self.top\n verts = np.empty((self.nparams + 2, 2))\n verts[:, 0] = self._modelx\n verts[:, 1] = np.concatenate([[h], p, [h]])\n return verts", "def load_plyfile(filename):\n plydata = plyfile.PlyData.read(filename)\n return plydata", "def transform_from_edgefile(filename, seed=None, dim=2):\n g = Graph.Read_Ncol(filename)\n\n layout = g.layout_drl(seed=seed,\n dim=dim,\n )\n\n xy = pd.DataFrame(vars(layout)[\"_coords\"], index=g.vs[\"name\"])\n\n return xy", "def read_piv(pivDir):\n pivData = pd.read_csv(pivDir)\n row = len(pivData.y.drop_duplicates())\n col = len(pivData.x.drop_duplicates())\n X = np.array(pivData.x).reshape((row, col))\n Y = np.array(pivData.y).reshape((row, col))\n U = np.array(pivData.u).reshape((row, col))\n V = np.array(pivData.v).reshape((row, col))\n return X, Y, U, V", "def load(file):\n return pq.read_table(file).to_pandas()", "def pfd_read (r) :\n s = r.readline()\n if s == \"\" :\n return False\n l = s.split()\n numVert = int(l[0])\n numRule = int(l[1])\n assert numVert > 0 and numVert <= 100\n assert numRule > 0 and numRule <= 100\n v = [[0,[]]] #build the Vertex array\n for i in range(1, numVert):\n temp = [0,[]]\n v.append(temp)\n s = r.readline()\n for i in range(0, numRule):\n if s == \"\":\n return False\n l = s.split()\n v[int(l[0])-1][0] = int(l[1]) #verts[l[0]].numPred = l[1]\n #verts[l[0]].preds = [0] * (len(l)-2) #I don't know whether this line is necessary\n lenl = len(l)\n for j in range(2,lenl):\n v[int(l[j])-1][1].append(int(l[0]))\n #verts[l[j]-1].succ.append(l[0]) \n s = r.readline()\n return v", "def parse_ply(file):\n if 'ply' != file.readline().strip():\n raise ('Not a valid PLY header', ImportError)\n\n while True:\n line = str(file.readline().strip())\n if line.startswith('element vertex'):\n n_verts = int(line.split()[-1]) # element vertex 290 --> 290\n if line.startswith('element face'):\n n_faces = int(line.split()[-1]) # element face 190 --> 190\n if line.startswith('property'):\n # performing check for valid XYZ structure\n if (line.split()[-1] == 'x' and\n str(file.readline().strip()).split()[-1] == 'y' and\n str(file.readline().strip()).split()[-1] == 'z' and\n not str(file.readline().strip()).startswith('property')):\n continue\n elif line == 'property list uchar int vertex_indices':\n continue\n else:\n raise ('Not a valid PLY header. Extra properties can not be evaluated.', ImportError)\n if line == 'end_header':\n break\n\n verts = [[float(s) for s in file.readline().strip().split(' ')] for i_vert in range(n_verts)]\n faces = [[int(s) for s in file.readline().strip().split(' ')] for i_face in range(n_faces)]\n\n return verts, faces, n_verts, n_faces", "def LoadAirplane():\n return vtkInterface.PolyData(planefile)", "def read_polygon_shapefile(filename):\n result = cpp_read_polygon_shapefile(filename)\n return (\n DataFrame({\"f_pos\": result[0], \"r_pos\": result[1]}),\n DataFrame({\"x\": result[2], \"y\": result[3]}),\n )", "def Load_PositionFile(position_filename):\n positions = pd.read_table(position_filename, delimiter=',', header=None)\n positions.columns = ['x','y']\n return positions", "def load_edgl(fname):\n # Reads edges\n df = pd.read_csv(fname, sep=\" \", header=None, usecols=[0, 1])\n # Convert to list of tuples\n return list(df.itertuples(index=False, name=None))", "def parse_data(self, path_to_file):\n\n line_dict, rel_dict = self.create_dicts(path_to_file)\n \n line_df = self.create_dataframe(line_dict, ['line'])\n rel_df = self.create_dataframe(rel_dict, ['relation'])\n\n line_df['relation'] = rel_df['relation']\n\n return (line_df, rel_df)", "def loadVTK(self, filename, folder):\n import vtk\n print('Extracting Dataset')\n start = time.time()\n reader = vtk.vtkPolyDataReader()\n reader.SetFileName(folder + filename)\n reader.Update()\n polydata = reader.GetOutput()\n n = polydata.GetNumberOfPoints()\n self.data = np.array([0, 0, 0])\n\n for i in range(0, n, 1):\n vraw = list(polydata.GetPoint(i))\n inRange = np.all([vraw[0] > self.ranges[0,0], vraw[0] < self.ranges[0,1], vraw[1] > self.ranges[1,0], vraw[1] < self.ranges[1,1], vraw[2] > self.ranges[2,0], vraw[2] < self.ranges[2,1]])\n if inRange:\n self.data = np.vstack((self.data, np.array(vraw)))\n if i % 50000 == 0:\n print(' Out of the ' + str(n) + ' particles in the dataset, ' + str(i) + ' (' + str(round(i*100/n, 3)) + ' %) have been processed, and ' + str(len(self.data) - 1) + ' have been stored.')\n\n self.data = self.data[1:, :]\n rangeStr = '_x[' + str(self.ranges[0,0]) + ',' + str(self.ranges[0,1]) + ']_y[' + str(self.ranges[1,0]) + ',' + str(self.ranges[1,1]) + ']_z[' + str(self.ranges[1,0]) + ',' + str(self.ranges[1,1]) + '].npy'\n np.save(folder + 'VoronoiData' + rangeStr, self.data)\n print('Elapsed Time: ' + str(round(time.time() - start, 3)))", "def load(filename):\n V = Util.loadPickle(filename + GeneralVertexList.ext)\n vList = GeneralVertexList(len(V))\n vList.V = V\n\n return vList", "def build_from_file(path):\n with open(path) as obj:\n raw_file = obj.read()\n file_lines = [line.split(\" \") for line in raw_file.split(\"\\n\")]\n\n vertices = {}\n faces = []\n for number, line in enumerate(file_lines):\n if line[0] == \"v\":\n vertices[number + 1] = tuple(map(float, line[1:]))\n if line[0] == \"f\":\n face = []\n for index in line[1:]:\n face.append(vertices[int(index)])\n face.append(vertices[int(line[1])])\n faces.append(face)\n return Object(points=faces)", "def read_polygon_shapefile(filename):\n result = cpp_read_polygon_shapefile(filename)\n f_pos = Series(result[0], name=\"f_pos\")\n r_pos = Series(result[1], name=\"r_pos\")\n return (\n f_pos,\n r_pos,\n DataFrame({\"x\": result[2], \"y\": result[3]}),\n )", "def from_csv(cls, path: typing.Union[str, Path]) -> \"VLEPoints\":\n frame = pandas.read_csv(path)\n\n if list(frame.columns) != VLE_COLUMNS:\n raise ValueError(\"Incorrect columns: %s\" % list(frame.columns))\n\n points = []\n\n d = frame.iloc[0].to_dict()\n components = [getattr(Components, d[\"first_component\"]),\n getattr(Components, d[\"second_component\"])]\n\n for _, row in frame.iterrows():\n d = row.to_dict()\n points.append(VLEPoint.from_dict(d))\n\n return VLEPoints(components=components, data=points)", "def fetch_from_sqlite(self):\n conn = get_sqlite()\n c = conn.cursor()\n c.execute('SELECT * FROM vertices ORDER BY id')\n vertices =c.fetchall()\n c.execute('SELECT * FROM edges')\n edges =c.fetchall()\n conn.commit()\n\n self.graph.add_vertices(len(vertices))\n for one in vertices:\n id =int(one[0])\n self.graph.vs[id][\"name\"] = one[1]\n self.graph.vs[id][\"parent\"] = one[2]\n self.graph.vs[id][\"size\"] = one[3]\n self.graph.vs[id][\"last_modified\"] = one[4]\n self.graph.vs[id][\"last_accessed\"] = one[5]\n\n for one in edges:\n self.graph.add_edges([(one[0],one[1])])", "def loadallvertices(self):\n if self.filedb is None:\n return\n vertices = dict()\n line_pattern = r\"[A-Z]{3},[A-Z]{3},[\\d]+$\"\n try:\n with open(self.filedb) as f:\n for line in f:\n # Recover origin, destiny and cost\n if bool(re.match(line_pattern, line)):\n start, finish, cost = line.rstrip('\\n\\r').split(\",\")\n # Create route entry\n route = {finish: int(cost)}\n origin_dict = vertices.get(start)\n if origin_dict is not None:\n origin_dict.update(route)\n vertices[start] = origin_dict\n else:\n vertices[start] = route\n\n with open(self.filedb) as f:\n for line2 in f:\n if bool(re.match(line_pattern, line2)):\n # Recover origin, destiny and cost\n start, finish, cost = line2.rstrip('\\n\\r').split(\",\")\n # Finish must be a vertice also\n if vertices.get(finish) is None:\n vertices[finish] = {finish: 0}\n\n except Exception as e:\n logging.error(\"File open error.\" + str(e))\n return None\n\n return vertices", "def loadData(fileName):\n with open(fileName, 'r') as openedFile:\n dataList = []\n for line in openedFile.readlines():\n line = line.rstrip('\\n').split('\\t')\n pt = Point(line[0], line[1], line[2])\n dataList.append(pt)\n return dataList" ]
[ "0.84510744", "0.73632604", "0.63794583", "0.6267305", "0.6175561", "0.60458577", "0.60157835", "0.5988801", "0.5944366", "0.588248", "0.58743864", "0.5838957", "0.5784811", "0.57548094", "0.5739832", "0.57038474", "0.5685003", "0.5678256", "0.5669674", "0.5648989", "0.5635623", "0.5634389", "0.5619777", "0.55863017", "0.5540753", "0.5535368", "0.5533982", "0.5510665", "0.5508382", "0.55061823" ]
0.80919033
1
> (sub1 1) 0 > (sub1 11111111111111111111111111111111112) 11111111111111111111111111111111113 > (sub1 1.4) 0.3999999999999999 > (sub1 1.5) 0.5 > (sub1 1+1i) 0+1i > (sub1 1/2) 1/2
def test_sub1(doctest): w_x = W_Fixnum(-sys.maxint-1).arith_sub1() assert isinstance(w_x, W_Bignum)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def sub(n1, n2):\n return n1 - n2", "def test_sub():\n z = Complex(1, -2)\n w = Complex(1, 1)\n assert (z - w) == Complex(0, -3)\n assert (z - (1+1j)) == Complex(0, -3)\n assert (z - 2) == Complex(-1, -2)\n assert (z - 2.0) == Complex(-1, -2)", "def SUB(self, n1, n2):", "def f1(x, a, b):\n #return x**43 - b*x**42 + x**7 - x**6 * a + 84*x - 42 * b - 42 * a\n return (x**42 + 42)/(x-a) + (x**6 + 42)/(x-b)", "def sub(num1, num2):\n return num1 - num2", "def sub(num1, num2):\n return num1 - num2", "def sub(num1, num2):\n return num1 - num2", "def sub(a,b):\r\n return a-b", "def f(x0: float, x1: float) -> float:\n return 8 - (x0 - 2) ** 2 - (x1 - 2) ** 2", "def sigb(o) :\n return o * (1 - o)", "def __sub__ (self,other):\n if (self.debug): print(f'enter fraction.__sub__ with {other}')\n f2 = fraction(-1*other.value[0],other.value[1])\n f3 = self.__add__(f2)\n return f3", "def subtract(value1, value2):\n return 1 / (1.0 / value1 - 1.0 / value2)", "def sub(a: Decimal, b: Decimal) -> Decimal:\n return a - b", "def root_1(a, b):\n return -b / a", "def sub(a,b):\n return [a[0]-b[0],a[1]-b[1],a[2]-b[2],1.0]", "def f1(x):\n return x**3 - 2*x + 2", "def pro_avfid_superoperator_compsubspace(U,L1):\n\n if U.type=='oper':\n inner = U.dag()*U_target\n part_idx = [0, 1, 3, 4] # only computational subspace\n ptrace = 0\n for i in part_idx:\n ptrace += inner[i, i]\n dim = 4 # 2 qubits comp subspace \n\n return np.real(((np.abs(ptrace))**2+dim*(1-L1))/(dim*(dim+1)))\n\n elif U.type=='super':\n kraus_form = qtp.to_kraus(U)\n dim=4 # 2 qubits in the computational subspace\n part_idx = [0, 1, 3, 4] # only computational subspace\n psum=0\n for A_k in kraus_form:\n ptrace = 0\n inner = U_target_diffdims.dag()*A_k # otherwise dimension mismatch\n for i in part_idx:\n ptrace += inner[i, i]\n psum += (np.abs(ptrace))**2\n\n return np.real((dim*(1-L1) + psum) / (dim*(dim + 1)))", "def chao1_var_no_doubletons(singles, chao1):\n s = float(singles)\n return s*(s-1)/2 + s*(2*s-1)**2/4 - s**4/(4*chao1)", "def sub(o1, o2):\n return o1-o2", "def sub(a, b):\n return a - b", "def sub(a, b):\n return a - b", "def sub(a, b):\n return a - b", "def divup(a, b):\n return (a + b - 1) // b", "def sub(value_m, value_n):\n return value_m + value_n", "def _cmplx_sub_ ( s , o ) :\n return (-o ) + complex ( s )", "def test_sub(self):\n newvalues = Fraction(1,2)-Fraction(1,2)\n fraction1 = Fraction(newvalues[0],newvalues[1])\n self.assertEqual(str(fraction1),\"0/4\")", "def sub(x, y) :\r\n z = y - x\r\n # The checker automatically proves z < 0 and z + x == y.\r\n return y", "def TestFunc2(x):\r\n return 10*(-0.02*x[0] + 0.5*x[0]*x[0] + x[1])**2 \\\r\n + 128*(-0.02*x[0] + 0.5*x[0]*x[0] - x[1]/4) \\\r\n - (8e-5)*x[0]", "def __truediv__ (self,other):\n if (self.debug): print(f'enter fraction.__mul__ with {other}')\n f3 = fraction(self.value[0]*other.value[1],self.value[1]*other.value[0])\n if (self.debug): print(f3, self, other)\n return f3", "def test_rtruediv():\n truediv = _MathExpression() / 2\n rtruediv = 9 / _MathExpression()\n assert truediv(9) == rtruediv(2)" ]
[ "0.63164145", "0.61161476", "0.60990065", "0.605321", "0.58723927", "0.58723927", "0.58723927", "0.5784584", "0.5782975", "0.5769095", "0.5741576", "0.57034177", "0.5690713", "0.56715757", "0.5641541", "0.5609032", "0.56069714", "0.5571379", "0.553509", "0.5533241", "0.5533241", "0.5533241", "0.5527861", "0.55160844", "0.5505442", "0.5500387", "0.5499668", "0.54783434", "0.54675233", "0.5463141" ]
0.650106
0
> (exact>inexact 1) 1.0 > (exact>inexact 1/2) 0.5 > (exact>inexact 0.5) 0.5 > (exact>inexact 1+2i) 1.0+2.0i > (exact>inexact 102222222222222222222222222222222222222222222222123123) 1.0222222222222222e+53
def test_exact_to_inexact(doctest):
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_inexact_prediace(doctest):", "def u_exact(t):\n return a * t + b", "def almost_eq(e1,e2) :\n\treturn round(e1-e2,4) == 0.0", "def test_inexact_to_exact(doctest):", "def test_le_1():\n a = FixedPoint(1, 'Q2.8')\n assert a < 1.1", "def test_lt_1():\n a = FixedPoint(1, 'Q2.8')\n assert a < 1.1", "def test_le_2():\n a = FixedPoint(1, 'Q2.8')\n b = FixedPoint(1.1, 'Q2.8')\n assert a < b", "def test_ge_1():\n a = FixedPoint(1, 'Q2.8')\n assert a > 0.9", "def longdouble_lte_float64():\n return np.longdouble(2**53) == np.longdouble(2**53) + 1", "def check_bit_exactness(input_raw_file):\n (t1, f1) = interpolate(input_raw_file, 'cpu_nn_lena.dat', 'cpu', 1, 'nn', 8000, 4000)\n (t2, f2) = interpolate(input_raw_file, 'gpu_nn_lena.dat', 'gpu', 1, 'nn', 8000, 4000)\n (t3, f3) = interpolate(input_raw_file, 'cpu_bl_lena.dat', 'cpu', 1, 'bl', 8000, 4000)\n (t4, f4) = interpolate(input_raw_file, 'gpu_bl_lena.dat', 'gpu', 1, 'bl', 8000, 4000)\n\n if filecmp.cmp(f1, f2, shallow=True):\n print(\"NN interpolation on GPU is bit exact with CPU\")\n if filecmp.cmp(f3, f4, shallow=True):\n print(\"Bilinear interpolation on GPU is bit exact with CPU\")", "def test_gt_1():\n a = FixedPoint(1, 'Q2.8')\n assert a > 0.9", "def test_exact_numerical_solution():\n a = 0.2\n b = 3\n\n def f(t, u):\n return a # + (u - u_exact(t))**5\n\n def u_exact(t):\n \"\"\"Exact u(t) corresponding to f above.\"\"\"\n return a * t + b\n\n u0 = u_exact(0)\n T = 8\n N = 10\n tol = 1E-15\n #t_points = np.linspace(0, T, N)\n t_span = (0, T)\n for solver_class in registered_solver_classes:\n solver = solver_class(f)\n solver.set_initial_condition(u0)\n t, u = solver.solve(t_span, N)\n u_e = u_exact(t)\n max_error = (u_e - u).max()\n msg = f'{solver.__class__.__name__} failed with max_error={max_error}'\n assert max_error < tol, msg", "def isqrt( a, b ):\n return a*a - b", "def test_inf():\n assert 'invalid' == classify_triangle(1,2,float('inf'))", "def test_non_integral_validation(self):", "def test_non_integral_validation(self):", "def test_ge_2():\n a = FixedPoint(1, 'Q2.8')\n b = FixedPoint(1.1, 'Q2.8')\n assert b > a", "def get_sqrt_2():\n return 1.41421356", "def test_truediv():\n truediv = _MathExpression() / 2\n assert math.isclose(truediv(9), 4.5) # type: ignore", "def test_lt_2():\n a = FixedPoint(1, 'Q2.8')\n b = FixedPoint(1.1, 'Q2.8')\n assert a < b", "def b(q):\n if q == 0 or q == 1:\n return float(0.0)\n return -(q * log2(q) + (1 - q) * log2(1 - q))", "def approx_eq(a, b):\n return abs(a-b) < approx_eq.eps", "def test06_approximate_types(self):\n\n import _cppyy, sys\n gbl = _cppyy.gbl\n\n o = gbl.operator_short(); o.m_short = 256\n assert o.m_short == 256\n assert int(o) == 256\n\n o = gbl.operator_unsigned_int(); o.m_uint = 2147483647 + 32\n assert o.m_uint == 2147483647 + 32\n assert long(o) == 2147483647 + 32\n\n o = gbl.operator_unsigned_long();\n o.m_ulong = sys.maxint + 128\n assert o.m_ulong == sys.maxint + 128\n assert long(o) == sys.maxint + 128\n\n o = gbl.operator_float(); o.m_float = 3.14\n assert round(o.m_float - 3.14, 5) == 0.\n assert round(float(o) - 3.14, 5) == 0.", "def fiabilite2(v1 : float, v2 : float, v3 : float\n , epsilon : float) -> float:\n if egal_eps(v1, v2, epsilon):\n if egal_eps(v1, v3, epsilon):\n if egal_eps(v2, v3, epsilon):\n return 1\n else:\n return 2/3\n else:\n if egal_eps(v2, v3, epsilon):\n return 2/3\n else:\n return 0\n elif egal_eps(v2, v3, epsilon):\n if egal_eps(v1, v3, epsilon):\n return 2/3\n else:\n return 0\n else:\n return 0", "def print_exact_res():\n\n print(\"************************************************************\")\n print(\"EXACT RESULT FOR THE VALUES THAT MINIMIZE THE FUNCTION:\\n\")\n f_str = \"The value of x_{:d} is {:f}\"\n for i in range(1, cfg.n + 1):\n print(f_str.format(i, float(i)))\n print(\"************************************************************\\n\")", "def fp_eq(x: float, y: float) -> bool:\n return fabs(x-y) < 10**-12", "def exactsolution(x, t, u):\n if 0 <= (x - u*t) and (x - u*t) <= 0.2:\n temp = 1 - (10 * (x - u*t) -1)**2\n else:\n temp = 0\n return temp", "def asinexact(dtype):\n if np.issubdtype(dtype, np.inexact):\n return dtype\n else:\n return np.float64", "def test_gt_2():\n a = FixedPoint(1, 'Q2.8')\n b = FixedPoint(1.1, 'Q2.8')\n assert b > a", "def iexact(self, other):" ]
[ "0.6380264", "0.61588365", "0.6138461", "0.61297613", "0.5908166", "0.58085465", "0.57954437", "0.57187057", "0.57136405", "0.5682127", "0.567197", "0.566006", "0.56335366", "0.5601193", "0.56009555", "0.56009555", "0.5597991", "0.5588879", "0.5588747", "0.5565807", "0.55296725", "0.5518713", "0.5500572", "0.54933786", "0.5470921", "0.5457546", "0.5427854", "0.5418359", "0.5413428", "0.54118246" ]
0.63425225
1
! (require '%flfxnum '%unsafe) > (unsafefl+ 1.0 2.0) 3.0 > (unsafefl 2.0 1.0) 1.0 > (unsafefl 2.0 0.5) 1.0 > (unsafefl/ 2.0 0.5) 4.0 > (unsafeflmin 3.0 5.4) 3.0 > (unsafeflmax 3.0 5.4) 5.4
def test_flonum_unsafe(doctest):
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_fixnum_unsafe(doctest):", "def install_N_():\n\n import __builtin__\n\n __builtin__.N_ = lambda s: s", "def test_fixnum_special(doctest):", "def test_spidermonkey_warning():\n # The following is attempting to store the octal \"999999999999\" in x, but\n # this is an invalid octal obviously. We need to \"use strict\" here because\n # the latest versions of spidermonkey simply accept that as a base 10\n # number, despite the \"0\" prefix.\n # We need spidermonkey to choke on this code, and this test makes sure that\n # when spidermonkey does, it doesn't break the validator.\n assert _do_test_raw(\"\"\"\n \"use strict\";\n var x = 0999999999999;\n \"\"\").failed()", "def longdouble_lte_float64():\n return np.longdouble(2**53) == np.longdouble(2**53) + 1", "def dbl(x):\n return 2 * x", "def compat():\n features_32 = np.array(\n [xxh32_intdigest(rand.bytes(13)) for _ in range(100)], dtype=np.uint32\n )\n results = set()\n print(\"\\nTesting minhash reference compatibility:\\n\")\n for func in funcs_ref:\n r = tuple(func(features_32))\n print(f\"{func.__name__:<18}: {r}\")\n results.add(r)\n assert len(results) == 1\n\n s = np.array([xxh64_intdigest(rand.bytes(13)) for _ in range(100)], dtype=np.uint64)\n results = set()\n print(\"\\nTesting minhash xor compatibility:\\n\")\n for func in funcs_xor:\n r = tuple(func(s))\n print(f\"{func.__name__:<18}: {r}\")\n results.add(r)\n # assert len(results) == 1", "def min(x):\n pass", "def test_exp():\n x = np.linspace(-3,3,13)\n\n default_use_numexpr = accel_math._USE_NUMEXPR\n\n accel_math._USE_NUMEXPR = True\n r1 = accel_math._exp(x)\n\n accel_math._USE_NUMEXPR = False\n r2 = accel_math._exp(x)\n\n np.testing.assert_almost_equal(r1,r2)\n\n accel_math._USE_NUMEXPR = default_use_numexpr", "def eigh_unsafe(self):\n from packaging import version as pac_version\n import scipy\n is_old_scipy = (\n pac_version.parse(scipy.__version__) < pac_version.parse(\"1.5\")\n )\n return (\n # macOS OpenBLAS eigh is unstable, see #1288\n (_blas_info() == \"OPENBLAS\" and platform.system() == 'Darwin')\n # The combination of scipy<1.5 and MKL causes wrong results when\n # calling eigh for big matrices. See #1495, #1491 and #1498.\n or (is_old_scipy and (_blas_info() == 'INTEL MKL'))\n )", "def ignore_builtin_verification():\n return not current_space().skip_builtin_verification", "def test_flonum_special(doctest):", "def longdouble_precision_improved():\n return not longdouble_lte_float64() and _LD_LTE_FLOAT64", "def best_float():\n try:\n long_info = type_info(np.longdouble)\n except FloatingError:\n return np.float64\n if (long_info['nmant'] > type_info(np.float64)['nmant'] and\n machine() != 'sparc64'): # sparc has crazy-slow float128\n return np.longdouble\n return np.float64", "def CompilationRelaxations(self) -> int:", "def _fcts():\n import numpy # pylint: disable=C0415\n from .cbenchmark_dot import vector_dot_product # pylint: disable=E0611,C0415\n from .cbenchmark_dot import vector_dot_product16 # pylint: disable=E0611,C0415\n from .cbenchmark_dot import vector_dot_product16_nofcall # pylint: disable=E0611,C0415\n from .cbenchmark_dot import vector_dot_product16_sse # pylint: disable=E0611,C0415\n\n def simple_dot(values):\n return numpy.dot(values, values)\n\n def c11_dot(vect):\n return vector_dot_product(vect, vect)\n\n def c11_dot16(vect):\n return vector_dot_product16(vect, vect)\n\n def c11_dot16_nofcall(vect):\n return vector_dot_product16_nofcall(vect, vect)\n\n def c11_dot16_sse(vect):\n return vector_dot_product16_sse(vect, vect)\n\n return [simple_dot, c11_dot, c11_dot16, c11_dot16_nofcall, c11_dot16_sse]", "def frexp10 ( value ) :\n \n ## p = cpp_frexp10 ( value )\n ## return p.first, p.second\n\n xv = abs ( value )\n if iszero ( xv ) : return ( 0 , 0 ) \n\n q = math.floor ( math.log10 ( float ( xv ) ) )\n\n if 0 < q : xv /= 10**q \n elif 0 > q : xv *= 10**abs(q) \n \n if 1 <= xv :\n xv /= 10\n q += 1\n \n return ( xv , q ) if ( 0 <= value ) else ( -xv , q )", "def test_nuke_psfs():\n # Without multiprocessing\n mt.nuke_psfs(mprocessing=False)\n\n # With multiprocessing\n mt.nuke_psfs()", "def compute_support():\n # support_values = [i for i in range(-MAX_MARK_VALUE, MAX_MARK_VALUE + 1, 0.01)]\n\n return np.arange(-MAX_MARK_VALUE, MAX_MARK_VALUE + 1).tolist()", "def main() -> int:\n\n a = None\n for n, g in enumerate(gen_primes(100000, 1000000)):\n repeat, indices = check_if_has_3_repeated_digits(str(g))\n if repeat:\n a = check_for_family_of_primes(repeat, indices, list(str(g)))\n if len(a) > 7 and min(a) > 100000:\n EULER_LOGGER.debug(f\"{a}\")\n a = min([int(i) for i in a])\n break\n\n return a", "def load_numpy_core_umath(finder, module):\n module.AddGlobalName(\"add\")\n module.AddGlobalName(\"absolute\")\n module.AddGlobalName(\"arccos\")\n module.AddGlobalName(\"arccosh\")\n module.AddGlobalName(\"arcsin\")\n module.AddGlobalName(\"arcsinh\")\n module.AddGlobalName(\"arctan\")\n module.AddGlobalName(\"arctanh\")\n module.AddGlobalName(\"bitwise_and\")\n module.AddGlobalName(\"bitwise_or\")\n module.AddGlobalName(\"bitwise_xor\")\n module.AddGlobalName(\"ceil\")\n module.AddGlobalName(\"conj\")\n module.AddGlobalName(\"conjugate\")\n module.AddGlobalName(\"cosh\")\n module.AddGlobalName(\"divide\")\n module.AddGlobalName(\"fabs\")\n module.AddGlobalName(\"floor\")\n module.AddGlobalName(\"floor_divide\")\n module.AddGlobalName(\"fmod\")\n module.AddGlobalName(\"greater\")\n module.AddGlobalName(\"hypot\")\n module.AddGlobalName(\"invert\")\n module.AddGlobalName(\"isfinite\")\n module.AddGlobalName(\"isinf\")\n module.AddGlobalName(\"isnan\")\n module.AddGlobalName(\"less\")\n module.AddGlobalName(\"left_shift\")\n module.AddGlobalName(\"log\")\n module.AddGlobalName(\"logical_and\")\n module.AddGlobalName(\"logical_not\")\n module.AddGlobalName(\"logical_or\")\n module.AddGlobalName(\"logical_xor\")\n module.AddGlobalName(\"maximum\")\n module.AddGlobalName(\"minimum\")\n module.AddGlobalName(\"multiply\")\n module.AddGlobalName(\"negative\")\n module.AddGlobalName(\"not_equal\")\n module.AddGlobalName(\"power\")\n module.AddGlobalName(\"remainder\")\n module.AddGlobalName(\"right_shift\")\n module.AddGlobalName(\"sign\")\n module.AddGlobalName(\"sinh\")\n module.AddGlobalName(\"sqrt\")\n module.AddGlobalName(\"tan\")\n module.AddGlobalName(\"tanh\")\n module.AddGlobalName(\"true_divide\")", "def safe_softplus(x, limit=10):\n ret = x\n _under_limit = x < limit\n ret[_under_limit] = np.log(1.0 + np.exp(x[_under_limit]))\n return ret", "def robust():\n from bbst import Bst\n return Bst([\n 10, 2, 1, 9, 4, 3, 8, 6, 5, 7, 18, 11, 19, 16, 12, 17, 14, 13, 15\n ])", "def benchmark(nx, tstop):\n Lx = 10\n Ly = 10\n c = 1.0\n ny = nx\n\n # our use of weave requires string formulas:\n Is = StringFunction('exp(-pow(x-Lx/2.0,2)/2.0 -pow(y-Ly/2.0,2)/2.0)',\n independent_variables=('x','y'),\n Lx=Lx, Ly=Ly, globals=globals())\n fs = StringFunction('0.0', independent_variables=('x', 'y', 't'),\n globals=globals())\n BCs = StringFunction('0.0', independent_variables=('x', 'y', 't'),\n globals=globals())\n\n def action(u, xv, yv, t):\n #print t\n pass\n\n implementation = {}\n cpu = []\n for ic in 'f77', 'vec', 'scalar', 'weave':\n for bc in 'f77', 'vec', 'scalar', 'weave':\n for inner in 'f77', 'vec', 'scalar', 'weave':\n implementation['ic'] = ic\n implementation['inner'] = inner\n implementation['bc'] = bc\n # optimize StringFunction functions for the non-weave case:\n # implementation:\n if 'weave' in (ic, bc, inner) or 'f77' in (ic, bc, inner):\n I = Is; f = fs; BC = BCs\n else:\n I = Is.__call__; f = fs.__call__; BC = BCs.__call__\n\n t0 = time.clock()\n dt, cpu_ic, cpu_inner, cpu_bc = \\\n solver(I, f, c, BC, Lx, Ly, nx, ny, 0, tstop,\n user_action=None,\n implementation=implementation,\n verbose=False)\n t1 = time.clock()\n cpu_total = cpu_ic + cpu_inner + cpu_bc\n overhead = (t1-t0)-cpu_total\n cpu.append([implementation.copy(), cpu_total,\n cpu_ic, cpu_inner, cpu_bc, overhead])\n print t1-t0, implementation, 'overhead:', overhead\n # normalize CPU-times:\n cpu_min = min([abs(c) for i, c, c1, c2, c3, c4 in cpu])\n print '\\n\\nMinimum CPU time:', cpu_min\n print 'no of time steps:', int(tstop/dt)\n print 'interior/boundary ratio:', int(nx*ny*1.0/max(nx,ny))\n for impl, cpu, cpu_ic, cpu_inner, cpu_bc, overhead in cpu:\n # normalized-CPU ic inner bc overhead\n print \"%8.2f\" % (cpu/cpu_min),\n print \"%-10s %8.2f; \" % (impl['ic'], cpu_ic),\n print \"%-10s %8.2f; \" % (impl['inner'], cpu_inner),\n print \"%-10s %8.2f; \" % (impl['bc'], cpu_bc),\n print \"%d%%\" % (overhead/cpu*100)", "def _validate_builtin(_):\n pass", "def _c_optimizations_required():\n pure_env = os.environ.get('PURE_PYTHON')\n require_c = pure_env == \"0\"\n return require_c", "def test_large_values(self):\n eq_(0, smart_int('1' * 1000))", "def smaceps():\n mach_eps = 2**-(24 - 1)/2\n return mach_eps", "def exercise_b2_53():\r\n pass", "def test_flfloor(doctest):" ]
[ "0.6193654", "0.5356504", "0.5192745", "0.51889336", "0.5102665", "0.4882313", "0.48294187", "0.48263472", "0.48239887", "0.48138288", "0.47466013", "0.47216377", "0.46795782", "0.46394727", "0.46227637", "0.4621179", "0.46082172", "0.4599316", "0.4594113", "0.45876083", "0.45816952", "0.4581311", "0.45807016", "0.45770216", "0.45722428", "0.4565629", "0.4548663", "0.45476702", "0.45465642", "0.45439893" ]
0.61471367
1
! (require '%flfxnum '%unsafe) > (unsafefx+ 10 20) 30 > (unsafefx 20 10) 10 > (unsafefx 20 5) 100 > (unsafefxmin 10 20) 10 > (unsafefxmin 20 10) 10 > (unsafefxmax 10 20) 20 > (unsafefxmax 20 10) 20 > (unsafefxmodulo 100 30) 20 > (unsafefxmodulo 100 30) 20 > (unsafefx 2 1) 1 > (unsafefx 2 5) 10 > (unsafefxmin 1 2) 1 > (unsafefxmin 2 1) 1 > (unsafefxmax 1 2) 2 > (unsafefxmax 2 1) 2 > (unsafefx> 2 1) t > (unsafefx>= 2 1) t > (unsafefx>= 1 1) t > (unsafefx>= 1 1) f > (unsafefx (unsafefx (unsafefx (unsafefx= 10 10) t > (unsafefxand 2 3) 2 > (unsafefxior 2 3) 3 > (unsafefxlshift 10 10) 10240 > (unsafefxrshift 1 20) 0 > (unsafefxrshift 20 1) 10 > (unsafefxrshift 20 1) 10 > (unsafefxmodulo 10 3) 1 > (unsafefxmodulo 10 3) 1 > (unsafefxremainder 10 3) 1 > (unsafefxremainder 10 3) 1 > (unsafefxquotient 10 3) 3 > (unsafefxlshift 1 10) 1024 ; implementation defined, but should terminate quickly > (unsafefxlshift 1 10000000) ;1
def test_fixnum_unsafe(doctest):
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def example_ten():\n x = list(range(10**6))\n i = bisect_left(x, 991234)", "def pe2(limit=4000000):\n a, b, s = 1, 2, 2\n while b <= limit:\n a, b = b, a + b\n if not b & 1:\n s += b\n return s", "def _cutoff32(value):\n return value % 0x100000000", "def solveProblem048():\n # Trivial to brute force with modern hardware.\n sd = 0\n for i in range(1,1000+1):\n sd += i**i\n s = str(sd)\n s = s[-10:]\n print(s)", "def sop(*args, **kwargs):\n return _randint(0, 2 ** 15 - 1)", "def get_min_run(n):\n r = 0\n while n >= 64:\n r |= n & 1\n n >>= 1\n return n + r", "def r1(x, n, max_size=32):\n return (x << n) % (2 << (max_size - 1)) + (x >> (max_size - n))", "def q8(array):\n a = array[0]\n b = array[4]\n c = array[8]\n d = array[12]\n a1 = roll(a, 00) + roll(b, 00) + roll(b, 12) + roll(c, 12) + roll(d, 28) + roll(a, 28) + roll(b, 28)\n b1 = roll(b, 19) + roll(c, 19) + roll(d, 3) + roll(a, 3) + roll(b, 3) + roll(c, 7) + roll(d, 23) + roll(a,\n 23) + roll(\n b, 23) + roll(a, 15) + roll(b, 15) + roll(b, 27) + roll(c, 27) + roll(d, 11) + roll(a, 11) + roll(b, 11) + roll(\n d, 31) + roll(a, 31) + roll(b, 31)\n c1 = roll(c, 0) + roll(d, 16) + roll(a, 16) + roll(b, 16) + roll(a, 8) + roll(b, 8) + roll(b, 20) + roll(c,\n 20) + roll(\n d, 4) + roll(a, 4) + roll(b, 4) + roll(d, 24) + roll(a, 24) + roll(b, 24)\n d1 = roll(a, 8) + roll(b, 8) + roll(b, 20) + roll(c, 20) + roll(d, 4) + roll(a, 4) + roll(b, 4) + roll(d,\n 24) + roll(a,\n 24) + roll(\n b, 24)\n\n return a1, array[1], array[2], array[3], b1, array[5], array[6], array[7], c1, array[9], array[\n 10], array[11], d1, array[13], array[14], array[15]", "def prjEuler():\r\n #Constants\r\n NUMSTRING = ( \"73167176531330624919225119674426574742355349194934\"\r\n \"96983520312774506326239578318016984801869478851843\"\r\n \"85861560789112949495459501737958331952853208805511\"\r\n \"12540698747158523863050715693290963295227443043557\"\r\n \"66896648950445244523161731856403098711121722383113\"\r\n \"62229893423380308135336276614282806444486645238749\"\r\n \"30358907296290491560440772390713810515859307960866\"\r\n \"70172427121883998797908792274921901699720888093776\"\r\n \"65727333001053367881220235421809751254540594752243\"\r\n \"52584907711670556013604839586446706324415722155397\"\r\n \"53697817977846174064955149290862569321978468622482\"\r\n \"83972241375657056057490261407972968652414535100474\"\r\n \"82166370484403199890008895243450658541227588666881\"\r\n \"16427171479924442928230863465674813919123162824586\"\r\n \"17866458359124566529476545682848912883142607690042\"\r\n \"24219022671055626321111109370544217506941658960408\"\r\n \"07198403850962455444362981230987879927244284909188\"\r\n \"84580156166097919133875499200524063689912560717606\"\r\n \"05886116467109405077541002256983155200055935729725\"\r\n \"71636269561882670428252483600823257530420752963450\" )\r\n \r\n #defined items\r\n greatest_prod = 1\r\n euler_queue = fiveQueue()\r\n \r\n #code\r\n for numIter in NUMSTRING:\r\n if( euler_queue.push( numIter ) ):\r\n temp_prod = euler_queue.product()\r\n if( temp_prod > greatest_prod ):\r\n greatest_prod = temp_prod\r\n \r\n print \"The greatest product is %d\" % greatest_prod\r\n return", "def sol(n):\n p = 1\n res = 0\n \n while n:\n p*=5\n if n&1:\n res+=p\n n=n>>1\n return res%1000000007", "def _varint_cost(n: int):\n result = 1\n while n >= 128:\n result += 1\n n >>= 7\n return result", "def rshift(val, n):\n return (val % 0x100000000) >> n", "def rshift(val, n):\n return (val % 0x100000000) >> n", "def fast_exp(a, x, n):\n x_2 = int2bin(x)\n vprint(\"{} = [{}]_2\".format(str(x), x_2))\n powers = [a % n]\n vprint(\"{}^(2^0) = {}^1 = {} \\\\equiv {}\".format(a, a, a, (a % n)))\n i = 1\n while i < len(x_2):\n # This (hilariously ugly) print statement prints the\n # intermediary operations in a format that can be easily\n # exported to LaTeX. TODO: Split it up into sane chunks.\n vprint(\"{}^{{ {}^{} }} = {}^{{ {} }} = {}^{{ {} }} * {}^{{ {} }} = {}*{} = {} \\\\equiv {}\".format(\n a, 2, i,\n a, pow(2, i),\n a, pow(2, i-1),\n a, pow(2, i-1),\n powers[-1], powers[-1],\n powers[-1] * powers[-1],\n (powers[-1] * powers[-1]) % n))\n next_power = (powers[-1] * powers[-1]) % n\n powers.append(next_power)\n i += 1\n\n vprint(\"{}^{{ {} }} = ...\".format(a, x))\n rpowers = list(reversed(powers))\n prod = 1\n i = 0\n while i < len(x_2):\n bit = x_2[i]\n power = rpowers[i]\n if bit == \"1\":\n vprint(\"* {} \\t== {}^{{ 2^{{ {} }} }}\\n\".format(power, a, len(x_2) - i - 1))\n prod *= power\n i += 1\n result = prod % n\n vprint(\"= {} \\\\equiv {}\".format(prod, result))\n return result", "def test_sub1(doctest):\n w_x = W_Fixnum(-sys.maxint-1).arith_sub1()\n assert isinstance(w_x, W_Bignum)", "def find_minrun(n: int) -> int:\n r = 0 # Becomes 1 if any bits are shifted off\n assert n >= 0\n while n >= 64:\n # The target of this while-loop:\n # If n is an exact power of 2, return 32;\n # otherwise, return int k in [32,64] such that n/k is close to, but strictly \n # less than, an exact power of 2 that is larger than 2^1=2.\n \n # | is `OR by bits`, & is `AND by bits`. ie r = r|(n&1).\n # The next two lines of code work as follows:\n # 1. If n is an exact power of 2, then for all loops, n&1=0, r=r|0=0|0=0, \n # and n is halved, until n=64 and is halved to 32, with r=0, so returns 32.\n # 2. Otherwise, then there must be at least one `1` among the second to the \n # last digits of n's binary form, eg.10010000. We scan from the rightmost digit # to the left, and whenever a 1 is met, r is 1. n will decrease to the n//2^k \n # that is closest to but less than 64. The target is met.\n #\n # In essence, this procedure is simply taking the first 6 bits of n, and add \n # 1 if any of the remaining bits is 1 (we call a bit that is 1 a \"set bit\").\n\n r |= n & 1\n n >>= 1 # move n's binary form all 1 digit to the right, ie n = n // 2\n # If n < 64, just return n, since it is too small to bother with fancy stuff\n return n + r", "def eight():\r\n \r\n number = \"73167176531330624919225119674426574742355349194934\\\r\n96983520312774506326239578318016984801869478851843\\\r\n85861560789112949495459501737958331952853208805511\\\r\n12540698747158523863050715693290963295227443043557\\\r\n66896648950445244523161731856403098711121722383113\\\r\n62229893423380308135336276614282806444486645238749\\\r\n30358907296290491560440772390713810515859307960866\\\r\n70172427121883998797908792274921901699720888093776\\\r\n65727333001053367881220235421809751254540594752243\\\r\n52584907711670556013604839586446706324415722155397\\\r\n53697817977846174064955149290862569321978468622482\\\r\n83972241375657056057490261407972968652414535100474\\\r\n82166370484403199890008895243450658541227588666881\\\r\n16427171479924442928230863465674813919123162824586\\\r\n17866458359124566529476545682848912883142607690042\\\r\n24219022671055626321111109370544217506941658960408\\\r\n07198403850962455444362981230987879927244284909188\\\r\n84580156166097919133875499200524063689912560717606\\\r\n05886116467109405077541002256983155200055935729725\\\r\n71636269561882670428252483600823257530420752963450\"\r\n\r\n greatest = 0\r\n \r\n i = 0\r\n while i < len(number) - 12:\r\n product = 1\r\n for j in range(13):\r\n product *= int(number[i + j])\r\n #j += 1\r\n if product > greatest:\r\n greatest = product\r\n i += 1\r\n \r\n return greatest", "def solution():\n constant = []\n i = 1\n\n while len(constant) < 1e6:\n constant.append(str(i))\n i += 1\n\n constant = \"\".join(constant)\n\n return (\n int(constant[0])\n * int(constant[9])\n * int(constant[99])\n * int(constant[999])\n * int(constant[9999])\n * int(constant[99999])\n * int(constant[999999])\n )", "def lrshift(val, n) -> np.int64:\n return (val % (1 << 64)) >> n", "def q2(array):\n a = array[2]\n b = array[7]\n c = array[8]\n d = array[13]\n a1 = roll(a, 00) + roll(b, 00) + roll(b, 12) + roll(c, 12) + roll(d, 28) + roll(a, 28) + roll(b, 28)\n b1 = roll(b, 19) + roll(c, 19) + roll(d, 3) + roll(a, 3) + roll(b, 3) + roll(c, 7) + roll(d, 23) + roll(a,\n 23) + roll(\n b, 23) + roll(a, 15) + roll(b, 15) + roll(b, 27) + roll(c, 27) + roll(d, 11) + roll(a, 11) + roll(b, 11) + roll(\n d, 31) + roll(a, 31) + roll(b, 31)\n c1 = roll(c, 0) + roll(d, 16) + roll(a, 16) + roll(b, 16) + roll(a, 8) + roll(b, 8) + roll(b, 20) + roll(c,\n 20) + roll(\n d, 4) + roll(a, 4) + roll(b, 4) + roll(d, 24) + roll(a, 24) + roll(b, 24)\n d1 = roll(a, 8) + roll(b, 8) + roll(b, 20) + roll(c, 20) + roll(d, 4) + roll(a, 4) + roll(b, 4) + roll(d,\n 24) + roll(a,\n 24) + roll(\n b, 24)\n\n return array[0], array[1], a1, array[3], array[4], array[5], array[6], b1, c1, array[9], array[10], array[11], \\\n array[\n 12], d1, array[14], array[15]", "def problem9_fast(n):\n n2 = n // 2\n ulimit = ceil(sqrt(n2)) - 1\n for u in range(2, ulimit):\n if n2 % u == 0:\n nu = n2 // u\n while nu % 2 == 0:\n nu //= 2\n if u % 2 == 1:\n k = u + 2\n else:\n k = u + 1\n while k < 2 * u and k <= nu:\n if nu % k == 0 and pe_utils.gcd(k, u) == 1:\n d = n2 // (k * u)\n v = k - u\n a = (u ** 2 - v ** 2) * d\n b = 2 * u * v * d\n c = (u ** 2 + v ** 2) * d\n return a * b * c\n k += 2\n return None", "def rshift(val: int, n: int) -> int:\n return (val % 0x100000000) >> n", "def test_bigSum():\n\n assert bigSum() == 20000000100000000", "def shiftleft(num,shiftplaces):\n for i in range(shiftplaces):\n num = multby2(num)\n return num", "def q7(array):\n a = array[1]\n b = array[5]\n c = array[9]\n d = array[13]\n a1 = roll(a, 00) + roll(b, 00) + roll(b, 12) + roll(c, 12) + roll(d, 28) + roll(a, 28) + roll(b, 28)\n b1 = roll(b, 19) + roll(c, 19) + roll(d, 3) + roll(a, 3) + roll(b, 3) + roll(c, 7) + roll(d, 23) + roll(a,\n 23) + roll(\n b, 23) + roll(a, 15) + roll(b, 15) + roll(b, 27) + roll(c, 27) + roll(d, 11) + roll(a, 11) + roll(b, 11) + roll(\n d, 31) + roll(a, 31) + roll(b, 31)\n c1 = roll(c, 0) + roll(d, 16) + roll(a, 16) + roll(b, 16) + roll(a, 8) + roll(b, 8) + roll(b, 20) + roll(c,\n 20) + roll(\n d, 4) + roll(a, 4) + roll(b, 4) + roll(d, 24) + roll(a, 24) + roll(b, 24)\n d1 = roll(a, 8) + roll(b, 8) + roll(b, 20) + roll(c, 20) + roll(d, 4) + roll(a, 4) + roll(b, 4) + roll(d,\n 24) + roll(a,\n 24) + roll(\n b, 24)\n\n return array[0], a1, array[2], array[3], array[4], b1, array[6], array[7], array[8], c1, array[10], array[11], \\\n array[\n 12], d1, array[14], array[15]", "def pseudo(x,N) :\n\treturn (x**2+1)%N", "def q1(array):\n a = array[3]\n b = array[4]\n c = array[9]\n d = array[14]\n a1 = roll(a, 00) + roll(b, 00) + roll(b, 12) + roll(c, 12) + roll(d, 28) + roll(a, 28) + roll(b, 28)\n b1 = roll(b, 19) + roll(c, 19) + roll(d, 3) + roll(a, 3) + roll(b, 3) + roll(c, 7) + roll(d, 23) + roll(a,\n 23) + roll(\n b, 23) + roll(a, 15) + roll(b, 15) + roll(b, 27) + roll(c, 27) + roll(d, 11) + roll(a, 11) + roll(b, 11) + roll(\n d, 31) + roll(a, 31) + roll(b, 31)\n c1 = roll(c, 0) + roll(d, 16) + roll(a, 16) + roll(b, 16) + roll(a, 8) + roll(b, 8) + roll(b, 20) + roll(c,\n 20) + roll(\n d, 4) + roll(a, 4) + roll(b, 4) + roll(d, 24) + roll(a, 24) + roll(b, 24)\n d1 = roll(a, 8) + roll(b, 8) + roll(b, 20) + roll(c, 20) + roll(d, 4) + roll(a, 4) + roll(b, 4) + roll(d,\n 24) + roll(a,\n 24) + roll(\n b, 24)\n\n return array[0], array[1], array[2], a1, b1, array[5], array[6], array[7], array[8], c1, array[10], array[11], \\\n array[\n 12], array[13], d1, array[15]", "def example_nine():\n x = list(range(10**6))\n i = x.index(991234)", "def bintogray(x: int) -> int:\n assert x >= 0\n return x ^ (x >> 1)", "def multby2(num):\n return((num * 2) % 4294967296)" ]
[ "0.5710434", "0.56326926", "0.5514432", "0.55042744", "0.5485843", "0.5473196", "0.54713386", "0.54608226", "0.545103", "0.54507494", "0.5435761", "0.54058605", "0.54058605", "0.53963244", "0.5376808", "0.5347544", "0.5317957", "0.5304127", "0.529716", "0.52925557", "0.52832407", "0.5280162", "0.527129", "0.5260164", "0.5257703", "0.52338713", "0.52197325", "0.52175903", "0.52038556", "0.52011615" ]
0.5653409
1
! (require racket/flonum) > (flceiling 2.5) 3.0 > (flceiling 2.5) 2.0
def test_flceiling(doctest):
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_ceiling(doctest):", "def test_flfloor(doctest):", "def __floor__(self, ???):", "def __init__(self):\n BuiltinFunction.__init__(self, \"ceil\",\n conversions=dict(maxima='ceiling',\n sympy='ceiling'))", "def testCeiling(self):\n\t\tself.assertTrue(calcFlopWins(2, 3) <= 1.0)", "def __ceil__(self, ???):", "def getCeiling(self):\n if self.ceiling is not None:\n return self.ceiling\n # preserve backwards compatability for zenpacks\n for dp in self.graphPoints():\n if dp.meta_type == 'DataPointGraphPoint' and dp.format:\n try:\n lhs = dp.format.split(\".\")[0][-1]\n rhs = dp.format.split(\".\")[1][0]\n return int(lhs) - int(rhs)\n except (IndexError, ValueError, TypeError):\n # unable to parse the format just continue\n # or use the default\n pass\n return 3", "def ceil(x):\r\n # see decorator for function body\r", "def floor(x):\r\n # see decorator for function body\r", "def ceil_div_offline(value, factor):\n return ((value) + (factor)-1) // (factor)", "def __floor__(self, *args, **kwargs): # real signature unknown\n pass", "def __floor__(self, *args, **kwargs): # real signature unknown\n pass", "def __floor__(self, *args, **kwargs): # real signature unknown\n pass", "def __floor__(self, *args, **kwargs): # real signature unknown\n pass", "def __floor__(self, *args, **kwargs): # real signature unknown\n pass", "def __floor__(self, *args, **kwargs): # real signature unknown\n pass", "def __floor__(self, *args, **kwargs): # real signature unknown\n pass", "def __floor__(self, *args, **kwargs): # real signature unknown\n pass", "def __floor__(self, *args, **kwargs): # real signature unknown\n pass", "def __floor__(self, *args, **kwargs): # real signature unknown\n pass", "def __floor__(self, *args, **kwargs): # real signature unknown\n pass", "def __floor__(self, *args, **kwargs): # real signature unknown\n pass", "def __floor__(self, *args, **kwargs): # real signature unknown\n pass", "def __floor__(self, *args, **kwargs): # real signature unknown\n pass", "def __floor__(self, *args, **kwargs): # real signature unknown\n pass", "def __floor__(self, *args, **kwargs): # real signature unknown\n pass", "def test_floor(doctest):", "def ceil(x):\n return 0.0", "def give_me_a_float():\n return 5.8\n pass", "def test_flonum_special(doctest):" ]
[ "0.6180841", "0.6116166", "0.5553814", "0.54663086", "0.5450169", "0.54192716", "0.5378596", "0.5373187", "0.5312131", "0.528041", "0.5276072", "0.5276072", "0.5276072", "0.5276072", "0.5276072", "0.5276072", "0.5276072", "0.5276072", "0.5276072", "0.5276072", "0.5276072", "0.5276072", "0.5276072", "0.5276072", "0.5276072", "0.5276072", "0.5200969", "0.5163441", "0.510346", "0.5087138" ]
0.64431214
0
! (require racket/flonum) > (flfloor 2.5) 2.0 > (flfloor 2.5) 3.0
def test_flfloor(doctest):
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def ifloor(f: SupportsFloat) -> int:\n\t\t# noinspection PyTypeChecker\n\t\treturn int(np.floor(f))", "def floor(x):\r\n # see decorator for function body\r", "def floor(x):\n return 0.0", "def test_flceiling(doctest):", "def test_floor(doctest):", "def def_mpf_constant(fixed):\n def f(prec, rnd=round_fast):\n wp = prec + 20\n v = fixed(wp)\n if rnd in (round_up, round_ceiling):\n v += 1\n return normalize(0, v, -wp, bitcount(v), prec, rnd)\n f.__doc__ = fixed.__doc__\n return f", "def floor_div(a, b):\r\n # see decorator for function body\r", "def p() -> float:\n return 0.9", "def test_ceiling(doctest):", "def __floor__(self, ???):", "def testCeiling(self):\n\t\tself.assertTrue(calcFlopWins(2, 3) <= 1.0)", "def give_me_a_float():\n return 5.8\n pass", "def floor(expr: vecpy.base.Expr):\n return vecpy.function(\"floor\", expr)", "def __rfloordiv__(self, other):\n return self.__rtruediv__(other)", "def __floor__(self, *args, **kwargs): # real signature unknown\n pass", "def __floor__(self, *args, **kwargs): # real signature unknown\n pass", "def __floor__(self, *args, **kwargs): # real signature unknown\n pass", "def __floor__(self, *args, **kwargs): # real signature unknown\n pass", "def __floor__(self, *args, **kwargs): # real signature unknown\n pass", "def __floor__(self, *args, **kwargs): # real signature unknown\n pass", "def __floor__(self, *args, **kwargs): # real signature unknown\n pass", "def __floor__(self, *args, **kwargs): # real signature unknown\n pass", "def __floor__(self, *args, **kwargs): # real signature unknown\n pass", "def __floor__(self, *args, **kwargs): # real signature unknown\n pass", "def __floor__(self, *args, **kwargs): # real signature unknown\n pass", "def __floor__(self, *args, **kwargs): # real signature unknown\n pass", "def __floor__(self, *args, **kwargs): # real signature unknown\n pass", "def __floor__(self, *args, **kwargs): # real signature unknown\n pass", "def __floor__(self, *args, **kwargs): # real signature unknown\n pass", "def __floor__(self, *args, **kwargs): # real signature unknown\n pass" ]
[ "0.6094957", "0.6085185", "0.58095694", "0.5765076", "0.5732744", "0.5660084", "0.5606469", "0.5454927", "0.54418606", "0.54019386", "0.53928703", "0.53492564", "0.53274024", "0.53134686", "0.53130627", "0.53130627", "0.53130627", "0.53130627", "0.53130627", "0.53130627", "0.53130627", "0.53130627", "0.53130627", "0.53130627", "0.53130627", "0.53130627", "0.53130627", "0.53130627", "0.53130627", "0.53130627" ]
0.7762754
0
! (require racket/flonum) > (fltruncate 2.5) 2.0 > (fltruncate 2.5) 2.0 > (fltruncate +inf.0) +inf.0
def test_fltruncate(doctest):
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def trunc(x):\n return 0", "def trunc(data):\n return _make.trunc(data)", "def truncate(s):\n truncate = whenFloating $ \\c e ->\n if dangerouslySmall c e\n then 0\n else fromInteger $ c `quotInteger` magnitude (-e)", "def __trunc__(self, ???):", "def trunc_inplace(a):", "def zzX_trunc(f, p):\n return zzX_strip([ zzX_rem(g, p) for g in f ])", "def test_truncate(doctest):", "def truncate(self, pos=None):\n ...", "def trunc(self, typ):", "def auto_truncate(val):\n return val[:7]", "def trunc(value):\n\t\treturn round(value, 3) if math.modf(value)[0] != 0 else round(value)", "def truncate(string):", "def test_truncate():\n assert truncate(15.22315, 3) == 15.223\n assert truncate(15.22215, 2) == 15.22\n assert truncate(33315.22215, 2) == 33315.22\n assert truncate(-1.22215, 2) == -1.22\n assert truncate(15.92215, 2) == 15.92\n assert truncate(.00215, 2) == 0.0\n assert truncate(.00215, 1) == 0.0\n assert truncate(15.22315, 3, True) == '15.223'\n assert truncate(15.22215, 2, True) == '15.22'\n assert truncate(33315.22215, 2, True) == '33315.22'\n assert truncate(-1.22215, 2, True) == '-1.22'\n assert truncate(15.92215, 2, True) == '15.92'\n assert truncate(.00215, 2, True) == '0.00'\n assert truncate(.1, 2, True) == '0.10'\n assert truncate(.4, 1, True) == '0.4'", "def truncation(self) -> int:\n return self._truncate", "def floor_inplace(a):", "def _truncate(self):\n dif = len(self) - self._maxLen\n if dif > 0:\n #return\n self[:dif] = []", "def float_trunc(v, zerobits):\n # A float is represented in binary like this:\n # seeeeeeeefffffffffffffffffffffff\n mask = -(1L << zerobits)\n v = struct.unpack('I', struct.pack('f', v))[0]\n v &= mask\n return struct.unpack('f', struct.pack('I', v))[0]", "def ceil_inplace(a):", "def truncateFluidCache(*args, q=True, query=True, e=True, edit=True, **kwargs)->Union[None,\n Any]:\n pass", "def truncate(f, n):\n if isinstance(f, float):\n s = '{}'.format(f)\n else:\n s = f\n if 'e' in s or 'E' in s:\n return '{0:.{1}f}'.format(f, n)\n i, p, d = s.partition('.')\n return '.'.join([i, (d+'0'*n)[:n]])", "def truncate(self, count=0, reverse=True):\n if reverse:\n return self.value[:(len(self.value) - count)]\n else:\n return self.value[count:]", "def setTruncate(ln):\n\n global length, count, side\n\n if length:\n warning(\"Truncate: option set with value pending, previous setting discarded.\")\n\n side = 0 # assume 'right' or start of bar\n count = 1 # assume 1 bar only\n\n ln, opts = opt2pair(ln) # separate out the option strings\n\n # Grab the truncate length first, need this to figure the\n # value for the side option, later.\n\n if len(ln) != 1:\n error(\"Truncate: Beats must be set. Syntax is <beats> [option=value]\")\n\n beats = stof(ln[0], \"Truncate: Bar length must be value.\")\n\n if beats < 1 or beats >= gbl.QperBar:\n error(\"Tuncate: Range must be 1 to %s, not '%s'.\" % (gbl.QperBar, beats))\n\n length = int(beats * gbl.BperQ)\n\n # now parse options\n\n for cmd, opt in opts:\n cmd=cmd.upper()\n\n if cmd == 'COUNT':\n b = stoi(opt, \"Truncate: Bar COUNT must be integer.\")\n if b <1:\n error(\"Truncate: Bar COUNT must be 1 or greater.\")\n count = b\n\n elif cmd == \"SIDE\":\n opt = opt.upper()\n max = gbl.QperBar * gbl.BperQ\n\n if opt == \"LEFT\": # side to use, default==left\n side = 0\n\n elif opt == \"RIGHT\": # use the right side of pattern\n side = max - length\n\n else:\n opt = stof(opt, \"Truncate: Expecting value, not '%s'.\" % opt)\n side = int( (opt-1) * gbl.BperQ)\n if side+length > max:\n error(\"Truncate: Side value of '%g' too large.\" % opt)\n \n else:\n error(\"Truncate: '%s' is an unknown option.\" % cmd)\n\n\n if gbl.debug:\n print \"Truncate: Next %s bar(s) are %g beats, \" \\\n \"using pattern from beats %g to %g.\" \\\n % (count, beats, float(side)/gbl.BperQ, (float(side)+length)/gbl.BperQ)", "def __trunc__(self, *args, **kwargs): # real signature unknown\n pass", "def __trunc__(self, *args, **kwargs): # real signature unknown\n pass", "def __trunc__(self, *args, **kwargs): # real signature unknown\n pass", "def __trunc__(self, *args, **kwargs): # real signature unknown\n pass", "def __trunc__(self, *args, **kwargs): # real signature unknown\n pass", "def __trunc__(self, *args, **kwargs): # real signature unknown\n pass", "def __trunc__(self, *args, **kwargs): # real signature unknown\n pass", "def __trunc__(self, *args, **kwargs): # real signature unknown\n pass" ]
[ "0.6891578", "0.67059904", "0.65174705", "0.65155673", "0.650897", "0.6454256", "0.6434144", "0.64217186", "0.61807334", "0.60763943", "0.60398847", "0.6005054", "0.5927545", "0.5905438", "0.5862055", "0.57917064", "0.5771346", "0.5762463", "0.5738256", "0.5734238", "0.5696697", "0.56696457", "0.5657388", "0.5657388", "0.5657388", "0.5657388", "0.5657388", "0.5657388", "0.5657388", "0.5657388" ]
0.74525243
0
> (rational? 1) t > (rational? +inf.0) f > (rational? "hello") f > (rational? 7/3) t > (rational? 13647861237849612903845789012745781623478613289571907344901263) t
def test_rational_predicate(doctest):
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def rational_frac_tests():\n print('\\n==========================================')\n print('rfrac.py @ rational_frac_tests: //////////\\n')\n print(RationalFrac(-1), RationalFrac(0))\n # __prime_factors()\n frac0 = RationalFrac(4.5)\n frac1 = RationalFrac(-0.125)\n frac2 = RationalFrac(0.99999)\n f = [frac0, frac1, frac2]\n print('float(-0.125) =', float(f[1]))\n print('float(0.99999) =', float(f[2]))\n print('9/2 + -1/8 =', f[0] + f[1])\n print('9/2 * -1/8 =', f[0] * f[1])\n print('-1/8 * 9/2 =', f[1] * f[0])\n print(f)\n print('frac(-0/1) + frac(-0/1) =',\n RationalFrac(-0) + RationalFrac(-0))\n f3 = RationalFrac('-7/29')\n print(f3)\n print(RationalFrac(25, 1000))\n print('\\nrfrac.py @ end of rational_frac_tests ////')\n print('==========================================\\n')", "def test_rational(doctest):", "def test_find_least_rational_surfaces():\n # simple test, linear iota going from 1 to 3\n iota = PowerSeriesProfile([1, 2])\n rhor, ior = find_most_rational_surfaces(iota, 10)\n rho, io = find_least_rational_surfaces(iota, 10)\n # to compare how rational/irrational things are, we use the length of the\n # continued fraction. Not a great test due to rounding errors, but seems to work\n lio = [len(dec_to_cf(i)) for i in io]\n lior = [len(dec_to_cf(i)) for i in ior]\n max_rational = max(lior)\n\n assert np.all(np.array(lio) > max_rational)", "def is_rational(symbol):\n return isa(symbol, fractions.Fraction) or _is_real(symbol)", "def rational_function_reduce(rational_function):\n phi = rational_function\n F = phi.numerator()\n G = phi.denominator()\n comm_factor = gcd(F,G)\n return (F.quo_rem(comm_factor)[0]) / (G.quo_rem(comm_factor)[0])", "def test_gt(self):\n f12: Fraction = Fraction(1, 2)\n f34: Fraction = Fraction(3, 4)\n f105: Fraction = Fraction(10, 5)\n self.assertTrue(f34 > f12)\n self.assertFalse(f12 > f105)\n self.assertFalse(f12 > f12)", "def test_fraction_rich_comparisson(self):\n fract1 = source.Fraction(5, 2) # 2.5\n fract2 = source.Fraction(3, 2) # 1.5\n fract3 = source.Fraction(25, 10) # 2.5\n\n self.assertFalse(fract1 != fract3) # 2.5 != 2.5\n self.assertTrue(fract1 == fract3) # 2.5 == 2.5\n self.assertTrue(fract2 < fract3) # 1.5 < 2.5\n\n # Let's try the other way\n self.assertTrue(fract1 >= fract2) # 2.5 >= 1.5\n self.assertFalse(fract2 >= fract3) # 1.5 >= 2.5\n\n # Let's try with other types\n self.assertTrue(fract1 >= 2) # 2.5 >= 2\n self.assertTrue(fract2 == 1.5) # 1.5 == 1.5\n\n # Let's try the other way with other types\n self.assertTrue(2 <= fract1) # 2 <= 2.5\n self.assertTrue(1.5 == fract2) # 1.5 == 1.5\n\n self.assertTrue(10 > fract1) # 10 > 2.5\n self.assertFalse(10 < fract1) # 10 < 2.5\n self.assertTrue(fract1 < 10) # 2.5 < 10\n self.assertFalse(fract1 > 10) # 2.5 > 10", "def test_real(self):\n\n real = common_math.real\n\n self.assertTrue(real(3.75) + real(4.75) == real(8.5))\n self.assertTrue(real(2.5) * real(-1.5) == -real(3.75))\n\n pi_1 = to_real(real, Fraction(311, 99))\n pi_2 = to_real(real, Fraction(333, 106))\n pi_3 = to_real(real, Fraction(355, 113))\n\n self.assertTrue(pi_1 < pi_2)\n self.assertTrue(pi_2 < pi_3)", "def isRational(self):\n return _libsbml.ASTNode_isRational(self)", "def fromRationalRepetend(rat, limit=Nothing):\n\n def longDiv(n):\n \"\"\"\n :param n: long\n :return: Either (Scientific, Rational) (Scientific, Maybe Int)\n \"\"\"\n return limit.fold(longDivNoLimit(0, 0, map.empty, n),\n lambda l: longDivWithLimit(-l, n))\n\n # todo - this tail recursion won't stand, man\n def longDivNoLimit(c, e, ns, n):\n \"\"\"\n Divide the numerator by the denominator using long division.\n\n :param c: long\n :param e: long\n :param ns: Map long long\n :param n: long\n :return (Scientific, Maybe long)\n \"\"\"\n if n == 0:\n return (Scientific(c, e), Nothing)\n else:\n e_prime = map.lookup(n, ns)\n if isJust(e_prime):\n return (Scientific(c, e), maybe.map(negate, e_prime))\n elif n < rat.denominator:\n return longDivNoLimit(c * 10, e - 1, map.insert(n, e, ns), n * 10)\n else:\n (q, r) = quotRemInteger(n, rat.denominator)\n return longDivNoLimit(c + q, e, ns, r)\n\n def longDivWithLimit(l, n):\n \"\"\"\n :param l: long\n :param n: long\n :return: Either (Scientific, Rational) (Scientific, Maybe Int)\n \"\"\"\n\n # todo - this tail recursion won't stand, man\n def go(c, e, ns, n):\n \"\"\"\n :param c: long\n :param e: long\n :param ns: Map long long\n :param n: long\n :return: Either (Scientific, Rational) (Scientific, Maybe Int)\n \"\"\"\n if n == 0:\n return Right(Scientific(c, e), Nothing)\n else:\n e_prime = map.lookup(n, ns)\n if isJust(e_prime):\n return Right(Scientific(c, e), maybe.map(negatve, e_prime))\n elif e <= l:\n return Left(Scientific(c, e), n % (d * magnitude (-e)))\n elif n < d:\n return go(c * 10, e - 1, map.insert(n, e, ns), n * 10)\n else:\n (q, r) = quotRemInteger(n, rat.denominator)\n return go(c + q, e, ns, r)\n\n return go(0, 0, map.empty)\n\n if rat.denominator == 0:\n raise ZeroDivisionError\n\n elif rat.numerator < 0:\n return either.fold(\n longDiv(-num),\n lambda (s, r ): Left( (-s, -r) ),\n lambda (s, mb): Right( (-s, mb) ))\n\n else:\n return longDiv(num)", "def test_find_most_rational_surfaces():\n # simple test, linear iota going from 1 to 3\n iota = PowerSeriesProfile([1, 2])\n rho, io = find_most_rational_surfaces(iota, 5)\n np.testing.assert_allclose(rho, np.linspace(0, 1, 5), atol=1e-14, rtol=0)\n np.testing.assert_allclose(io, np.linspace(1, 3, 5), atol=1e-14, rtol=0)", "def change_to_rational(number: float) -> Tuple[int, int]:\n f = Fraction(str(number))\n return (f.numerator, f.denominator)", "def test_GreaterThan(self):\n self.assertTrue(Fraction(9,10)>Fraction(7,10))", "def isqrt( a, b ):\n return a*a - b", "def test_3_operands(self):\n f12: Fraction = Fraction(1, 2)\n f34: Fraction = Fraction(3, 4)\n f44: Fraction = Fraction(4, 4)\n f84: Fraction = Fraction(8, 4)\n f48: Fraction = Fraction(4, 8)\n f816: Fraction = Fraction(8, 16)\n self.assertTrue(f12 + f34 + f44 == Fraction(72, 32))\n self.assertTrue(f12 - f34 - f44 == Fraction(-5,4))\n self.assertTrue(f12 * f34 * f44 == Fraction(3, 8))\n self.assertTrue(f12 / f34 / f44 == Fraction(4, 6))\n self.assertTrue(f12 == f48 == f816)\n self.assertFalse(f12 == f816 == f34)\n self.assertTrue(f12 != f34 != f44)\n self.assertFalse(f12 != f48 != f816)\n self.assertTrue(f12 < f34 < f44)\n self.assertFalse(f84 < f44 < f12)\n self.assertTrue(f12 <= f12 <= f48)\n self.assertFalse(f84 <= f44 < f12)\n self.assertTrue(f44 > f34 > f12)\n self.assertFalse(f12 > f44 > f84)\n self.assertTrue(f12 >= f48 >= f816)\n self.assertFalse(f12 >= f44 >= f816)", "def test_GreaterThanorEqualto(self):\n self.assertTrue(Fraction(7,10)>=Fraction(7,10))", "def test_ge(self):\n f12: Fraction = Fraction(1, 2)\n f34: Fraction = Fraction(3, 4)\n f93: Fraction = Fraction(9, 3)\n f124: Fraction = Fraction(12, 4)\n self.assertTrue(f12 >= f34)\n self.assertTrue(f93 >= f124)\n self.assertFalse(f93 >= f12)", "def fromRational(rat):\n def longDiv(c, e, n):\n \"\"\"\n Divide the numerator by the denominator using long division.\n\n :param c: long\n :param e: long\n :param n: long\n :return: Scientific\n \"\"\"\n if n == 0:\n return Scientific(c, e)\n else:\n # TODO: Use a logarithm here!\n # TODO: Can't use tail recursion like this in python!\n if n < d:\n return longDiv(c * 10, e - 1, n * 10)\n else:\n (q, r) = quotRemInteger(n, d)\n return longDiv(c+q, e, r)\n\n d = rat.denominator\n\n if d == 0:\n raise ZeroDivisionError\n else:\n return rational.positivize(longDiv(0, 0), rat.numerator)", "def test_mixing_ratio_from_specific_humidity_no_units():\n q = 0.012\n w = mixing_ratio_from_specific_humidity(q)\n assert_almost_equal(w, 0.01215, 3)", "def test_solveset_real_rational():\n assert solveset_real((x - y**3) / ((y**2)*sqrt(1 - y**2)), x) \\\n == FiniteSet(y**3)\n # issue 4486\n assert solveset_real(2*x/(x + 2) - 1, x) == FiniteSet(2)", "def is_rational(self):\n return self.col[1:, :].is_zero_matrix", "def dectofr(x):\n # n = int(floor(x))\n # x -= n\n # if x < error:\n # # return (n, 1)\n # return Fraction(n, 1)\n # elif 1 - error < x:\n # # return (n+1, 1)\n # return Fraction(n + 1, 1)\n #\n # # The lower fraction is 0/1\n # lower_n = 0\n # lower_d = 1\n # # The upper fraction is 1/1\n # upper_n = 1\n # upper_d = 1\n # while True:\n # # The middle fraction is (lower_n + upper_n) / (lower_d + upper_d)\n # middle_n = lower_n + upper_n\n # middle_d = lower_d + upper_d\n # # If x + error < middle\n # if middle_d * (x + error) < middle_n:\n # # middle is our new upper\n # upper_n = middle_n\n # upper_d = middle_d\n # # Else If middle < x - error\n # elif middle_n < (x - error) * middle_d:\n # # middle is our new lower\n # lower_n = middle_n\n # lower_d = middle_d\n # # Else middle is our best fraction\n # else:\n # # return (n * middle_d + middle_n, middle_d)\n # # return \"{0}/{1}\".format(n*middle_d+middle_n,middle_d)\n # return Fraction(n * middle_d + middle_n, middle_d)\n\n n = str(x)\n d = 1\n dig = digitsafterdecimal(x)\n multiplier = 10 ** dig\n n = n.replace(\".\", \"\")\n return Fraction(int(n), int(d * multiplier))", "def nearly_equal(a, b, sig_fig=5):\n return a == b or int(a*10**sig_fig) == int(b*10**sig_fig)", "def test_solveset_real_rational():\n x = Symbol('x', real=True)\n y = Symbol('y', real=True)\n assert solveset_real((x - y**3) / ((y**2)*sqrt(1 - y**2)), x) \\\n == FiniteSet(y**3)\n # issue 4486\n assert solveset_real(2*x/(x + 2) - 1, x) == FiniteSet(2)", "def test_fraction_math_ops(self):\n fract1 = source.Fraction(5, 3)\n fract2 = source.Fraction(2, 3)\n self.assertEqual(fract1 + fract2, source.Fraction(7, 3))\n self.assertEqual(fract1 + 5, source.Fraction(20, 3))\n self.assertEqual(3 + fract1, source.Fraction(14, 3))\n self.assertEqual(fract1 * fract2, source.Fraction(10, 9))\n self.assertEqual(5 * fract2, source.Fraction(10, 3))", "def lift_rational_field(q, field):\n if not field:\n return Constructible(q)\n else:\n zero = Constructible.lift_rational_field(0, field[1])\n lift = Constructible.lift_rational_field(q, field[1])\n return Constructible(lift, zero, field)", "def rationalize(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT):\n result: List[TOKEN] = []\n passed_float = False\n for toknum, tokval in tokens:\n if toknum == NAME:\n if tokval == 'Float':\n passed_float = True\n tokval = 'Rational'\n result.append((toknum, tokval))\n elif passed_float == True and toknum == NUMBER:\n passed_float = False\n result.append((STRING, tokval))\n else:\n result.append((toknum, tokval))\n\n return result", "def fraction_to_proper_fraction(rational):\n assert isinstance(rational, Fraction), repr(rational)\n quotient = int(rational)\n residue = rational - quotient\n return quotient, residue", "def fractionify(n):\n i = 0\n while True:\n if not n * 10 ** i % 1:\n break\n i += 1\n return n * 10 ** i, 10 ** i", "def t(o, r):\n return (r/o)**2" ]
[ "0.6784243", "0.6648297", "0.64456624", "0.6416477", "0.62569875", "0.60745555", "0.60259306", "0.5970766", "0.58682173", "0.58424383", "0.5784617", "0.57590175", "0.5710712", "0.5709708", "0.57082677", "0.57038885", "0.56855655", "0.5633985", "0.5622209", "0.5607985", "0.55999357", "0.5595871", "0.5566985", "0.55609787", "0.55551493", "0.55521166", "0.55268735", "0.5523104", "0.54988265", "0.54906005" ]
0.7162609
0
Find all simple cycles in a graph
def simple_cycles(g: Graph) -> List[List[Branch]]: # Make copy because the graph gets altered during the algorithm graph_copy = g.copy() branch_map = {} copy_result = list() # Create map to allow returning original branches for branch in g.branches: branch_map[branch.id] = branch # Yield every elementary cycle in python graph G exactly once # Expects a dictionary mapping from vertices to iterables of vertices def _unblock(thisnode, blocked, B): stack = set([thisnode]) while stack: node = stack.pop() if node in blocked: blocked.remove(node) stack.update(B[node]) B[node].clear() sccs = [(graph_copy, scc) for scc in strongly_connected_components(graph_copy)] while sccs: current_graph, scc = sccs.pop() startnode = scc.pop() path = [startnode.id] pathBranches = [] blocked = set() closed = set() blocked.add(startnode.id) B = defaultdict(set) stack = [(startnode, list(startnode.outgoing))] while stack: thisnode, nbrs = stack[-1] if nbrs: branch = nbrs.pop() nextnode = branch.end if nextnode.id == startnode.id: result = pathBranches[:] result.append(branch) copy_result.append(result) closed.update(path) elif nextnode.id not in blocked: path.append(nextnode.id) pathBranches.append(branch) stack.append((nextnode, list(nextnode.outgoing))) closed.discard(nextnode.id) blocked.add(nextnode.id) continue if not nbrs: if thisnode.id in closed: _unblock(thisnode.id, blocked, B) else: for nbr in map(lambda x: x.end, thisnode.outgoing): if thisnode.id not in B[nbr.id]: B[nbr.id].add(thisnode.id) stack.pop() path.pop() if (pathBranches): pathBranches.pop() startnode.remove() subgraph = current_graph.subgraph(set(scc)) new_scc = strongly_connected_components(subgraph) sccs.extend([(subgraph, scc) for scc in new_scc]) for loop in copy_result: yield list(map(lambda b: branch_map[b.id], loop))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def find_all_cycles(s,graph):\n\n grph = u.edge_to_list_dict(graph)\n node_cnt = len(grph)\n k = z.Int(\"k\")\n syms = [z.Int('node%s'%i) for i in range(node_cnt)]\n\n # s.add(syms[0] == 0) # start node is a 0\n s.add(k < node_cnt)\n s.add(k > 1)\n\n o = z.Optimize()\n\n # for source, sinks in sgraph.s_adj_list():\n for i in range(node_cnt):\n s.add(syms[i] >= 0)\n s.add(syms[i] <= k)\n s.add(z.Or([syms[j] == ((syms[i] + 1) % k) for j in grph[i]]) == (syms[i] == 0))\n\n\n r = []\n m = []\n\n # o.minimize(z.Sum([syms[i] for i in range(node_cnt)]))\n s.add(z.Product([syms[i] for i in range(node_cnt)]) == 0)\n done = False\n while not done:\n if s.check() == z.sat:\n m = s.model()\n r.append(m)\n s.add(k != m[k])\n else:\n done = True\n\n return r", "def test_cycles():\n graph = Graph()\n for one, two in [(1, 2), (2, 3), (3, 1)]:\n graph.add_edge(one, two)\n cycles = list(graph.find_cycles())\n eq_(len(cycles), 1)\n eq_(cycles[0], [1, 2, 3])", "def find_cycle(self):\n # from guido's blog :\n # http://neopythonic.blogspot.com/2009/01/detecting-cycles-in-directed-graph.html\n worklist = set(self.successors)\n while worklist:\n stack = [worklist.pop()]\n while stack:\n top = stack[-1]\n for node in self.successors.get(top, ()):\n try:\n # raises ValueError if node is not in stack.\n cycle = stack[stack.index(node) :]\n succs = dict(\n (source, [cycle[(i + 1) % len(cycle)]])\n for i, source in enumerate(cycle)\n )\n return Digraph(succs, self.get_score, self.get_label)\n except ValueError:\n pass\n if node in worklist:\n stack.append(node)\n worklist.remove(node)\n break\n else:\n stack.pop()\n return None", "def get_elementary_cycles(self):\n tarjan = Tarjan(self.graph)\n for ssc in tarjan.ssc():\n for start_node in ssc:\n least_node = min(ssc) # Some kind of ordering\n self.find_cycles(least_node, least_node)\n # ssc changes at each iteration, since we remove the\n # least node to avoid unnecesary DFSs\n ssc = tarjan.remove_useless_edges(ssc, least_node)\n return self.cycles", "def find_cycles(graph, from_node = None):\n cycle = []\n if not from_node:\n from_node = graph.keys()[0]\n \n keep_reading = True\n while keep_reading:\n to_nodes = graph[from_node]\n #pick first approach\n if len(to_nodes) >= 1:\n \n interaction = find_next(to_nodes, from_node)\n if interaction:\n if len(to_nodes) > 1:\n split.append(from_node)\n used_edges.append(interaction)\n cycle.append(interaction)\n \n from_node = interaction[1]\n \n else:\n keep_reading = False\n else:\n keep_reading = False\n\n\n if check_cycle(cycle):\n cycles.append(cycle)\n\n return split", "def has_cycle(graph):\n ds = DisjointSet()\n\n # creates a set of all graph nodes\n node_set = set()\n for edge in graph:\n node_set.add(edge.node1)\n node_set.add(edge.node2)\n\n for item in node_set:\n ds.make_set(item)\n\n for edge in graph:\n same_set = ds.union(edge.node1, edge.node2)\n if same_set:\n return True\n\n return False", "def has_cycles(graph):\n path = set()\n\n def visit(node):\n path.add(node)\n for neighbour in graph.edges[node]:\n if neighbour in path or visit(neighbour):\n return True\n path.remove(node)\n return False\n\n return any(visit(node) for node in graph.nodes)", "def test_cycle(self):\n g = Graph(3)\n g.add_edge(0, 1)\n g.add_edge(0, 2)\n # g.add_edge(0, 0)\n assert g.contains_cycle() is False\n g.add_edge(1, 2)\n assert g.contains_cycle() is True", "def cyclic(n):\n if seen[n]: return seen[n] == -1\n seen[n] = -1 #GRAY\n if any(cyclic(nn) for nn in digraph.get(n, []) if seen[nn] != 1): return True\n seen[n] = 1 #BLACK\n ans.append(n)\n return False", "def cyclic(g):\n path = set()\n visited = set()\n\n def visit(vertex):\n if vertex in visited:\n return False\n visited.add(vertex)\n path.add(vertex)\n for neighbour in g.parents_of(vertex):\n if neighbour in path or visit(neighbour):\n return True\n path.remove(vertex)\n return False\n\n return any(visit(v) for v in g.indices)", "def four_cycles(graph, vertex):\n count = 0\n for i in range(len(graph[vertex])):\n for j in range(i + 1, (len(graph[vertex]))):\n \tnode1 = graph[vertex][i]\n \tnode2 = graph[vertex][j]\n \tfor neighbour in graph[node2]:\n \t\tif neighbour != vertex and neighbour in graph[node1]:\n \t\t\tcount += 1\n return count", "def creates_cycle(connections, test):\n node_in, node_out = test\n\n if node_in == node_out:\n # Self-loop\n return True\n\n visited = {node_out}\n while True:\n num_added = 0\n for a, b in connections:\n if a in visited and b not in visited:\n if b == node_in:\n return True\n\n visited.add(b)\n num_added += 1\n\n if num_added == 0:\n return False", "def remove_cycle_recur(self):\n \n visited = set()\n path = []\n \n for node in self.node_set:\n if node not in visited:\n min_edge = self.remove_cycle_helper(node, visited, path)\n visited.clear()\n path.clear()\n if min_edge is not None:\n # if there is a cycle and the min weight is found\n if len(min_edge) == 2:\n return min_edge\n \n visited.clear()\n path.clear()\n return []", "def five_cycles(graph, vertex):\n count = 0\n for i in range(len(graph[vertex])):\n for j in range(i + 1, (len(graph[vertex]))):\n \tnode1 = graph[vertex][i]\n \tnode2 = graph[vertex][j]\n \tfor neighbour1 in graph[node1]:\n \t\tif neighbour1 != vertex and neighbour1 != node2:\n \t\t\tfor neighbour2 in graph[node2]:\n \t\t\t\tif neighbour2 != vertex and neighbour2 != node1 and neighbour2 in graph[neighbour1]:\n\t\t \t\t\tcount += 1\n return count", "def has_cycle(G,start):\n if G == None:\n return False\n else:\n for vertex in G:\n vertex.setColor(\"white\")\n vertex.setPredecessor(None)\n vertex.setDistance(sys.maxint)\n vertex.setEntryTime(0)\n vertex.setExitTime(0)\n \n dfsTraversal = []\n stack = []\n time = 0\n start.setColor(\"gray\")\n start.setPredecessor(None)\n time += 1\n start.setEntryTime(time)\n stack.append(start)\n while stack:\n currNode = stack.pop()\n dfsTraversal.append(currNode.getId())\n for node in currNode.getConnections():\n if node.getColor() == \"gray\":\n return True\n if node.getColor() == \"white\":\n time += 1\n node.setColor(\"gray\")\n node.setPredecessor(currNode)\n node.setEntryTime(time)\n stack.append(node)\n currNode.setColor(\"black\")\n time += 1\n currNode.setExitTime(time)\n \n return False", "def all_simple_cycles(self, starting_vertices=None, rooted=False,\n max_length=None, trivial=False):\n return list(self.all_cycles_iterator(starting_vertices=starting_vertices, simple=True, rooted=rooted, max_length=max_length, trivial=trivial))", "def find_eulerian_cycle(adj_dict, edges):\n if not adj_dict:\n return []\n\n checked = [False] * len(edges)\n list_keys = list(adj_dict.keys())\n for i in list_keys: # the first time will return true anyway\n cycle = []\n if dfs(i, adj_dict, edges, checked, cycle, i):\n return cycle\n return cycle", "def _all_cycles_iterator_vertex(self, vertex, starting_vertices=None, simple=False,\n rooted=False, max_length=None, trivial=False,\n remove_acyclic_edges=True):\n if starting_vertices is None:\n starting_vertices = [vertex]\n # First enumerate the empty cycle\n if trivial:\n yield [vertex]\n # First we remove vertices and edges that are not part of any cycle\n if remove_acyclic_edges:\n sccs = self.strongly_connected_components()\n d = {}\n for id, component in enumerate(sccs):\n for v in component:\n d[v] = id\n h = copy(self)\n h.delete_edges([(u,v) for (u,v) in h.edge_iterator(labels=False) if d[u] != d[v]])\n else:\n h = self\n queue = [[vertex]]\n if max_length is None:\n from sage.rings.infinity import Infinity\n max_length = Infinity\n while queue:\n path = queue.pop(0)\n # Checks if a cycle has been found\n if len(path) > 1 and path[0] == path[-1]:\n yield path\n # Makes sure that the current cycle is not too long\n # Also if a cycle has been encountered and only simple cycles are allowed,\n # Then it discards the current path\n if len(path) <= max_length and (not simple or path.count(path[-1]) == 1):\n for neighbor in h.neighbor_out_iterator(path[-1]):\n # If cycles are not rooted, makes sure to keep only the minimum\n # cycle according to the lexicographic order\n if rooted or neighbor not in starting_vertices or path[0] <= neighbor:\n queue.append(path + [neighbor])", "def _subtour(edges,n):\n visited = [False]*n\n cycles = []\n costs = []\n selected = [[] for i in range(n)]\n for x,y in edges:\n selected[x].append(y)\n while True:\n current = visited.index(False)\n thiscycle = [current]\n while True:\n visited[current] = True\n neighbors = [x for x in selected[current] if not visited[x]]\n if len(neighbors) == 0:\n break\n current = neighbors[0]\n thiscycle.append(current)\n cycles.append(thiscycle)\n costs.append(len(thiscycle))\n if sum(costs) == n:\n break\n return cycles[costs.index(min(costs))]", "def test_find_cycles_not_conected(self):\n self._build_sample_graph()\n # Adding cycle g -> h -> g\n sg = self.skill_graph.add(Skill.build('g', ''))\n sh = self.skill_graph.add(Skill.build('h', ''))\n self.skill_graph.add_prerequisite(sg.id, sh.id)\n self.skill_graph.add_prerequisite(sh.id, sg.id)\n skill_map = SkillMap.load(self.course)\n expected0 = [sg.id, sh.id]\n successors = skill_map.build_successors()\n result = SkillMapMetrics(skill_map).simple_cycles()\n self.assertEqual(sorted(result[0]), expected0)", "def scc(graph, reverse_graph, nodes):\n\n out = defaultdict(list)\n track = Track()\n dfs_loop(reverse_graph, nodes, track)\n sorted_nodes = sorted(track.finish_time,\n key=track.finish_time.get, reverse=True)\n track.current_time = 0\n track.current_source = None\n track.explored = set()\n dfs_loop(graph, sorted_nodes, track)\n for lead, vertex in groupby(sorted(track.leader, key=track.leader.get),\n key=track.leader.get):\n out[lead] = list(vertex)\n\n return out", "def all_cycles_iterator(self, starting_vertices=None, simple=False,\n rooted=False, max_length=None, trivial=False):\n if starting_vertices is None:\n starting_vertices = self\n # Since a cycle is always included in a given strongly connected\n # component, we may remove edges from the graph\n sccs = self.strongly_connected_components()\n d = {}\n for id, component in enumerate(sccs):\n for v in component:\n d[v] = id\n h = copy(self)\n h.delete_edges([ (u,v) for (u,v) in h.edge_iterator(labels=False)\n if d[u] != d[v] ])\n # We create one cycles iterator per vertex. This is necessary if we\n # want to iterate over cycles with increasing length.\n vertex_iterators = dict([(v, h._all_cycles_iterator_vertex( v\n , starting_vertices=starting_vertices\n , simple=simple\n , rooted=rooted\n , max_length=max_length\n , trivial=trivial\n , remove_acyclic_edges=False\n )) for v in starting_vertices])\n cycles = []\n for vi in vertex_iterators.values():\n try:\n cycle = next(vi)\n cycles.append((len(cycle), cycle))\n except(StopIteration):\n pass\n # Since we always extract a shortest path, using a heap\n # can speed up the algorithm\n from heapq import heapify, heappop, heappush\n heapify(cycles)\n while cycles:\n # We choose the shortest available cycle\n _, shortest_cycle = heappop(cycles)\n yield shortest_cycle\n # We update the cycle iterator to its next available cycle if it\n # exists\n try:\n cycle = next(vertex_iterators[shortest_cycle[0]])\n heappush(cycles, (len(cycle), cycle))\n except(StopIteration):\n pass", "def find_cycles(self,max_cycle_len=4,starting_edges=None,check_area=True):\n def traverse(a,b):\n cs=self.angle_sort_adjacent_nodes(b,ref_nbr=a)\n return b,cs[-1]\n\n visited=set() # directed tuple of nodes\n\n cycles=[]\n\n if starting_edges is None:\n starting_edges=self.valid_edge_iter()\n\n for j in starting_edges:\n if j % 10000==0:\n print(\"Edge %d/%d, %d cycles\"%(j,self.Nedges(),len(cycles)))\n # iterate over the two half-edges\n for A,B in (self.edges['nodes'][j], self.edges['nodes'][j,::-1]):\n cycle=[A]\n\n while (A,B) not in visited and len(cycle)<max_cycle_len:\n visited.add( (A,B) )\n cycle.append(B)\n A,B = traverse(A,B)\n if B==cycle[0]:\n if check_area:\n A=signed_area( self.nodes['x'][cycle] )\n if A>0:\n cycles.append(cycle)\n else:\n cycles.append(cycle)\n break\n return cycles", "def test_find_cycles_multiple_cycles(self):\n self._build_sample_graph()\n # Adding cycle a -> d -> a\n self.skill_graph.add_prerequisite(self.sa.id, self.sd.id)\n # Adding cycle g -> h -> g\n sg = self.skill_graph.add(Skill.build('g', ''))\n sh = self.skill_graph.add(Skill.build('h', ''))\n self.skill_graph.add_prerequisite(sg.id, sh.id)\n self.skill_graph.add_prerequisite(sh.id, sg.id)\n\n expected = [[self.sa.id, self.sd.id], [sg.id, sh.id]]\n skill_map = SkillMap.load(self.course)\n successors = skill_map.build_successors()\n result = SkillMapMetrics(skill_map).simple_cycles()\n self.assertEqual(len(result), len(expected))\n for cycle in result:\n self.assertIn(sorted(cycle), expected)", "def path(g): #g: graph\n marked = set()\n nodes = set(g.nodes) \n output = list()\n def recursive(g):\n for i in nodes.copy():\n d = dependents(g,i)\n if (not d) or all(dd in marked for dd in d):\n output.append((i,g.nodes[i]['word']))\n marked.add(i)\n nodes.remove(i)\n if nodes==set([0]):\n break\n recursive(g)\n break\n recursive(g)\n return output", "def cycle(self):\n # Iteratively remove all leaves from the graph\n discard = set(self.leaves())\n parents = set()\n for node in discard:\n parents.update(node.parents())\n n = True\n while n: # Keep removing leaves until we can't remove any more\n n = 0 # Count how many leaves we can remove in this pass\n new_parents = set()\n for mother in parents:\n if mother.children() - discard:\n new_parents.add(mother)\n else:\n n += 1\n discard.add(mother)\n new_parents.update(mother.parents())\n parents = new_parents\n if not parents: # If we removed everything, there are no cycles \n return False\n else: # If there is a cycle, do the same with roots\n discard_top = set(self.roots())\n children = set()\n for node in discard_top:\n children.update(node.children())\n n = True\n while n:\n n = 0\n new_children = set()\n for daughter in children:\n if daughter.parents() - discard_top:\n new_children.add(daughter)\n else:\n n += 1\n discard_top.add(daughter)\n new_children.update(daughter.children())\n children = new_children\n return self.nodes() - discard - discard_top", "def _check_cycles(self, graph):\n if list(nx.simple_cycles(graph)):\n raise AbstractGraphError('Cycles in graph')", "def find_already_eulerian_cycle(adj_dict, edges):\n if not adj_dict:\n return []\n\n checked = [False] * len(edges)\n list_keys = list(adj_dict.keys())\n for i in list_keys: # the first time will return true anyway\n cycle = [i]\n if dfs_eulerian(i, adj_dict, edges, checked, cycle, i):\n return cycle\n return cycle", "def get_non_repeat_nodes(G, path):\n sing_nodes = []\n for nd in path:\n if G.out_degree(nd)==1 and G.in_degree(nd)==1:\n sing_nodes.append(nd)\n return sing_nodes", "def is_acyclic(graph):\n visited = []\n dfs_seq = DFSIterator(graph)\n\n for node in dfs_seq:\n visited.insert(0, node)\n node_neighbors = graph.get_neighbors(node)\n \n for neighbor in node_neighbors:\n if neighbor in visited:\n return False\n\n return True" ]
[ "0.78507674", "0.74452114", "0.70848405", "0.70129675", "0.69033825", "0.67549735", "0.67269826", "0.67196727", "0.66163373", "0.6600396", "0.6543087", "0.65245026", "0.64197814", "0.6418425", "0.63913023", "0.6387601", "0.63739425", "0.6307837", "0.6288959", "0.62879014", "0.62312114", "0.62290823", "0.62283444", "0.6219189", "0.61987776", "0.61797786", "0.6175765", "0.615332", "0.6152516", "0.614748" ]
0.7579529
1
Note that `channel` must be the same pika channel instance via which the message being ACKed was retrieved (AMQP protocol constraint).
def ack_message(channel, delivery_tag): global logger if channel.is_open: channel.basic_ack(delivery_tag) logger.debug("Channel is acked!") else: # Channel is already closed, so we can't ACK this message; # log and/or do something that makes sense for your app in this case. logger.debug("Channel is closed!")
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def acknowledge_message(self, channel, delivery_tag):\n logger.info('Acknowledging message %s', delivery_tag)\n channel.basic_ack(delivery_tag)", "def acknowledgement(self, message: Message[ValueType]):", "def acknowledge(self, message: Message[ValueType]) -> Message[ValueType]:", "def get_msg(self, my_queue):\n self.channel.basic_qos(prefetch_count=COUNT)\n try:\n for method_frame, properties, body in self.channel.consume(my_queue):\n self.channel.basic_ack(method_frame.delivery_tag)\n return body\n except pika.exceptions, err_msg:\n log.error(err_msg)\n return False", "def handle_channel_assigned(self, channel):\n logger.debug(\"AIRepository was assigned channel {}\".format(channel))\n self.channel = channel", "def message_process(self, channel: pika.adapters.blocking_connection.BlockingChannel,\n method_frame, header_frame, body):\n LOGGER.info('routing key: {routing_key} | headers: {headers} | body: {body}'.format(\n routing_key=method_frame.routing_key,\n headers=header_frame.headers,\n body=body.decode(),\n ))\n channel.basic_ack(method_frame.delivery_tag)\n # channel.basic_nack(delivery_tag=method_frame.delivery_tag, multiple=False, requeue=True)", "def finish_message(self, basic_deliver, future):\n delivery_tag = basic_deliver.delivery_tag\n\n if not future.exception():\n try:\n self.logger.debug(\"Acking message %s\", delivery_tag)\n self._channel.basic_ack(delivery_tag)\n except Exception as ex:\n self.logger.exception(\n \"Error acking message %s, about to shut down: %s\", delivery_tag, ex\n )\n self._panic_event.set()\n else:\n real_ex = future.exception()\n\n if isinstance(real_ex, RepublishRequestException):\n try:\n with BlockingConnection(self._connection_parameters) as c:\n headers = real_ex.headers\n headers.update({\"request_id\": real_ex.request.id})\n props = BasicProperties(\n app_id=\"beer-garden\",\n content_type=\"text/plain\",\n headers=headers,\n priority=1,\n delivery_mode=PERSISTENT_DELIVERY_MODE,\n )\n c.channel().basic_publish(\n exchange=basic_deliver.exchange,\n properties=props,\n routing_key=basic_deliver.routing_key,\n body=SchemaParser.serialize_request(real_ex.request),\n )\n\n self._channel.basic_ack(delivery_tag)\n except Exception as ex:\n self.logger.exception(\n \"Error republishing message %s, about to shut down: %s\",\n delivery_tag,\n ex,\n )\n self._panic_event.set()\n elif isinstance(real_ex, DiscardMessageException):\n self.logger.info(\n \"Nacking message %s, not attempting to requeue\", delivery_tag\n )\n self._channel.basic_nack(delivery_tag, requeue=False)\n else:\n # If request processing throws anything else we terminate\n self.logger.exception(\n \"Unexpected exception during request %s processing, about \"\n \"to shut down: %s\",\n delivery_tag,\n real_ex,\n exc_info=False,\n )\n self._panic_event.set()", "def handle_message(self, data, channel):\n pass", "def consume_message(message):\n # Assign the message to the global drone_message\n global drone_message\n drone_message = message\n # The Rabbit mq runs in the localhost and the username , password is\n # athavan\n credentials = pika.PlainCredentials('guest', 'guest')\n # Pass the mqhost , port , virtualhost and credentials\n parameters = pika.ConnectionParameters('localhost', 5672, '/', credentials)\n connection = pika.SelectConnection(parameters, on_connected)\n try:\n connection.ioloop.start()\n except KeyboardInterrupt:\n # close the connnection\n connection.close()\n # loop until we are fully closed. It will stop on its own\n connection.ioloop.start()", "def consume_ack(self, event):\n pass", "def handle_delivery(channel, method, header, body):\n print(body)", "def acknowledge_message(self, delivery_tag):\n self.logger.info('acknowledging message %s', delivery_tag)\n self._channel.basic_ack(delivery_tag)", "def acknowledge_message(self, delivery_tag):\n logger.info('Acknowledging message %s process %s consumer_id %s', delivery_tag, threading.current_thread, str(self.consumer_id))\n self._channel.basic_ack(delivery_tag)", "def on_message_received(ch, method, properties, body):\n # the body contains the command flag followed by a colon ':' and the message for the drone\n # decode the body to utf8\n received_bytes = body.decode('utf-8')\n # split the received_bytes to get the command _flag and message\n recieved_message = received_bytes.split(':')\n # since rabbit mq body is a byte\n if (str(recieved_message[0]) == \"c01\"):\n # c01 - command center orders the drone to deliver a item\n print(\"Order Received from the command center to deliver an item to the following address \\n\", str(\n recieved_message[1]))\n time.sleep(2)\n # print in the drone's console that the item has been lift off\n print('\\nLifting off the Item to the delivery address.')\n print('\\nUpdating Status to the command centre ......')\n # Assume the drone has reached the delivery address . Now send a\n # message to the warehouse command center that it has reached the\n # delivery area\n time.sleep(5)\n rpc_sendback(\"c02\")\n # Assume the drone has delivered the item and issue the status message\n # to the command center\n time.sleep(5)\n rpc_sendback(\"c03\")\n # #Assume the drone has reached the parking spot and issue the message to the command center that is available for next instruction\n time.sleep(5)\n rpc_sendback(\"c04\")\n\n else:\n print(\"Received Instruction from Warehouse \" +\n str(recieved_message[1]))\n channel.basic_ack(delivery_tag=method.delivery_tag)\n # channel.start_consuming()", "def MessageAck(self, request, context):\n context.code(beta_interfaces.StatusCode.UNIMPLEMENTED)", "def read(self):\n method_frame, header_frame, body = self._channel.basic_get(self.name)\n if method_frame:\n pika_message = PikaMessage(body,\n delivery_info=method_frame,\n properties=header_frame,\n )\n return pika_message.to_message()\n else:\n return None", "def read_channel(self,channel):\n self.spi.set_channel(channel)\n return (self.spi.read_channel(channel))", "def read_channel(self, channel: int, /) -> int:", "def get(self, channel):\n try:\n return self[channel.lower()]\n except KeyError:\n return None", "def getChannelResponse(self):\n \n \n return self.channel_response", "def receive_message(self, channel: str, message: str) -> None:\n print(f\"{self._name} receives message {message} from \"\n f\"channel-[{channel}]\")", "def on_message(self, channel, basic_deliver, properties, body):\n self.logger.debug(\n \"Received message #%s from %s on channel %s: %s\",\n basic_deliver.delivery_tag,\n properties.app_id,\n channel.channel_number,\n body,\n )\n\n # Pika gives us bytes, but we want a string to be ok too\n try:\n body = body.decode()\n except AttributeError:\n pass\n\n try:\n future = self._on_message_callback(body, properties.headers)\n callback = partial(self.on_message_callback_complete, basic_deliver)\n future.add_done_callback(callback)\n except DiscardMessageException:\n self.logger.debug(\n \"Nacking message %s, not attempting to requeue\",\n basic_deliver.delivery_tag,\n )\n self._channel.basic_nack(basic_deliver.delivery_tag, requeue=False)\n except Exception as ex:\n self.logger.exception(\n \"Exception while trying to schedule message %s, about to nack \"\n \"and requeue: %s\",\n basic_deliver.delivery_tag,\n ex,\n )\n self._channel.basic_nack(basic_deliver.delivery_tag, requeue=True)", "def on_message(self, unused_channel, basic_deliver, properties, body):\n logger.info('Received message # %s from %s: %s',\n basic_deliver.delivery_tag, properties.app_id, body)\n self.rx_queue.put(body)\n self.acknowledge_message(unused_channel, basic_deliver.delivery_tag)", "def handle_ack(self, msg):\r\n if msg[0] == 'post':\r\n self.handle_post_frame(msg)\r\n elif msg[0] == 'sync':\r\n self.handle_sync(msg)\r\n else:\r\n raise ValueError(f'unknown ack: {msg}')", "def MessageAck(self, request, timeout, metadata=None, with_call=False, protocol_options=None):\n raise NotImplementedError()", "async def goodbye_channel(self, ctx, *, channel: discord.TextChannel):\n await queries.update_setting(ctx, \"goodbye_settings\", \"channel_id\", channel.id)\n await util.send_success(ctx, f\"Goodbye messages channel is now {channel.mention}\")", "def handleReceived():\r\n global receivedAck\r\n receivedAck = True", "def SafeHangup(channelID):\n try:\n ARIclient.channels.hangup(channelId=channelID)\n except:\n return", "def process_ack(self, ack_message):\n processing = True\n while processing:\n sent_message, time_sent = self.awaiting_ack.get()\n if sent_message.get_message_id() == ack_message.ack_id:\n processing = False\n else:\n self.awaiting_ack.put((sent_message, time_sent))", "def _ack(self,cmd):\n self.get(\"ACK\",cmd,self.from_uri,self.Q,self.I)\n self.response = self.ack()\n self.deal_msg(self.response)" ]
[ "0.64406365", "0.6272624", "0.6254079", "0.59941304", "0.58116174", "0.5726528", "0.56323904", "0.55881184", "0.55846435", "0.5554266", "0.54920876", "0.5490809", "0.542975", "0.54154646", "0.54040796", "0.53981715", "0.5382634", "0.5352141", "0.5350141", "0.5345407", "0.53299224", "0.53250057", "0.53223103", "0.5322145", "0.5311708", "0.5306238", "0.52884126", "0.5276636", "0.527627", "0.5274186" ]
0.70551664
0
Test the Interrogate flow.
def testInterrogate(self): flow_name = "Interrogate" with test_lib.Stubber(flow.GRRFlow, "SendReply", self.MockSendReply): # Run the flow in the simulated way for _ in test_lib.TestFlowHelper(flow_name, InterrogatedClient(), token=self.token, client_id=self.client_id): pass # Now check that the AFF4 object is properly set fd = aff4.FACTORY.Open(self.client_id, token=self.token) self.assertEqual(fd.Get(fd.Schema.HOSTNAME), "test_node") self.assertEqual(fd.Get(fd.Schema.SYSTEM), "Linux") self.assertEqual(fd.Get(fd.Schema.INSTALL_DATE), 100 * 1000000) # Check the client info info = fd.Get(fd.Schema.CLIENT_INFO) self.assertEqual(info.client_name, config_lib.CONFIG["Client.name"]) self.assertEqual(info.client_version, int(config_lib.CONFIG["Client.version_numeric"])) self.assertEqual(info.build_time, config_lib.CONFIG["Client.build_time"]) # Check the client config config_info = fd.Get(fd.Schema.GRR_CONFIG) self.assertEqual(config_info.location, "http://www.example.com") self.assertEqual(config_info.poll_min, 1.0) # Check that the index has been updated. index_fd = aff4.FACTORY.Create(fd.Schema.client_index, "AFF4Index", mode="r", token=self.token) self.assertEqual( [fd.urn], [x for x in index_fd.Query([fd.Schema.HOSTNAME], ".*test.*")]) # Check for notifications user_fd = aff4.FACTORY.Open("aff4:/users/test", token=self.token) notifications = user_fd.Get(user_fd.Schema.PENDING_NOTIFICATIONS) self.assertEqual(len(notifications), 1) notification = notifications[0] self.assertEqual(notification.subject, rdfvalue.RDFURN(self.client_id)) # Check that reply sent from the flow is correct self.assertEqual(self.flow_reply.client_info.client_name, config_lib.CONFIG["Client.name"]) self.assertEqual(self.flow_reply.client_info.client_version, int(config_lib.CONFIG["Client.version_numeric"])) self.assertEqual(self.flow_reply.client_info.build_time, config_lib.CONFIG["Client.build_time"]) self.assertEqual(self.flow_reply.system_info.system, "Linux") self.assertEqual(self.flow_reply.system_info.node, "test_node") self.assertEqual(self.flow_reply.system_info.release, "5") self.assertEqual(self.flow_reply.system_info.version, "2") self.assertEqual(self.flow_reply.system_info.machine, "i386") users = list(fd.Get(fd.Schema.USER)) self.assertEqual(len(users), 3) self.assertEqual(users[0].username, "Foo") self.assertEqual(users[1].username, "Bar") self.assertEqual(users[2].username, u"文德文") self.assertEqual(str(fd.Get(fd.Schema.USERNAMES)), "Foo Bar 文德文") net_fd = fd.OpenMember("network") interfaces = list(net_fd.Get(net_fd.Schema.INTERFACES)) self.assertEqual(interfaces[0].mac_address, "123456") self.assertEqual(interfaces[0].addresses[0].human_readable, "127.0.0.1") self.assertEqual(socket.inet_ntoa(interfaces[0].addresses[0].packed_bytes), "127.0.0.1") # Mac addresses should be available as hex for searching mac_addresses = fd.Get(fd.Schema.MAC_ADDRESS) self.assertTrue("123456".encode("hex") in str(mac_addresses)) # Check that virtual directories exist for the mount points fd = aff4.FACTORY.Open(self.client_id.Add("fs/os/mnt/data"), token=self.token) # But no directory listing exists yet - we will need to fetch a new one self.assertEqual(len(list(fd.OpenChildren())), 0) fd = aff4.FACTORY.Open(self.client_id.Add("fs/tsk/dev/sda"), token=self.token) # But no directory listing exists yet - we will need to fetch a new one self.assertEqual(len(list(fd.OpenChildren())), 0) fd = aff4.FACTORY.Open(self.client_id.Add("devices/dev/sda"), token=self.token) # But no directory listing exists yet - we will need to fetch a new one self.assertEqual(len(list(fd.OpenChildren())), 0) # Check flow's reply self.assertEqual(len(self.flow_reply.users), 3) self.assertEqual(self.flow_reply.users[0].username, "Foo") self.assertEqual(self.flow_reply.users[1].username, "Bar") self.assertEqual(self.flow_reply.users[2].username, u"文德文") self.assertEqual(len(self.flow_reply.interfaces), 1) self.assertEqual(self.flow_reply.interfaces[0].mac_address, "123456") # Check that the client summary was published to the event listener. self.assertEqual(DiscoveryTestEventListener.event.client_id, self.client_id) self.assertEqual( DiscoveryTestEventListener.event.interfaces[0].mac_address, "123456") # Check that label indexes are updated. self.assertEqual( list(search.SearchClients("label:Label2", token=self.token)), [self.client_id])
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_handle(self):\n with pytest.raises(NotImplementedError):\n self.behaviour.act()", "def _test(self):\n pass", "def _test(self):\n pass", "def _test(self):\n pass", "def testing(self):\n print('test successful')", "def test_get_run(self):\n pass", "def runtest(self):", "def runTest(self):\n return True", "def test_get_scenario(self):\n pass", "def test_gameHandleEvents(self):\n # this kinda gonna be reiterating the other tests??\n # the tests of all the individual methods below make this test work\n pass", "def test_strategy(self):\n self.first_play_test(C)", "def TestOneStep(self):\n pass", "def test_01_visit(self):", "def test(self):\n pass", "def test_runGame(self):\n # this is tested by playing the game. No good way to unit test this.\n pass", "def test_start_scan(self):\n pass", "def test_emirp_check():\r\n pass", "def _handler_command_test(self, *args, **kwargs):\n next_state = None\n result = None\n\n next_state = SBE37ProtocolState.TEST\n \n return (next_state, result)", "def _handler_test_enter(self, *args, **kwargs):\n # Tell driver superclass to send a state change event.\n # Superclass will query the state. \n self._driver_event(DriverAsyncEvent.STATE_CHANGE)\n \n # Forward the test event again to run the test handler and\n # switch back to command mode afterward.\n Timer(1, lambda: self._protocol_fsm.on_event(SBE37ProtocolEvent.RUN_TEST)).start()", "async def test_flow_works(hass: HomeAssistant) -> None:\n disc_bridge = get_discovered_bridge(supports_v2=True)\n\n with patch(\n \"homeassistant.components.hue.config_flow.discover_nupnp\",\n return_value=[disc_bridge],\n ):\n result = await hass.config_entries.flow.async_init(\n const.DOMAIN, context={\"source\": config_entries.SOURCE_USER}\n )\n\n assert result[\"type\"] == \"form\"\n assert result[\"step_id\"] == \"init\"\n\n result = await hass.config_entries.flow.async_configure(\n result[\"flow_id\"], user_input={\"id\": disc_bridge.id}\n )\n\n assert result[\"type\"] == \"form\"\n assert result[\"step_id\"] == \"link\"\n\n flow = next(\n flow\n for flow in hass.config_entries.flow.async_progress()\n if flow[\"flow_id\"] == result[\"flow_id\"]\n )\n assert flow[\"context\"][\"unique_id\"] == \"aabbccddeeff\"\n\n with patch.object(config_flow, \"create_app_key\", return_value=\"123456789\"):\n result = await hass.config_entries.flow.async_configure(\n result[\"flow_id\"], user_input={}\n )\n\n assert result[\"type\"] == \"create_entry\"\n assert result[\"title\"] == \"Hue Bridge aabbccddeeff\"\n assert result[\"data\"] == {\n \"host\": \"1.2.3.4\",\n \"api_key\": \"123456789\",\n \"api_version\": 2,\n }", "def test_forward(self):\n validate_forward()", "def _test(self):", "def _test(self):", "def _test(self):", "def _test(self):", "def _test(self):", "def test_alive():\n pass", "def test_alive():\n pass", "def test_alive():\n pass", "def test_verify_connection_to_a_device():" ]
[ "0.63244754", "0.62555957", "0.62555957", "0.62555957", "0.6252443", "0.6157891", "0.61134434", "0.6089899", "0.60834277", "0.60353076", "0.60253406", "0.6024636", "0.6020408", "0.6019066", "0.6013192", "0.601198", "0.600709", "0.6003489", "0.6001394", "0.5998351", "0.597625", "0.59738535", "0.59738535", "0.59738535", "0.59738535", "0.59738535", "0.5937059", "0.5937059", "0.5937059", "0.5933303" ]
0.6306134
1
opcodes + registers. Checks if the `arg` is a keyword.
def iskeyword(self, arg: str): if arg.upper() in self._keywords: return True return False
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def func(input, keyword=None):\r\n pass", "def run_keyword(name, *args):\n BuiltIn().run_keyword(name, *args)", "def this_is_a_keyword(arg1):\r\n print(arg1)\r\n return 'Whatever'", "def process_arg(arg):\n return False", "def UsesArgument(func, argnr):\n argname = func.__code__.co_varnames[argnr]\n bytecode = dis.Bytecode(func)\n for instr in bytecode:\n if argname in str(instr):\n return True\n return False", "def test_single_keyword_arg_provided(self):\n _func = required_parameters('arg1')(undecorated_func)\n self.assertEqual(_func(arg1='hello'), 'foo')", "def __call__(self, word, *args):\n return self.value[word](*args)", "def run_keyword_and_ignore_keyword_definitions(name, *args):\n try:\n status, _ = BuiltIn().run_keyword_and_ignore_error(name, *args)\n except HandlerExecutionFailed:\n LOGGER.log_message(Message(\"Keyword {} not implemented\", \"ERROR\"))\n return \"FAIL\", \"\"\n return status, _", "def add_keyword(x):\n ParsingTmp.keywords.append(x)", "def has_arg(self, arg_name):\n raise NotImplementedError(\"ICallable.has_arg\")", "def keyword_only(func):\n\n @wraps(func)\n def wrapper(self, *args, **kwargs):\n if len(args) > 0:\n raise TypeError(\"Method %s forces keyword arguments.\" % func.__name__)\n self._input_kwargs = kwargs\n return func(self, **kwargs)\n\n return wrapper", "def dummy(*args, **kwargs):\r\n pass", "def test_kw_args_with_keywords():\n assert arguments.fun_opt_kw_params(visited_color='blue',\n link_color='red',\n back_color='yellow',\n fore_color='orange') == ('orange',\n 'yellow',\n 'red', 'blue')", "def _can_perform_call(self, node, args, keywords):\n return (\n getattr(node, \"starargs\", None) is None\n and getattr(node, \"kwargs\", None) is None\n and all(isinstance(arg, KnownValue) for arg in args)\n and all(isinstance(arg, KnownValue) for _, arg in keywords)\n )", "def my_func(a: 'a string',\n b: int = 1,\n *args: 'additional positional args',\n kw1: 'first keyword-only arg',\n kw2: 'second keyword-only arg' = 10,\n **kwargs: 'additional keyword-only args') -> str:\n pass", "def __init__(\n self, subject_as_keyword: bool, arg_map: Dict[str, str], arg_strict: bool\n ):\n self.subject_as_keyword = subject_as_keyword\n self.arg_map = arg_map\n self.arg_strict = arg_strict", "def get_argument_as_keywords(self):\n status = True\n arg_kv = self.get_values_for_mandatory_args()\n if len(arg_kv) != len(self.req_args_list):\n msg = 'could not execute %s without mandatory arguments' % (object)\n self.data_repository = skip_and_report_status(self.data_repository, msg)\n status = False\n arg_kv = self.get_values_for_optional_args(arg_kv)\n return arg_kv, status", "def test_star_args_with_keywords():\n assert arguments.fun_star_params(visited_color='orange',\n link_color='yellow',\n back_color='red',\n fore_color='blue') == ('orange',\n 'yellow',\n 'red', 'blue')", "def string_check(param, name):\n\tif not isinstance(param, strcomp):\n\t\traise TypeError(\"Keyword arg '%s' must be of type string. Got: %s\" % (\n\t\t\tname, type(param)))\n\telse:\n\t\tpass", "def test_queryKeywordFlag(self):\n self._keywordFilteringTest(\"keyword\")", "def test_stepregistry_step_decorator_should_register_func_with_proper_keyword(keyword):\n # given\n registry = StepRegistry()\n context = {}\n registry.create_step_decorators(context)\n\n # when\n def test_step():\n ...\n\n test_step = context[keyword.lower()](\"pattern\")(test_step)\n\n # then\n assert registry.step_implementations(keyword) == [\n StepImpl(keyword, \"pattern\", test_step)\n ]", "def _getargs(fn_sig):\n params = fn_sig.parameters\n args = []\n for k, v in params.items():\n if (v.kind & v.POSITIONAL_OR_KEYWORD) == v.POSITIONAL_OR_KEYWORD:\n args.append(k)\n else:\n msg = \"%s argument type unsupported in jitclass\" % v.kind\n raise errors.UnsupportedError(msg)\n return args", "def test_onearg_and_keyword(self):\n varargs = (12,)\n kwargs = {'default' : 13}\n method = getattr(self.foo,'f_onearg_and_default')\n var_dict = reassign_function_arguments(method, varargs, kwargs)\n self.assert_(var_dict['arg1'] == 12)\n self.assert_(var_dict['default'] == 13)\n self.assert_(len(var_dict) == 2)", "def _opcode_fetch(self, opcode: str, *args, **kwargs) -> None:\n _args_params = [x for x in args if self.iskeyword(x)]\n _args_hexs = [decompose_byte(tohex(x)) for x in args if ishex(x)]\n _opcode_search_params = \" \".join([opcode, *_args_params]).upper()\n _opcode_hex = self._lookup_opcodes_dir.get(_opcode_search_params)\n if _opcode_hex:\n return _opcode_hex, _args_hexs\n raise OPCODENotFound", "def __call__(self, *ar, **kw):\n\t\tkw = {**self.default_kw, **kw} # add any default keywords\n\t\tkw = {k:v for k,v in kw.items() if self.is_kwarg_valid(k)} # remove non valid keywords (keywords that are not in base func)\n\n\t\t# selectively get the kwargs according to the user\n\t\tif self.ignore_kw == \"ALL\":\n\t\t\tkw = {}\n\t\telif type(self.ignore_kw) == list:\n\t\t\tkw = {k:v for k,v in kw.items() if not k in self.ignore_kw}\n\t\telse:\n\t\t\traise Exception(\"self.ignore_kw must be list or ALL, but is:\", self.ignore_kw)\n\t\t\n\n\t\tassert self.check(ar, is_check_verbose=True), \"Checks have failed on given parameters %s for %s\"%(ar, self.__class__.__name__)\n\t\treturn self.base_func(*self.additional_check(ar), **kw)", "def test_keyword(self):\n varargs = ()\n kwargs = {'default' : 12}\n method = getattr(self.foo,'f_default')\n var_dict = reassign_function_arguments(method, varargs, kwargs)\n self.assert_(var_dict['default'] == 12)\n self.assert_(len(var_dict) == 1)", "def pykeyword(operation='list', keywordtotest=None):\n\n # If the operation was 'list'\n if operation == 'list':\n # Return an array of keywords\n return str(keyword.kwlist)\n\n # If the operation was 'in'\n elif operation == 'in':\n # Return a boolean for if the string was a keyword\n return keyword.iskeyword(str(keywordtotest))\n\n # Raise a warning\n raise ValueError(\"Invalid operation specified.\")", "def dummy_func(*args, **kwargs):\r\n pass", "def _hcss_fits_keyword(header, keyword, *args):\n if len(args) > 1:\n raise ValueError('Invalid number of arguments.')\n for k in header.keys():\n if not k.startswith('key.'):\n continue\n if header[k] == keyword:\n return header[k[4:]]\n if len(args) == 1:\n return args[0]\n raise KeyError(\"Keyword '{0}' not found.\".format(keyword))", "def test_keyword():\n token = Token(\"l\", TokenInfo(\"<stdin>\", 0, 1, \"let\"))\n assert token.info.offset == 1\n assert token.info.filename == \"<stdin>\"\n assert token.lexeme == \"l\"\n assert token.info.lineno == 0\n assert token.symbol == Literal.STRING\n assert token.info.line == \"let\"\n\n token += 'e'\n assert token.info.offset == 1\n assert token.info.filename == \"<stdin>\"\n assert token.lexeme == \"le\"\n assert token.info.lineno == 0\n assert token.symbol == Literal.STRING\n assert token.info.line == \"let\"\n\n token += 't'\n assert token.info.offset == 1\n assert token.info.filename == \"<stdin>\"\n assert token.lexeme == \"let\"\n assert token.info.lineno == 0\n assert token.symbol == Keyword.LET\n assert token.info.line == \"let\"\n\n token = Token(\"l\", TokenInfo(\"<stdin>\", 0, 1, \"lett\"))\n assert token.info.offset == 1\n assert token.info.filename == \"<stdin>\"\n assert token.lexeme == \"l\"\n assert token.info.lineno == 0\n assert token.symbol == Literal.STRING\n assert token.info.line == \"lett\"\n\n token += 'e'\n assert token.info.offset == 1\n assert token.info.filename == \"<stdin>\"\n assert token.lexeme == \"le\"\n assert token.info.lineno == 0\n assert token.symbol == Literal.STRING\n assert token.info.line == \"lett\"\n\n token += 't'\n assert token.info.offset == 1\n assert token.info.filename == \"<stdin>\"\n assert token.lexeme == \"let\"\n assert token.info.lineno == 0\n assert token.symbol == Keyword.LET\n assert token.info.line == \"lett\"\n\n token += 't'\n assert token.info.offset == 1\n assert token.info.filename == \"<stdin>\"\n assert token.lexeme == \"lett\"\n assert token.info.lineno == 0\n assert token.symbol == Literal.STRING\n assert token.info.line == \"lett\"\n\n token = Token(\"a\", TokenInfo(\"<stdin>\", 0, 1, \"alet\"))\n assert token.info.offset == 1\n assert token.info.filename == \"<stdin>\"\n assert token.lexeme == \"a\"\n assert token.info.lineno == 0\n assert token.symbol == Literal.STRING\n assert token.info.line == \"alet\"\n\n token += 'l'\n assert token.info.offset == 1\n assert token.info.filename == \"<stdin>\"\n assert token.lexeme == \"al\"\n assert token.info.lineno == 0\n assert token.symbol == Literal.STRING\n assert token.info.line == \"alet\"\n\n token += 'e'\n assert token.info.offset == 1\n assert token.info.filename == \"<stdin>\"\n assert token.lexeme == \"ale\"\n assert token.info.lineno == 0\n assert token.symbol == Literal.STRING\n assert token.info.line == \"alet\"\n\n token += 't'\n assert token.info.offset == 1\n assert token.info.filename == \"<stdin>\"\n assert token.lexeme == \"alet\"\n assert token.info.lineno == 0\n assert token.symbol == Literal.STRING\n assert token.info.line == \"alet\"" ]
[ "0.63227534", "0.6266325", "0.61915255", "0.5615778", "0.56087416", "0.54038626", "0.53846157", "0.53418374", "0.52948177", "0.5270503", "0.52183044", "0.51543736", "0.5144137", "0.5143743", "0.5123514", "0.50824267", "0.50451785", "0.50425905", "0.5031", "0.5018023", "0.5009495", "0.5002478", "0.49764827", "0.49638018", "0.4963301", "0.4959492", "0.4955724", "0.4925781", "0.49255303", "0.4898539" ]
0.6713264
0
Returns the register from `addr`
def _get_register(self, addr: str): addr = addr.upper() _register = self._registers_list.get(addr, None) if _register: return _register raise SyntaxError(msg="next link not found; check the instruction")
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _getReg(address):\n return struct.unpack(\"<L\", mem[address:address+4])[0]", "def readREG_byte( addr):\n\treturn bus.read_byte_data( DEVICE_ADDRESS, addr )", "def read_register(self, address):\n\n return self.register[address]", "def _parse_addr(self, addr: str):\n addr = addr.upper()\n return self._registers_list.get(addr, None)", "def reg_read(self, addr):\n\n num_records = 0\n for range_dict in self.ranges:\n if range_dict['min'] <= addr <= range_dict['max']:\n offset = (addr - range_dict['min'])\n num_records += offset / self.register_stride\n break\n else:\n num_records += range_dict['max_offset'] / self.register_stride + 1\n else:\n sys.exit(\"bad read address\")\n\n with open(self.registers_path, 'r') as _file:\n _file.seek(num_records * self.record_len)\n line0 = _file.readline()\n\n list0 = line0.strip().split(': ')\n raddr = int(list0[0], 16)\n\n if raddr != addr:\n msg = \"bad addr read back 0x{:x} != 0x{:x}\".format(raddr, addr)\n sys.exit(msg)\n\n return int(list0[1], 16)", "def get_data(self, addr):\n\t\tret_val = None\n\t\tif addr < 0:\n\t\t\tprint(\"FAIL - negative address\")\n\t\tif addr >= len(self.data):\n\t\t\ttry:\n\t\t\t\tret_val = self.regs[ addr ]\n\t\t\texcept:\n\t\t\t\tret_val = 0\n\t\telse:\n\t\t\tret_val = self.data[ addr ]\n\n\t\treturn ret_val", "def read_register(self, device_id, address):\n register_array = self.read(device_id, address, 1) \n return register_array[0] << 24 | register_array[1] << 16 | register_array[2] << 8 | register_array[3]", "def read_ulpi_register(self, addr):\n assert self.ulpi_clock_is_up()\n\n self.regs.ucfg_rcmd = self.UCFG_REGISTER_ACCESS_ACTIVE | (addr & self.UCFG_REGISTER_ADDRESS_MASK)\n\n while self.regs.ucfg_rcmd & self.UCFG_REGISTER_ACCESS_ACTIVE:\n pass\n\n return self.regs.ucfg_rdata", "def get_register(self, regnr):\n self.sendpkt(\"p %x\" % regnr)\n data = self.rxqueue.get()\n data = bytes.fromhex(data)\n res, = struct.unpack('<I', data)\n return res", "def get_register(self, register):\n if not Vm.is_register(register):\n raise ValueError(\"Expected register value, instead got: \" + str(register))\n\n return self.registers[register - REGISTER_0]", "def get_address_value(cls, addr):\n\t\tprint \" Called get_address_value({})\".format(addr)\n\t\ttype = abs(addr) // 1000 # integer division\n\t\trelative_address = abs(addr) - (type * 1000)\n\t\tprint \"> Get mem value: type = {}, addr = {}\".format(type, relative_address)\n\t\t# use heap for search if addr is negative, else the current local mem\n\t\tif addr >= 14000:\n\t\t\tprint \"> Const vars memory: {}\".format(cls.const_vars)\n\t\t\treturn cls.const_vars[addr]\n\t\telif addr < 0:\n\t\t\tprint \"> Heap memory: {}\".format(cls.heap.memory)\n\t\t\treturn cls.heap.memory[type][abs(relative_address)]\n\t\telse:\n\t\t\tprint \"> Stack memory: {}\".format(cls.stack.peek().memory)\n\t\t\treturn cls.stack.peek().memory[type][relative_address]", "def read_debug_port_register(self, addr):\n if not self._is_u8(addr):\n raise ValueError('The addr parameter must be an unsigned 8-bit value.')\n\n addr = ctypes.c_uint8(addr)\n data = ctypes.c_uint32()\n\n result = self._lib.NRFJPROG_read_debug_port_register(addr, ctypes.byref(data))\n if result != NrfjprogdllErr.SUCCESS:\n raise APIError(result)\n\n return data.value", "def register_pair_read(self, addr) -> Byte:\n print(f\"register pair read {addr}\")\n _register = self._get_register(addr)\n data = _register.read_pair()\n # self._write_opcode(data)\n return data", "def get(self, addr):\n\n if len(addr) == 4:\n return ipset.ipmap_ipv4_get(self.map, addr)\n\n elif len(addr) == 16:\n return ipset.ipmap_ipv6_get(self.map, addr)\n\n else:\n raise ValueError(\"Invalid address\")", "def GetReg():\n\n global Asm\n\n # Save pointer in case we need to start all over again\n pointer = dec.Asm.Parse_Pointer\n # First try to get a register name\n reg = assem.GetWord().upper()\n\n family = dec.Asm.AVR_Family\n\n if reg == '':\n # Operand was expected but not found\n errors.DoError('missoper', False)\n return 0\n\n if (len(reg) == 2 or len(reg) == 3) and reg[0] == 'R':\n # Can it be a register name? Must be 2 or 3 chars long and start with R\n reg = reg[1:]\n if reg.isdigit:\n # The register number must be numeric of course\n if len(reg) == 1 or reg[0] != '0':\n # It is numeric, without a leading 0\n register = int(reg)\n if register >= 0 and register < 32:\n # OK it is a register\n if dec.Asm.Pass == 2 and (family == 1 or family == 5) and\\\n register < 16:\n # Oops, the Reduced Core family doesn't have\n # registers 0 to 15\n errors.DoError('range', False)\n register = 16\n return register\n\n # Operand was not a register, evaluate expression now\n dec.Asm.Parse_Pointer = pointer\n value = assem.EvalExpr()\n register = value[0]\n\n if dec.Asm.Pass == 2:\n # Test range only if in pass 2\n if register < 0 or register > 31:\n # It's a range error, simply ignore everything which doesn't fit\n errors.DoError('range', False)\n register = 0\n if (family == 1 or family == 5) and register < 16:\n # The range for the Reduced Core family is 16 to 31\n errors.DoError('range', False)\n register = 16\n\n # Expression evaluated to a register number\n return register & 31", "def sim_access(self, addr):\n if addr[:2] == '0b':\n addr = addr[2:]\n vpn, offset = self.Vaddr_breakdown(addr) #Break down virtual address into VPN and . \n ppn = self.searchTLB(vpn) #Search TLB for a VPN->PPN mapping. ppn = None if not found.\n phys_addr = 0\n if not ppn: #VPN->PPN mapping not found in TLB\n ppn = self.searchPT(vpn, ppn) #Next search the page table for a mapping. Either returns or finds the next available PPN in memory (LRU)\n phys_addr = str(bin(ppn)) + str(bin(offset))\n self.accesses += 1\n return phys_addr\n else:\n #Found ppn. Concatenate with offset and return as physical address bitstring. \n phys_addr = str(bin(ppn)) + str(bin(offset))\n self.accesses += 1\n return phys_addr", "def read(self, addr):\n if addr < len(self.RAM):\n return self.RAM[addr]", "def read_reg(self, address, size=1):\n return self.usb.cmdReadMem(address, size)", "def ldx(self, addr):\n\n val = self.mem.read(addr)\n self.reg.idx = val", "def translate_reg(register):\n if register in register_table:\n return register_table[register]\n else:\n raise invalid_register_name(register)", "def get_address(address, registers):\n \n try:\n address, offset = address.split('+')\n offset = int(offset)\n except ValueError:\n try:\n address, offset = address.split('-')\n offset = -int(offset)\n except ValueError:\n offset = 0\n\n if address.isdigit():\n return int(address)\n\n return int(registers[address]) + offset", "def find_value(self, func_addr, instr_addr, register):\n reg_num = idaapi.ph_get_regnames().index(register)\n\n # go back from the current instruction to the start of the function\n for instr_addr in list(instructions(func_addr, instr_addr))[::-1]:\n # look for instrucations that move a value into the desired register\n mnemonic = idc.GetMnem(instr_addr)\n if mnemonic == 'mov':\n\n op1_type = idc.get_operand_type(instr_addr, 0)\n op1_value = idc.get_operand_value(instr_addr, 0)\n \n if op1_type == idc.o_reg and op1_value == reg_num:\n op2_type = idc.get_operand_type(instr_addr, 1)\n op2_value = idc.get_operand_value(instr_addr, 1)\n\n # if this instruction sets the register to an immediate value\n if op2_type == idc.o_imm:\n # return that value\n return op2_value\n else:\n # it is not an immediate value, so we say we cannot\n # resolve the value\n return None\n\n # we did not find an allocation of the register,\n # so we return None to indicate that\n return None", "def decode_addr(self, addr):\n self._check_pid_wrap()\n # Find the binary that contains the specified address.\n # For .so files, look at the relative address; for the main\n # executable, look at the absolute address.\n for binary, (start, end) in self.code_ranges.items():\n if addr >= start and addr <= end:\n offset = addr - start \\\n if binary.endswith(\".so\") else addr\n return \"%s [%s]\" % (self._decode_sym(binary, offset),\n binary)\n return \"%x\" % addr", "def read(self, addr, index=None):\n\n addr_idx = self.index_addr(addr, index)\n value = self.mem.read(addr_idx)\n\n return value", "def get_input_register(self, regnum, regtype=\"double\"):\n return self.registers.__dict__['input_{}_register_{}'.format(regtype, regnum)]", "def extractRegister(register):\n # Special Case registers\n if register.lower() == \"pc\": return 15\n elif register.lower() == \"sp\": return 14\n\n if register[0].lower() != \"r\": return None\n register = register[1:]\n if not register.isnumeric(): return None\n register = int(register)\n if register > 15 or register < 0: return None\n return register", "def get_value(self, address):\n\n return self.data[address]", "def get_custom_register(self, index):\n\t\tif (index not in self.custom_registers):\n\t\t\tsys.stderr.write(\"WARNING : Custom register \" + str(index) + \" is not declared for \" + self._target_id +\"\\n\")\n\t\t\treturn None\n\n\t\treturn self.custom_registers[index]", "def getByte(self, addr: ghidra.program.model.address.Address) -> int:\n ...", "def UINT32(dump,addr):\n return dump.ROM[addr]" ]
[ "0.74102914", "0.71406376", "0.7103341", "0.69185746", "0.67063063", "0.6661927", "0.6335207", "0.6268558", "0.62317944", "0.6210637", "0.6075053", "0.5962305", "0.5932137", "0.59120995", "0.59016246", "0.57828265", "0.5752089", "0.5752045", "0.56154996", "0.5613452", "0.56096566", "0.5603465", "0.5567202", "0.55456424", "0.5519443", "0.55124956", "0.55098945", "0.54541385", "0.5451335", "0.5421775" ]
0.7519734
0
opcode fetch Fetches the hex code of an instruction from `opcode`
def _opcode_fetch(self, opcode: str, *args, **kwargs) -> None: _args_params = [x for x in args if self.iskeyword(x)] _args_hexs = [decompose_byte(tohex(x)) for x in args if ishex(x)] _opcode_search_params = " ".join([opcode, *_args_params]).upper() _opcode_hex = self._lookup_opcodes_dir.get(_opcode_search_params) if _opcode_hex: return _opcode_hex, _args_hexs raise OPCODENotFound
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_opcode(self, code):\r\n opcode = int(str(code)[-2:])\r\n return opcode", "def read_byte(self, opcode: int) -> int:\n\n # 0xff = 255\n\n return opcode & 0xFF", "def fetch_instruction(self) -> dict:\n instruction = self.__ROM.read(self.regs[\"ip\"].read())\n self.regs[\"ip\"].inc()\n return self.disassembler.decode_instruction(instruction)", "def read_idcode_opcode(device, idcode_opcode):\n opcode_length = len(idcode_opcode)\n data = bytearray()\n data.extend((WRITE_BITS_TMS_NVE, 4, 0b11111)) # go to reset\n data.extend((WRITE_BITS_TMS_NVE, 4, 0b00110)) # go to shift-ir\n data.extend((WRITE_BITS_NVE_LSB, opcode_length - 2, int(idcode_opcode))) # shift IDCODE opcode\n data.extend((WRITE_BITS_TMS_NVE, 4, 0b00111)) # go to shift-dr\n data.extend((READ_BYTES_NVE_LSB, 3, 0)) # read command\n device.write(bytes(data)) # send off MPSSE commands\n idcode = device.read(4)[::-1]\n return \"\".join(format(byte, \"08b\") for byte in idcode)", "def read_opcode(self) -> int:\n\n offset = self.current_address - self.STARTING_ADDRESS\n\n if self.insight:\n self.insight.opcode(self.rom_data, offset)\n\n return self.rom_data[offset] << 8 | self.rom_data[offset + 1]", "def read_operation(self, opcode: int) -> int:\n\n if self.insight:\n self.insight.operation(opcode)\n\n return opcode & 0xF000", "def read_address(self, opcode: int) -> int:\n\n if self.insight:\n self.insight.address(opcode)\n\n return opcode & 0xFFF", "def opcode(self):\n return struct.unpack('<H', self.pkt.payload[0:2])[0]", "def process(opcode):\n opcode.process()", "def fetch_execute(self):\n\n op_code = self.mem.read(self.reg.ip)\n self.reg.ip_inc()\n addr = self.mem.read(self.reg.ip)\n self.reg.ip_inc()\n\n # Execute the instruction on addr.\n self.op_codes[op_code.num](addr)", "def decodeOpcode(opcode):\n\tresult = []\n\n\t# mnemonic\n\tid = opcode & ((1 << OPCODE_BITS) - 1)\n\tif id not in inverse:\n\t\traise ValueError('Unknown mnemonic')\n\n\tmnemonic = inverse[id]\n\tresult.append(mnemonic)\n\tmeta = mnemonics[mnemonic]\n\n\t# destination\n\tresult.append([None, operand.Register][mnemonics[mnemonic][0]])\n\n\t# arguments\n\tbit = 0x80\n\tfor i in xrange(1, len(meta)):\n\t\t# No params\n\t\tif len(meta[i]) == 0:\n\t\t\tcontinue\n\n\t\t# only one type\n\t\tif len(meta[i]) == 1:\n\t\t\tresult.append(meta[i][0])\n\t\t\tcontinue\n\n\t\t# two possible types\n\t\twhich = (opcode & bit) != 0\n\t\tresult.append(meta[i][which])\n\t\tbit >>= 1\n\n\treturn result", "def get_idcode_opcode(bsdl_as_json):\n instruction_registers = bsdl_as_json[\"instruction_register_description\"][\"instruction_opcodes\"]\n idcode_instruction = next(\n reg for reg in instruction_registers if reg[\"instruction_name\"] == \"IDCODE\"\n )\n idcode_opcode = idcode_instruction[\"opcode_list\"][0]\n return idcode_opcode", "def decode_opcode(self, packed_opcode):\n packed_opcode = str(packed_opcode)\n while(len(packed_opcode) != 5):\n packed_opcode = '0' + packed_opcode\n\n return [int(packed_opcode[3:]), packed_opcode[2] == '1', packed_opcode[1] == '1', packed_opcode[0] == '1']", "def decode_op_return(op_return_hex):\n return binascii.unhexlify(op_return_hex[4:])", "def fetch(self):\n line = self.code[self.ip]\n self.ip += 1\n return line", "def get_opcode_mode(op):\n op_str = f\"{op:05}\"\n DE = int(op_str[-2:])\n C = int(op_str[2])\n B = int(op_str[1]) \n A = int(op_str[0]) \n\n return A, B, C, DE", "def _decode_insn(self, bitvec76, start, pos):\n insn_wnd = bitvec76[start:start + 0xC] # Opcode is 12 bits long. \n opcode = int(insn_wnd, 2) \n\n # print(f'[+] Instruction Window at {pos:2X}h: {insn_wnd} ~> Opcode: {opcode:03X}h')\n \n # Check if opcode is valid\n if opcode & 0x80 == 0:\n if (opcode & 0x3F) + 0xD != pos:\n raise IndexError(\"instruction and immediate size mismatch\")\n \n if opcode & 0x40 != 0:\n insn_wnd2 = bitvec76[start + 0xC:]\n operand = int(insn_wnd2, 2)\n else:\n insn_wnd2 = bitvec76[start + 0xC:]\n operand = int(insn_wnd2[::-1], 2)\n\n width = (opcode & 0x3F) + 1\n else:\n if opcode & 0xFF00 == 0x400 or opcode & 0xFF00 == 0xF00:\n raise IndexError(\"inappropriate combination of mnemonic and operand type\")\n if pos != 12:\n raise IndexError(\"inappropriate combination of operand type and immediate data\")\n\n insn_wnd2, operand = None, None\n width = (opcode & 0x3F) + 1\n \n return opcode >> 8, operand, width", "def opcode(self):\n if self.op is None:\n return None\n return self.op.value", "def parse(self, opcode_pc: PC) -> Tuple[ZMachineOpcodeInfo, PC]:\n address = int(opcode_pc)\n\n opcode_byte = self._memory[address]\n opcode_form = self._opcode_form(opcode_byte)\n\n next_pc = address + 1\n if opcode_form == OpcodeForm.VARIABLE:\n opcode_info = self.variable_form_opcode(opcode_byte)\n # Variable operand types are stored in the byte/bytes following the opcode\n operand_types, next_pc = self._parse_variable_operand_types(next_pc, 1)\n elif opcode_form == OpcodeForm.SHORT:\n opcode_info = self.short_form_opcode(opcode_byte)\n # The short operand type is stored in the opcode byte itself\n operand_types = self._parse_short_operand_types(opcode_byte)\n elif opcode_form == OpcodeForm.LONG:\n opcode_info = self.long_form_opcode(opcode_byte)\n # Long form operand types are also stored in the opcode byte\n operand_types = self._parse_long_operand_types(opcode_byte)\n else:\n raise NotImplemented('Extended opcodes are not currently implemented')\n\n operands, next_pc = self._read_operands(next_pc, operand_types)\n\n if opcode_info is None:\n raise ZMachineOpcodeParsingError('opcode not found')\n else:\n opcode_name, has_result, has_label, has_str = opcode_info\n\n # Read in the result variable number and advance the PC\n if has_result:\n res_var = ZByte(self._memory, next_pc)\n next_pc += 1\n else:\n res_var = None\n\n if has_label:\n label, next_pc = self.read_label(next_pc)\n else:\n label = None\n\n if has_str:\n string_literal, next_pc = z_string_to_str_with_next(\n self._memory, next_pc, self._header.abbreviations_table_address\n )\n else:\n string_literal = None\n\n opcode_info = ZMachineOpcodeInfo(\n opcode_name,\n operand_types,\n operands,\n res_var,\n label,\n string_literal,\n bytes(self._memory[address:next_pc])\n )\n\n return opcode_info, PC(next_pc)", "def strace_code_fetch_event(self, operation, address, address_range=0):\n cmd = enums.JLinkStraceCommand.TRACE_EVENT_SET\n event_info = structs.JLinkStraceEventInfo()\n event_info.Type = enums.JLinkStraceEvent.CODE_FETCH\n event_info.Op = operation\n event_info.Addr = int(address)\n event_info.AddrRangeSize = int(address_range)\n handle = self._dll.JLINK_STRACE_Control(cmd, ctypes.byref(event_info))\n if handle < 0:\n raise errors.JLinkException(handle)\n\n return handle", "def locctr_increamenter(opcode, operand):\n if opcode == \"base\" or opcode == \"nobase\":\n return [0, True]\n if opcode == \"resw\":\n try:\n value = int(operand)\n except ValueError:\n print(\"operand is not a number\")\n return False\n temp = int(operand) * 3\n return [temp, True]\n if opcode == \"resb\":\n try:\n \n value = int(operand)\n \n except ValueError:\n print(\"operand is not a number\")\n return False\n return [value, True]\n if opcode == \"word\":\n return [3, True]\n if opcode == \"byte\":\n value = operand.partition(\"'\")[-1].rpartition(\"'\")[0]\n temp = len(value)\n if operand[0].lower() == 'x':\n if temp % 2 == 0:\n return [temp // 2, True]\n else:\n return [(temp + 1) // 2, True]\n elif operand[0].lower() == 'c':\n return [temp, True]\n else:\n no_of_bits = math.ceil(math.log(int(operand),2))\n bytes = math.ceil(no_of_bits / 8)\n return [bytes, True]\n\n if opcode == \"rsub\":\n return [3, False]\n if opcode.find('+') != -1:\n return [4, False]\n if operand.find(\",\") != -1:\n str = operand.split(\",\")\n if str[1].lower() == 'x':\n return [3, False]\n return [2, False]\n if opcode == 'clear' or opcode == 'svc' or opcode == 'tixr':\n return [2, False]\n if operand.isspace():\n return [1, False]\n return [3, False]", "def get_byte(self, offset):\n self.ret = ida_bytes.get_byte(offset)\n return self.ret", "def fetch_code(url):\n status, response = http_request(url)\n\n if status != 200:\n writer(\n f\"\\nError: HTTP status {status} returned, 200 expected\\n - {url}\\n\",\n FORMAT[\"ERROR\"]\n )\n sys.exit(1)\n\n code_type = classify_response(response)\n\n return response, code_type", "async def fetch_get(self, command, data):\n _LOGGER.debug(\"[Foobar2k] Running fetch GET\")\n async with self._session.get(\"{base_url}{command}\".format(\n base_url=self._base_url, command=command), data=data) as resp_obj:\n response = await resp_obj.text()\n if (resp_obj.status == 200 or resp_obj.status == 204):\n _LOGGER.debug(\"[Foobar2k] Have a response\")\n return response\n else:\n _LOGGER.error(f\"Host [{self._host}] returned HTTP status code [{resp_obj.status}] to GET command at \"\n \"end point [{command}]\")\n return None", "def DecodeInstruction(ea):\n insn = ida_ua.insn_t()\n inslen = ida_ua.decode_insn(insn, ea)\n return insn if inslen > 0 else None", "def retrieve_hash(conn,hashcode):\n # need reindexing?\n #if NEEDS_REINDEXING:\n # reindex(conn)\n # query\n raise NotImplementedError\n q = \"SELECT tid, weight FROM hashes WHERE jumpcode=\"\n q += str(hashcode)\n res = conn.execute(q)\n # done\n return res.fetchall()", "def __init__(self, opcode):\n self.opcode = opcode", "def get_op_code(self):\n\t\treturn call_sdk_function('PrlJob_GetOpCode', self.handle)", "def getInstructionAt(self, address: ghidra.program.model.address.Address) -> ghidra.program.model.listing.Instruction:\n ...", "def instr(addr=None):\n global simulator\n\n if simulator is None:\n print \"Program is not started.\"\n return\n try:\n if addr is None:\n addr = pc()\n\n instr = simulator.get_instruction(addr)\n if instr is None:\n for i in program.disas(addr, 1):\n instr = i[1]\n print instr\n else:\n print instr\n except:\n simulation_error()" ]
[ "0.6188017", "0.5964656", "0.5931929", "0.5867376", "0.5842648", "0.5692336", "0.56319845", "0.56124514", "0.5602991", "0.55496913", "0.5336672", "0.5316029", "0.5192877", "0.51912916", "0.5115001", "0.5048067", "0.5041225", "0.48393863", "0.48243648", "0.47319537", "0.46972606", "0.46719006", "0.46535286", "0.46334243", "0.45662805", "0.4564696", "0.45598963", "0.4551107", "0.45395696", "0.4501284" ]
0.6904691
0
Method to prepare the upcoming instruction, i.e. opcode fetch, assembler output etc.
def prepare_operation(self, command: str, opcode: str, *args, **kwargs) -> bool: _opcode_hex, _args_hex = self._opcode_fetch(opcode, *args) self.super_memory.PC.write(_opcode_hex) _assembler = [_opcode_hex] for x in _args_hex: for y in x[::-1]: self.super_memory.PC.write(y) _assembler.append(y) self._assembler[command] = " ".join(_assembler).lower() return True
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def compileInstruction(self, ins):\n pass", "def handle_instruction(self, msg):\n assert isinstance(msg, pb.Instruction)\n logging.info(\"NODE: handling instruction - {}\".format(msg).replace('\\n', ','))\n self.config.from_instruction = True\n\n call_later(msg.delay, self.tc_runner.bootstrap_promoters)\n\n if msg.instruction == 'bootstrap-only':\n pass\n\n elif msg.instruction == 'tx':\n rate = float(msg.param)\n interval = 1.0 / rate\n call_later(msg.delay, self.tc_runner.make_tx, interval, False)\n\n elif msg.instruction == 'tx-validate':\n rate = float(msg.param)\n interval = 1.0 / rate\n call_later(msg.delay, self.tc_runner.make_tx, interval, False)\n call_later(msg.delay + 10, self.tc_runner.make_validation, interval)\n\n elif msg.instruction == 'tx-random':\n rate = float(msg.param)\n interval = 1.0 / rate\n call_later(msg.delay, self.tc_runner.make_tx, interval, True)\n\n elif msg.instruction == 'tx-random-validate':\n rate = float(msg.param)\n interval = 1.0 / rate\n call_later(msg.delay, self.tc_runner.make_tx, interval, True)\n call_later(msg.delay + 10, self.tc_runner.make_validation, interval)\n\n else:\n raise AssertionError(\"Invalid instruction msg {}\".format(msg))", "def expand_instruction(self, instruction, start_location):\n return", "def buildInstruction(ops: List[ghidra.program.model.pcode.PcodeOp], fallthruoffset: int, paramshift: int, addrFactory: ghidra.program.model.address.AddressFactory) -> unicode:\n ...", "def advance(self):\n if self.instr is not None:\n self.instr.opcode = self.instr.binary[25:]\n if opcode_decode[self.instr.opcode] == 'R-type':\n self.decode_rtype()\n elif opcode_decode[self.instr.opcode] == 'I-type' or opcode_decode[self.instr.opcode] == 'Load':\n self.decode_itype()\n else:\n raise SyntaxError(\"Invalid opcode\")", "def fetch_instruction(self) -> dict:\n instruction = self.__ROM.read(self.regs[\"ip\"].read())\n self.regs[\"ip\"].inc()\n return self.disassembler.decode_instruction(instruction)", "def parse_next_instruction(self) -> None:\n instruction = self.program[self.pointer]\n opcode = instruction % 100\n if opcode == 99:\n self.halt = True\n\n self.modes = instruction // 100\n\n if opcode == 1:\n self.op_sum()\n if opcode == 2:\n self.op_multiply()\n if opcode == 3:\n self.op_input()\n if opcode == 4:\n self.op_output()\n if opcode == 5:\n self.op_jump_if_true()\n if opcode == 6:\n self.op_jump_if_false()\n if opcode == 7:\n self.op_less_than()\n if opcode == 8:\n self.op_equal_to()\n if opcode == 9:\n self.op_adjust_relative()", "def fetch_execute(self):\n\n op_code = self.mem.read(self.reg.ip)\n self.reg.ip_inc()\n addr = self.mem.read(self.reg.ip)\n self.reg.ip_inc()\n\n # Execute the instruction on addr.\n self.op_codes[op_code.num](addr)", "def Inherent():\n\n global Asm\n\n target.CodeWord(dec.Asm.Instructions[dec.Asm.Mnemonic][3])", "def process(opcode):\n opcode.process()", "def getInstructionBefore(self, instruction: ghidra.program.model.listing.Instruction) -> ghidra.program.model.listing.Instruction:\n ...", "def processingInstruction(self, target, data):\n pass", "def assemble(self):\n machineCodeLength = len(self.instructionList)\n # Adds all of the data lengths to the length\n for symbol in self.symbolTable:\n if symbol[\"type\"] == \"DATA\":\n machineCodeLength += symbol[\"length\"]\n # Stores the machine code instructions\n machineCode = [0 for i in range(machineCodeLength)]\n # Adds all DATA symbols to the machineCode\n dataOffset = len(self.instructionList) # Stores the offset into the machine code for the current data symbol\n for symbol in self.symbolTable:\n if symbol[\"type\"] == \"DATA\":\n # Stores the operand into the memory\n\n # Stores the memory location of the data\n symbol[\"pointer\"] = dataOffset\n dataOffset += symbol[\"length\"]\n\n # Assembles every instruction\n for i in range(len(self.instructionList)):\n ins = self.instructionList[i]\n # Constructs the machine code instruction\n machineCode[i] |= (ins['controlBits'] & 0x3F) << 26\n machineCode[i] |= (ins['code'] & 0xFF) << 18\n # Looks through all of the awaiting in the operand and fills in the output for each\n for sym in ins['operand']['awaiting']:\n symType = \"DATA\" if \"DATA\" in sym else \"LABEL\"\n symbolName = sym[symType]['symbol']\n destination = sym[symType]['output']\n # Searches through the symbol table for the symbol\n for symbol in self.symbolTable:\n # Checks if it is a valid symbol\n if symbol[\"type\"] == symType and symbol[\"name\"] == symbolName:\n if symbol[\"type\"] == \"LABEL\":\n ins[\"operand\"][destination] = symbol[\"pointer\"]\n elif symbol[\"type\"] == \"DATA\":\n ins[\"operand\"][destination] = symbol[\"pointer\"]\n ins['operand']['awaiting'] = []\n print(ins)\n # Gets the main operand value\n if ins['operand']:\n if 'operand' in ins['operand']:\n if ins['operand']['operandType'] == 'int':\n machineCode[i] |= (1 << 18) # Sets value mode for the operand\n value = ins['operand']['operand'].to_bytes(4, \"big\")\n machineCode[i] |= value[0] << 12\n machineCode[i] |= value[1] << 8\n machineCode[i] |= value[2] << 4\n machineCode[i] |= value[3]\n elif ins['operand']['operandType'] == 'float':\n machineCode[i] |= (1 << 18) # Sets value mode for the operand\n value = struct.pack('>f', ins['operand']['operand'])\n machineCode[i] |= value[0] << 12\n machineCode[i] |= value[1] << 8\n machineCode[i] |= value[2] << 4\n machineCode[i] |= value[3]\n elif ins['operand']['operandType'] == 'register':\n machineCode[i] |= (ins['operand']['operand'] & 0xF) << 4\n if 'Rin' in ins['operand']: \n # Clears the bits at the location\n machineCode[i] &= 0xFFFFF0FF\n machineCode[i] |= (ins['operand']['Rin'] & 0xF) << 8\n elif 'address' in ins['operand']:\n if ins['operand']['addressingMode'] == \"Absolute\" or ins['operand']['addressingMode'] == \"Indirect\":\n addr = ins['operand']['address'].to_bytes(4, \"big\")\n machineCode[i] |= addr[0] << 12\n machineCode[i] |= addr[1] << 8\n machineCode[i] |= addr[2] << 4\n machineCode[i] |= addr[3]\n if ins['operand']['addressingMode'] == \"Absolute\": machineCode[i] |= 0x0 << 16\n elif ins['operand']['addressingMode'] == \"Indirect\": machineCode[i] |= 0x1 << 16\n\n if ins['operand']['addressingMode'] == \"Register\":\n machineCode[i] |= 0x2 << 16\n machineCode[i] |= ins['operand']['offset']\n if 'Rout' in ins['operand']:\n # Clears the bits at the location\n machineCode[i] &= 0xFFFFF0FF\n machineCode[i] |= (ins['operand']['Rin'] & 0xF) << 8\n else:\n # Clears the bits at the location\n machineCode[i] &= 0xFFFF0FFF\n machineCode[i] |= (ins['operand']['Rin'] & 0xF) << 12\n elif ins['operand']['addressingMode'] == \"RegisterOffset\": \n machineCode[i] |= 0x3 << 16\n\n if 'Rout' in ins['operand']:\n # Clears the bits at the location\n machineCode[i] &= 0xFFFF0FFF\n machineCode[i] |= (ins['operand']['Rout'] & 0xF) << 12\n print(machineCode[i])", "def prepare(self):\n self.func = \"\"\n self.var = \"\"\n\n vs = [ x for x in self.content.split() if x ]\n if vs[0] != 'using' or vs[-2] != 'do':\n return\n\n self.func = \" \".join(vs[1:-2])\n self.var = vs[-1]", "def advance(self):\n if self.instr is not None:\n self.simulator.registers[int(self.instr.binary[20:25], 2)][1] = self.instr.result", "def advance(self):\n\n if self.instr is not None:\n #calculate the offset of the lw and sw instructions\n if opcode_decode[self.instr.opcode] == 'Load':\n self.instr.source1RegValue = self.instr.source1RegValue + int(self.instr.imm)\n else:\n self.instr.result = eval(\n \"%d %s %d\" % (\n self.instr.source1RegValue, self.simulator.operations[self.instr.operation],\n self.instr.source2RegValue))", "def step(self):\n # parse opcode and parameter mode(s) from instruction\n # (convert integer into 5-digit string with zeroes before parsing)\n instruction = str(self.program[self.index]).zfill(5)\n opcode = int(instruction[-2:])\n param1_mode = int(instruction[-3])\n param2_mode = int(instruction[-4])\n param3_mode = int(instruction[-5])\n\n # opcode to halt program\n if opcode == 99:\n self.halted = True\n return\n\n # opcodes for addition or multiplication\n if opcode in (1, 2):\n val1 = self.get_value(self.index+1, param1_mode)\n val2 = self.get_value(self.index+2, param2_mode)\n\n if opcode == 1:\n total = val1 + val2\n elif opcode == 2:\n total = val1 * val2\n\n self.set_value(self.index+3, param3_mode, total)\n self.index += 4\n return\n\n # opcode for input\n if opcode == 3:\n try:\n inputval = self.inputs.pop(0)\n except IndexError:\n # no input available, halt program until external process\n # adds input and restarts the process\n self.halted = True\n return\n\n self.set_value(self.index+1, param1_mode, inputval)\n self.index += 2\n return\n\n # opcode for output\n if opcode == 4:\n self.outputs += [self.get_value(self.index+1, param1_mode)]\n self.index += 2\n return\n\n # opcodes for jump-if-true / jump-if-false\n if opcode in (5, 6):\n val1 = self.get_value(self.index+1, param1_mode)\n val2 = self.get_value(self.index+2, param2_mode)\n\n # Should jump; update instruction pointer directly\n if (opcode == 5 and val1 != 0) or (opcode == 6 and val1 == 0):\n self.index = val2\n return\n\n # No action, continue to next instruction\n self.index += 3\n return\n\n # opcode for less than / equal to\n if opcode in (7, 8):\n val1 = self.get_value(self.index+1, param1_mode)\n val2 = self.get_value(self.index+2, param2_mode)\n\n # Default 0 (False), set to 1 if True\n result = 0\n if opcode == 7 and val1 < val2:\n result = 1\n elif opcode == 8 and val1 == val2:\n result = 1\n\n self.set_value(self.index+3, param3_mode, result)\n self.index += 4\n return\n\n # opcode for relative base offset\n if opcode == 9:\n self.relative_base += self.get_value(self.index+1, param1_mode)\n self.index += 2\n return\n\n raise Exception(\"unknown opcode, something went wrong\")", "def feed(self, instruction):\n assert self.future_inst is None, 'BranchUnit fed when full'\n self.future_inst = instruction\n self.future_timer = max(0, instruction.DELAY - 1)", "def make_instructions(self):\n #de, aux, vers = self.rods\n de, aux, vers = 0, 1, 2\n n = self.num_rings\n\n self.recur(n, de, aux, vers)\n\n ### Add dummy tuple at end so I can look one move ahead on states\n self.instructions.append((0, 0, 0))", "def getInstructionAfter(self, instruction: ghidra.program.model.listing.Instruction) -> ghidra.program.model.listing.Instruction:\n ...", "def DecodePrecedingInstruction(ea):\n insn = ida_ua.insn_t()\n prev_addr, farref = ida_ua.decode_preceding_insn(insn, ea)\n return (insn, farref) if prev_addr != ida_idaapi.BADADDR else (None, False)", "def advance(self):\n # if the current program counter is still smaller than the last instruction\n if self.simulator.programCounter < (len(self.simulator.instrCollection) * 4 + 0x1000):\n # increment the instruction counter\n self.simulator.instrCount += 1\n # get another instruction\n self.instr = PipelineInstruction(self.simulator.mainmemory[self.simulator.programCounter])\n else:\n self.instr = None\n # increment program counter to the next byte\n self.simulator.programCounter += 4", "def _find_processing_instructions(self):\n pass", "def advance(self):\n # skip for now since only doing r-type\n if self.instr is not None:\n if opcode_decode[self.instr.opcode] == 'Load':\n self.simulator.mainmemory[self.instr.source2RegValue] = self.instr.source1RegValue", "def __instructions(self):\n\n self += comment('Intel Parallel Studio XE')\n self += packages(ospackages=self.__ospackages)\n self += copy(src=self.__tarball,\n dest=posixpath.join(self.__wd, self.__tarball_name))\n if self.__license and not '@' in self.__license:\n # License file\n self += copy(src=self.__license,\n dest=posixpath.join(self.__wd, 'license.lic'))\n self += shell(commands=self.__commands)\n\n if self.__psxevars:\n # Source the mpivars environment script when starting the\n # container, but the variables not be available for any\n # subsequent build steps.\n self += shell(commands=['echo \"source {0}/compilers_and_libraries/linux/bin/compilervars.sh intel64\" >> {1}'.format(self.__prefix, self.__bashrc)])\n else:\n self += environment(variables=self.environment_step())", "def pre_process(self):\n pass", "def pre_process(self):\n pass", "def pre_process(self):\n pass", "def pre_process(self):\n pass", "def pre_process(self):\n pass" ]
[ "0.5819239", "0.5730217", "0.5627368", "0.562327", "0.5603512", "0.55455965", "0.55300134", "0.5526716", "0.55007833", "0.54850966", "0.54205954", "0.5392538", "0.53790957", "0.5354042", "0.53317094", "0.53161323", "0.52962804", "0.52901727", "0.52779526", "0.52770406", "0.52361304", "0.5207961", "0.52014285", "0.51310784", "0.51293236", "0.511982", "0.511982", "0.511982", "0.511982", "0.511982" ]
0.6025537
0
Returns the contents of memory location pointed by `addr`.
def memory_read(self, addr: str) -> Byte: print(f"memory read {addr}") _parsed_addr = self._parse_addr(addr) if _parsed_addr: return _parsed_addr.read(addr) data = self.memory.read(addr) return data
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def read(self, addr, index=None):\n\n addr_idx = self.index_addr(addr, index)\n value = self.mem.read(addr_idx)\n\n return value", "def get_address_value(cls, addr):\n\t\tprint \" Called get_address_value({})\".format(addr)\n\t\ttype = abs(addr) // 1000 # integer division\n\t\trelative_address = abs(addr) - (type * 1000)\n\t\tprint \"> Get mem value: type = {}, addr = {}\".format(type, relative_address)\n\t\t# use heap for search if addr is negative, else the current local mem\n\t\tif addr >= 14000:\n\t\t\tprint \"> Const vars memory: {}\".format(cls.const_vars)\n\t\t\treturn cls.const_vars[addr]\n\t\telif addr < 0:\n\t\t\tprint \"> Heap memory: {}\".format(cls.heap.memory)\n\t\t\treturn cls.heap.memory[type][abs(relative_address)]\n\t\telse:\n\t\t\tprint \"> Stack memory: {}\".format(cls.stack.peek().memory)\n\t\t\treturn cls.stack.peek().memory[type][relative_address]", "def read_memory(self, address):\n\n return self.memory[address]", "def read_memory(self, address):\n return self.memory[Vm.filter_mem_address(address)]", "def readfrom_mem(self, addr: int, memaddr: int, *,\n addrsize: int = 8) -> bytes:\n ...", "def read(self, addr):\n if addr < len(self.RAM):\n return self.RAM[addr]", "def read(self, address: int) -> bytes:\n return bytearray() + self.mem[address]", "def get_data(self, addr):\n\t\tret_val = None\n\t\tif addr < 0:\n\t\t\tprint(\"FAIL - negative address\")\n\t\tif addr >= len(self.data):\n\t\t\ttry:\n\t\t\t\tret_val = self.regs[ addr ]\n\t\t\texcept:\n\t\t\t\tret_val = 0\n\t\telse:\n\t\t\tret_val = self.data[ addr ]\n\n\t\treturn ret_val", "def readfrom_mem(self, addr: int, memaddr: int, nbytes: int, /, *, addrsize: int = 8) -> bytes:", "def readfrom_mem(self, addr: int, memaddr: int, nbytes: int, /, *, addrsize: int = 8) -> bytes:", "def get(self, addr):\n\n if len(addr) == 4:\n return ipset.ipmap_ipv4_get(self.map, addr)\n\n elif len(addr) == 16:\n return ipset.ipmap_ipv6_get(self.map, addr)\n\n else:\n raise ValueError(\"Invalid address\")", "def read(self, addr: str) -> dict:\n for block in self.__mem:\n if block['address'] == addr:\n return block\n\n return {}", "def readfrom_mem_into(\n self, \n addr: int, \n memaddr: int, \n buf: bytes, \n /, \n *, \n addrsize: int = 8\n ) -> None:", "def readfrom_mem_into(\n self, \n addr: int, \n memaddr: int, \n buf: bytes, \n /, \n *, \n addrsize: int = 8\n ) -> None:", "def sim_access(self, addr):\n if addr[:2] == '0b':\n addr = addr[2:]\n vpn, offset = self.Vaddr_breakdown(addr) #Break down virtual address into VPN and . \n ppn = self.searchTLB(vpn) #Search TLB for a VPN->PPN mapping. ppn = None if not found.\n phys_addr = 0\n if not ppn: #VPN->PPN mapping not found in TLB\n ppn = self.searchPT(vpn, ppn) #Next search the page table for a mapping. Either returns or finds the next available PPN in memory (LRU)\n phys_addr = str(bin(ppn)) + str(bin(offset))\n self.accesses += 1\n return phys_addr\n else:\n #Found ppn. Concatenate with offset and return as physical address bitstring. \n phys_addr = str(bin(ppn)) + str(bin(offset))\n self.accesses += 1\n return phys_addr", "def read_memory(self, address, size):\n return self.read(0, address, size, mem_device=True)", "def readfrom_mem_into(self, addr: int, memaddr: int, buf: bytearray, *,\n addrsize: int = 8) -> None:\n ...", "def get_value(self, address):\n\n return self.data[address]", "def from_addr(address):\n return MemoryRange(address, size_t.sizeof, \"MemorySpace.from_addr\", \"address\", MemoryType.Address)", "def get_pos(self, addr: str) -> \"Position\":\n\n # i, j = _address_to_indices(addr)\n return self.positions[addr[0]][int(addr[1])]", "def decode_addr(self, addr):\n self._check_pid_wrap()\n # Find the binary that contains the specified address.\n # For .so files, look at the relative address; for the main\n # executable, look at the absolute address.\n for binary, (start, end) in self.code_ranges.items():\n if addr >= start and addr <= end:\n offset = addr - start \\\n if binary.endswith(\".so\") else addr\n return \"%s [%s]\" % (self._decode_sym(binary, offset),\n binary)\n return \"%x\" % addr", "def _parse_addr(self, addr: str):\n addr = addr.upper()\n return self._registers_list.get(addr, None)", "def readmem32(self, address):\n return self._readmem(address, 'mem32')", "def get_manual(addr):\n try:\n property_addr = ADDRESS_OWNERS[addr]\n return get_normal(property_addr)\n except KeyError:\n return None", "def get_fig(cls, addr):\n\t\ttype = abs(addr) // 1000 # integer division\n\t\trelative_address = abs(addr) - (type * 1000)\n\t\tprint \"> Rel = {} - {}\".format(abs(addr), (type * 1000))\n\t\tprint \"> Get Fig mem value: type = {}, addr = {}\".format(type, relative_address)\n\n\t\tif addr < 0:\n\t\t\tprint \"> Heap memory: {}\".format(cls.heap.memory)\n\t\t\treturn cls.heap.memory[type][abs(relative_address)]\n\t\telse:\n\t\t\tprint \"> Stack memory: {}\".format(cls.stack.peek().memory)\n\t\t\treturn cls.stack.peek().memory[type][relative_address]", "def sprint_addr(addr: bytes) -> str:\n\n if not len(addr) or not addr:\n return \"\"\n\n return str(ipaddress.ip_address(addr))", "def read_mem_word(self, address):\n value = self.read_memory(address)\n value += self.read_memory(address + 1) << 8\n return value", "def read_memory(self, address):\n address = address & 0xFFFF\n if address in self.breads:\n self.paused = True\n self.pause_reason = 'Read at ' + hex(address)\n return self.memory.ReadMemory(self, address)", "def get_address(address_file):\n if not path.exists(address_file) :\n print(\"file not found :\", address_file)\n return None\n addr_file = open(address_file,'r')\n address = addr_file.readlines()\n return address[0]", "def disasm_dump(bin, addr):\n return cache.access((bin,addr), lambda x: disasm_work(*x))" ]
[ "0.6570045", "0.6555623", "0.6411876", "0.63828987", "0.62359416", "0.61978424", "0.61914027", "0.6157194", "0.6058711", "0.6058711", "0.6019673", "0.59167546", "0.5831898", "0.5831898", "0.57772386", "0.574528", "0.57056254", "0.5657386", "0.56354696", "0.56002843", "0.5512567", "0.5502873", "0.5489993", "0.54690754", "0.54251325", "0.5422173", "0.54177666", "0.538798", "0.53781945", "0.53628016" ]
0.68927795
0
Writes the `data` at the memory location pointed by `addr`
def memory_write(self, addr: str, data) -> bool: addr = str(addr) print(f"memory write {addr}|{data}") _parsed_addr = self._parse_addr(addr) if _parsed_addr: return _parsed_addr.write(data, addr) self.memory.write(addr, data) return True
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def write_block_data(self, addr, reg, data):\n raise NotImplementedError()", "def write_byte(self, addr, data):\n raise NotImplementedError()", "def write(self, addr, data, control):\n if not self._is_u32(addr):\n raise ValueError('The addr parameter must be an unsigned 32-bit value.')\n\n if not self._is_valid_buf(data):\n raise ValueError('The data parameter must be a sequence type with at least one item.')\n\n if not self._is_bool(control):\n raise ValueError('The control parameter must be a boolean value.')\n\n addr = ctypes.c_uint32(addr)\n data_len = ctypes.c_uint32(len(data))\n data = (ctypes.c_uint8 * data_len.value)(*data)\n control = ctypes.c_bool(control)\n\n result = self._lib.NRFJPROG_write(addr, ctypes.byref(data), data_len, control)\n if result != NrfjprogdllErr.SUCCESS:\n raise APIError(result)", "def write_byte_data(self, addr, reg, data):\n raise NotImplementedError()", "def write(self, device_id, address, data = None, mem_device = False):\n raise AssertionError(\"write function is not implemented\")", "def qspi_write(self, addr, data):\n if not self._is_u32(addr):\n raise ValueError('The addr parameter must be an unsigned 32-bit value.')\n \n if not self._is_valid_buf(data):\n raise ValueError('The data parameter must be a sequence type with at least one item.')\n \n addr = ctypes.c_uint32(addr)\n data_len = ctypes.c_uint32(len(data))\n data = (ctypes.c_uint8 * data_len.value)(*data)\n \n result = self._lib.NRFJPROG_qspi_write(addr, ctypes.byref(data), data_len)\n if result != NrfjprogdllErr.SUCCESS:\n raise APIError(result)", "def write_memory(self, address, data):\n self.write(0, address, data, mem_device = True)", "def write(self, addr, value, index=None):\n\n addr_idx = self.index_addr(addr, index)\n self.mem.write(addr_idx, value)", "def writeto_mem(self, addr: int, memaddr: int, buf: bytes, /, *, addrsize: int = 8) -> None:", "def writeto_mem(self, addr: int, memaddr: int, buf: bytes, /, *, addrsize: int = 8) -> None:", "def set_data(self, addr, value):\n\t\tif addr < 0:\n\t\t\tprint(\"FAIL - negative address\")\n\t\tif addr >= len(self.data):\n\t\t\tself.regs[ addr ] = value\n\t\telse:\n\t\t\tself.data[ addr ] = value", "def writeto_mem(self, addr: int, memaddr: int, buf: bytearray, *,\n addrsize: int = 8) -> None:\n ...", "def write(self, addr: str, data: str, state: str = 'E') -> None:\n found = False\n\n # Searching for the cache block\n for block in self.__mem:\n # Check if the block is valid and the memory address is\n # the correct\n if block['address'] == addr:\n block['data'] = data\n block['state'] = state\n found = True\n break\n\n # Check if the block was not in cache\n if not found:\n invalid = False\n\n # Searching for an invalid block\n for block in self.__mem:\n if block['state'] == 'I':\n # Set the data in the invalid block\n block['address'] = addr\n block['data'] = data\n block['state'] = state\n\n invalid = True\n break\n \n # If an invalid block does not exist\n if not invalid:\n # Get a random block\n block = randint(0, self.__size - 1)\n\n # Set the new information\n self.__mem[block] = {\n 'address': addr,\n 'available': Lock(),\n 'data': data,\n 'state': state\n }", "def write_debug_port_register(self, addr, data):\n if not self._is_u8(addr):\n raise ValueError('The addr parameter must be an unsigned 8-bit value.')\n\n if not self._is_u32(data):\n raise ValueError('The data parameter must be an unsigned 32-bit value.')\n\n addr = ctypes.c_uint8(addr)\n data = ctypes.c_uint32(data)\n\n result = self._lib.NRFJPROG_write_debug_port_register(addr, data)\n if result != NrfjprogdllErr.SUCCESS:\n raise APIError(result)", "def write_memory(handle: VmbHandle, addr: int, data: bytes): # coverage: skip\n # Note: Coverage is skipped. Function is untestable in a generic way.\n _verify_addr(addr)\n\n bytesWrite = VmbUint32()\n\n try:\n call_vimba_c('VmbMemoryWrite', handle, addr, len(data), data, byref(bytesWrite))\n\n except VimbaCError as e:\n msg = 'Memory write access at {} failed with C-Error: {}.'\n raise ValueError(msg.format(hex(addr), repr(e.get_error_code()))) from e", "def memory_write32(self, addr, data, zone=None):\n return self.memory_write(addr, data, zone, 32)", "def writeto(self, addr: int, buf: bytes, stop: bool = True, /) -> int:", "def writeto(self, addr: int, buf: bytes, stop: bool = True, /) -> int:", "def write_word_data(self, addr, reg, data):\n raise NotImplementedError()", "def writeto(self, addr: int, buf: bytearray,\n stop: bool = True) -> int:\n ...", "def write_reg(self, address, data):\n return self.usb.cmdWriteMem(address, data)", "def sendto(self, data, addr):\n asyncio.ensure_future(self.__inner_protocol.send_data(data, addr))", "def memory_write(self, addr, data, zone=None, nbits=None):\n buf_size = len(data)\n buf = None\n access = 0\n\n if nbits is None:\n # Pack the given data into an array of 8-bit unsigned integers in\n # order to write it successfully\n packed_data = map(lambda d: reversed(binpacker.pack(d)), data)\n packed_data = list(itertools.chain(*packed_data))\n\n buf_size = len(packed_data)\n buf = (ctypes.c_uint8 * buf_size)(*packed_data)\n\n # Allow the access width to be chosen for us.\n access = 0\n elif nbits == 8:\n buf = (ctypes.c_uint8 * buf_size)(*data)\n access = 1\n elif nbits == 16:\n buf = (ctypes.c_uint16 * buf_size)(*data)\n access = 2\n buf_size = buf_size * access\n elif nbits == 32:\n buf = (ctypes.c_uint32 * buf_size)(*data)\n access = 4\n buf_size = buf_size * access\n else:\n raise ValueError('Given bit size is invalid: %s' % nbits)\n\n args = [addr, buf_size, buf, access]\n\n method = self._dll.JLINKARM_WriteMemEx\n if zone is not None:\n method = self._dll.JLINKARM_WriteMemZonedEx\n args.append(zone.encode())\n\n units_written = method(*args)\n if units_written < 0:\n raise errors.JLinkWriteException(units_written)\n\n return units_written", "def write(data):", "def write(self, address: int, value: bytearray):\n for i, val in enumerate(value):\n self.mem[address+i] = value", "def sendto(self, data, addr=None):\n if not isinstance(data, (bytes, bytearray, memoryview)):\n raise TypeError(\"data: expecting a bytes-like instance, got {!r}\"\n .format(type(data).__name__))\n self._check_status()\n if not self._writable:\n raise TransportError('transport is not writable')\n try:\n self._handle.send(addr, data, self._on_send_complete)\n except pyuv.error.UVError as e:\n error = TransportError.from_errno(e.args[0])\n # Try to discern between permanent and transient errors. Permanent\n # errors close the transport. This list is very likely not complete.\n if error.errno != pyuv.errno.UV_EBADF:\n raise error\n self._error = error\n self.abort()\n self._write_buffer_size += 1\n self._maybe_pause_protocol()", "def write( data ):", "def write_access_port_register(self, ap_index, addr, data):\n if not self._is_u8(ap_index):\n raise ValueError('The ap_index parameter must be an unsigned 8-bit value.')\n\n if not self._is_u8(addr):\n raise ValueError('The addr parameter must be an unsigned 8-bit value.')\n\n if not self._is_u32(data):\n raise ValueError('The data parameter must be an unsigned 32-bit value.')\n\n ap_index = ctypes.c_uint8(ap_index)\n addr = ctypes.c_uint8(addr)\n data = ctypes.c_uint32(data)\n\n result = self._lib.NRFJPROG_write_access_port_register(ap_index, addr, data)\n if result != NrfjprogdllErr.SUCCESS:\n raise APIError(result)", "def stax(self, addr):\n\n self.mem_if.write(addr, self.reg.accum, index=self.reg.idx)", "def write_data(self, data):\n print('Wrote %d bytes' % (len(data)))" ]
[ "0.6937246", "0.69350517", "0.69095874", "0.67334324", "0.66806304", "0.6635651", "0.66282445", "0.6501015", "0.6463658", "0.6463658", "0.64097583", "0.6409628", "0.6295188", "0.6252589", "0.61846143", "0.61398613", "0.6126138", "0.6126138", "0.6095817", "0.5979808", "0.5968716", "0.5822537", "0.5816881", "0.58087134", "0.5799357", "0.57586", "0.5754048", "0.57514334", "0.57070166", "0.5696122" ]
0.71273893
0
Method to read and return the data of the register pair pointed by `addr`
def register_pair_read(self, addr) -> Byte: print(f"register pair read {addr}") _register = self._get_register(addr) data = _register.read_pair() # self._write_opcode(data) return data
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_data(self, addr):\n\t\tret_val = None\n\t\tif addr < 0:\n\t\t\tprint(\"FAIL - negative address\")\n\t\tif addr >= len(self.data):\n\t\t\ttry:\n\t\t\t\tret_val = self.regs[ addr ]\n\t\t\texcept:\n\t\t\t\tret_val = 0\n\t\telse:\n\t\t\tret_val = self.data[ addr ]\n\n\t\treturn ret_val", "def read_register(self, address):\n\n return self.register[address]", "def reg_read(self, addr):\n\n num_records = 0\n for range_dict in self.ranges:\n if range_dict['min'] <= addr <= range_dict['max']:\n offset = (addr - range_dict['min'])\n num_records += offset / self.register_stride\n break\n else:\n num_records += range_dict['max_offset'] / self.register_stride + 1\n else:\n sys.exit(\"bad read address\")\n\n with open(self.registers_path, 'r') as _file:\n _file.seek(num_records * self.record_len)\n line0 = _file.readline()\n\n list0 = line0.strip().split(': ')\n raddr = int(list0[0], 16)\n\n if raddr != addr:\n msg = \"bad addr read back 0x{:x} != 0x{:x}\".format(raddr, addr)\n sys.exit(msg)\n\n return int(list0[1], 16)", "def read_register(self, device_id, address):\n register_array = self.read(device_id, address, 1) \n return register_array[0] << 24 | register_array[1] << 16 | register_array[2] << 8 | register_array[3]", "def readREG_byte( addr):\n\treturn bus.read_byte_data( DEVICE_ADDRESS, addr )", "def read(self, addr, index=None):\n\n addr_idx = self.index_addr(addr, index)\n value = self.mem.read(addr_idx)\n\n return value", "def Read_Reg(self, bank, addr, data=0):\n # data is used for spi write\n cmd = self.board_def.CMD_READ_REG\n # data = 0xFAFAFAFA\n\n #I need to pack bank into 4 bytes and then only use the 3\n packedBank = struct.pack(\"l\", bank)\n unpackedBank = struct.unpack('4b', packedBank)\n\n packet = struct.pack(\"4bLi\", cmd, unpackedBank[0], unpackedBank[1], unpackedBank[2], addr, data)\n #Next I need to send the command\n try:\n self.send_data(packet)\n except socket.timeout:\n print (\"Timeout raised and caught\")\n #next read from the socket\n try:\n self.recv_stat, self.recv_data = self.receive_data()\n except socket.timeout:\n print (\"Timeout raised and caught\")\n\n if self.recv_stat != 0x0:\n print ('Issue with Reading Register stat={}!!!'.format(self.recv_stat) )\n return self.board_def.STAT_ERROR\n return self.recv_data", "def read_ulpi_register(self, addr):\n assert self.ulpi_clock_is_up()\n\n self.regs.ucfg_rcmd = self.UCFG_REGISTER_ACCESS_ACTIVE | (addr & self.UCFG_REGISTER_ADDRESS_MASK)\n\n while self.regs.ucfg_rcmd & self.UCFG_REGISTER_ACCESS_ACTIVE:\n pass\n\n return self.regs.ucfg_rdata", "def read(self, addr):\n if addr < len(self.RAM):\n return self.RAM[addr]", "def read_block_data(self, addr, reg):\n raise NotImplementedError()", "def memory_read(self, addr: str) -> Byte:\n print(f\"memory read {addr}\")\n _parsed_addr = self._parse_addr(addr)\n if _parsed_addr:\n return _parsed_addr.read(addr)\n data = self.memory.read(addr)\n return data", "def read_byte_data(self, addr, reg):\n raise NotImplementedError()", "def _getReg(address):\n return struct.unpack(\"<L\", mem[address:address+4])[0]", "def get_value(self, address):\n\n return self.data[address]", "def read_word_data(self, addr, reg):\n raise NotImplementedError()", "def read_reg(self, address, size=1):\n return self.usb.cmdReadMem(address, size)", "def _parse_addr(self, addr: str):\n addr = addr.upper()\n return self._registers_list.get(addr, None)", "def read_memory(self, address):\n\n return self.memory[address]", "def _readmem(self, address, command):\n # Build list of commands to read register.\n address = '{0:08X}'.format(address) # Convert address value to hex string.\n commands = [\n '{0} {1} 1'.format(command, address),\n 'q'\n ]\n # Run command and parse output for register value.\n output = self.run_commands(commands)\n match = re.search('^{0} = (\\S+)'.format(address), output,\n re.IGNORECASE | re.MULTILINE)\n if match:\n return int(match.group(1), 16)\n else:\n raise AdaLinkError('Could not find expected memory value, are the JLink and board connected?')", "def get_register(self, regnr):\n self.sendpkt(\"p %x\" % regnr)\n data = self.rxqueue.get()\n data = bytes.fromhex(data)\n res, = struct.unpack('<I', data)\n return res", "async def i2c_read_data(self, address):\n if address in self.i2c_map:\n map_entry = self.i2c_map.get(address)\n data = map_entry.get('value')\n return data\n else:\n return None", "async def i2c_read_data(self, address):\n if address in self.i2c_map:\n map_entry = self.i2c_map.get(address)\n data = map_entry.get('value')\n return data\n else:\n return None", "def _get_register(self, addr: str):\n addr = addr.upper()\n _register = self._registers_list.get(addr, None)\n if _register:\n return _register\n raise SyntaxError(msg=\"next link not found; check the instruction\")", "def hifread(self, addr = \"0x40000888\"):\n\n addr = hifread_preproc(addr)\n\n if self.ocd is None:\n ret = CpDummyTransport.hifread(self,addr)\n else:\n # ret = self.ocd.board.target.dp.read_reg(addr)\n ret = self.ocd.board.target.read32(addr)\n\n return ret", "def hifread(self, addr = '0x3ff00014'):\n\n if isinstance(addr,int):\n # convert to string\n addr = hex(addr)\n\n if self.port is None:\n # fallback to dummy transport\n ret = CpDummyTransport.hifread(self,addr)\n else:\n # ret = esptool.main( ['--port' , self.port , '--after no_reset', 'read_mem', addr] )\n # dump value on file... horrible hack because no output available\n tmpfile = 'tmpdump'\n ret = esptool.main( # pylint: disable=E1101\n ['--port' , self.port , '--after',\n 'no_reset', 'dump_mem', addr, '4', tmpfile]\n )\n\n if os.path.isfile(tmpfile):\n with open(tmpfile, \"rb\") as tmpfh:\n ret = '0x' + tmpfh.read().hex()\n os.remove(tmpfile)\n else:\n ret = 0\n\n return ret", "def get_address_value(cls, addr):\n\t\tprint \" Called get_address_value({})\".format(addr)\n\t\ttype = abs(addr) // 1000 # integer division\n\t\trelative_address = abs(addr) - (type * 1000)\n\t\tprint \"> Get mem value: type = {}, addr = {}\".format(type, relative_address)\n\t\t# use heap for search if addr is negative, else the current local mem\n\t\tif addr >= 14000:\n\t\t\tprint \"> Const vars memory: {}\".format(cls.const_vars)\n\t\t\treturn cls.const_vars[addr]\n\t\telif addr < 0:\n\t\t\tprint \"> Heap memory: {}\".format(cls.heap.memory)\n\t\t\treturn cls.heap.memory[type][abs(relative_address)]\n\t\telse:\n\t\t\tprint \"> Stack memory: {}\".format(cls.stack.peek().memory)\n\t\t\treturn cls.stack.peek().memory[type][relative_address]", "def read_debug_port_register(self, addr):\n if not self._is_u8(addr):\n raise ValueError('The addr parameter must be an unsigned 8-bit value.')\n\n addr = ctypes.c_uint8(addr)\n data = ctypes.c_uint32()\n\n result = self._lib.NRFJPROG_read_debug_port_register(addr, ctypes.byref(data))\n if result != NrfjprogdllErr.SUCCESS:\n raise APIError(result)\n\n return data.value", "def ldax(self, addr):\n\n val = self.mem_if.read(addr, index=self.reg.idx)\n self.reg.accum = val", "def read(self, reg):\n return self.bus.read_byte_data(self.address, reg)", "def ldx(self, addr):\n\n val = self.mem.read(addr)\n self.reg.idx = val" ]
[ "0.7810009", "0.7275747", "0.70863676", "0.6955075", "0.6929632", "0.68649", "0.680708", "0.6660876", "0.6565061", "0.6513682", "0.6464846", "0.6462695", "0.6416825", "0.62562", "0.62405956", "0.6140814", "0.6089457", "0.6086728", "0.60492694", "0.6043605", "0.60391027", "0.60391027", "0.6027398", "0.5810429", "0.5796425", "0.5773162", "0.5757894", "0.57367617", "0.5735915", "0.5717434" ]
0.7661122
1
Handle Items deselection and trigger event `Items Deselected` Call each callback in `items_deselected_listeners` and store a new history stamp
def onItemsDeselected(self, silent: bool = False): try: current_selected_items = self.getSelectedItems() if current_selected_items == self._last_selected_items: return # TODO monitor usage of this function, may be call more than once self.resetLastSelectedStates() if not current_selected_items: self._last_selected_items = None if not silent: self.history.storeHistory('Deselected Everything') for callback in self._items_deselected_listeners: callback() except Exception as e: dumpException(e)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def addItemsDeselectedListener(self, callback: 'callable'):\n self._items_deselected_listeners.append(callback)", "def onItemSelected(self, silent: bool = False):\n # if silent selection is True, ignore the event\n if self._silent_selection_events:\n return\n\n # Detect change in selected items by comparing old selection to the new ones\n current_selected_items = self.getSelectedItems()\n if current_selected_items != self._last_selected_items:\n self._last_selected_items = current_selected_items\n if not silent:\n self.history.storeHistory('Selection Changed')\n for callback in self._item_selected_listeners:\n callback()", "def on_deactivate(self) -> None:", "def on_deactivate(self):", "def doDeselectItems(self, silent: bool = False) -> None:\n for item in self.getSelectedItems():\n item.setSelected(False)\n if not silent:\n self.onItemsDeselected()", "def onSelected(self, item):\n if not item:\n self.clearBidData()\n else:\n self.enableAddOrder()", "def OnClearSelected(self, event):\n\n for i in range(self.m_dataViewListCtrlCloud.GetItemCount()):\n if self.m_dataViewListCtrlCloud.GetToggleValue(i, 0):\n series = self.m_dataViewListCtrlCloud.GetValue(i, 1)\n self.controller.db.deleteSeriesData(series)\n self.m_dataViewListCtrlCloud.DeleteItem(i)\n print('Row removed: ', i)", "def handle_item_consumption(self):\n self.tooltip_focus = None\n self.active_item_index = None\n self.refresh_inventory()\n self.refresh_equipment()", "def on_selected_new_item(self, item):\n pass", "def _on_data_deleted(self, msg):\n for data_item in self.state.data_items:\n if data_item['name'] == msg.data.label:\n self.state.data_items.remove(data_item)", "def _handle_select_event(self):\n selected_item = self.item_list[self.item_cursor.cursor]\n if selected_item == \"CANCEL\":\n self.is_dead = True\n\n # You can't sell key items.\n elif selected_item.type == ItemTypes.KEY_ITEMS:\n self.do_what_response_menu = \\\n Dialogue(\"29\", self.player, self.player,\n replace=[selected_item.name.upper()], show_curs=False)\n\n # Create a sell event with the selected item.\n else:\n self.active_sell_event = SellHowMany(self.player,\n selected_item)", "def hook_frame_unselected(self):", "def vue_data_item_selected(self, event):\n viewer_id, selected_items = event['id'], event['selected_items']\n\n self._update_selected_data_items(viewer_id, selected_items)", "def on_deleteButton_clicked(self):\n for itm in self.historyList.selectedItems():\n ditm = self.historyList.takeItem(self.historyList.row(itm))\n del ditm\n self.historyList.scrollToItem(self.historyList.currentItem())\n self.historyList.setFocus()", "def not_use_triggered(self):\n\n self.select_items()\n if self.items_selected:\n for index, item in enumerate(self.items_selected):\n index_selected = self.indices_selected[index]\n frame_selected = index_selected + 1\n item.setText(\"Frame %i excluded\" % frame_selected)\n item.setBackground(self.background_excluded)\n item.setForeground(QtGui.QColor(255, 255, 255))\n self.index_included[index_selected] = False\n self.frame_selector.setPhoto(self.frame_index)", "def on_historyList_itemSelectionChanged(self):\n selected = len(self.historyList.selectedItems()) > 0\n self.copyButton.setEnabled(selected and\n self.__vm.activeWindow() is not None)\n self.deleteButton.setEnabled(selected)\n self.executeButton.setEnabled(selected)", "def onOrderSelected(self, item):\n if self.lstOrders.getMultiSelectedItems() == []:\n self.clearBidData()\n else:\n self.btnCancelOrder.enable()", "def onSelected(self):\n pass", "def _list_items_changed_handler ( self, name, not_used, event ):\n arg_lists = self._get_instance_handlers( name[:-6] )\n\n for item in event.removed:\n for args in arg_lists:\n item.on_trait_change( remove = True, *args )\n\n for item in event.added:\n for args in arg_lists:\n item.on_trait_change( *args )", "def on_unselected(self):\n self.colour = self.normal_colour\n self.is_selected = False\n self.redraw()", "def _on_item_selection_changed(self, event):\n item = event.GetItem()\n if item is not None:\n self._model.change_value(event.GetColumn(), item)", "def __onRemoveClicked(self):\n\t\tresults = self.deleteSelectedListWidgetItems(self.ui.listWidget, \"Remove Items?\", \"Are you sure that you want to remove the selected items?\")\n\t\t# force the iteration... removal from the list is our only goal.\n\t\tfor item in results:\n\t\t\tpass", "def selectionChanged(self, selected, deselected):\n rows = [self.model.nodeFromIndex(row) for row in self.selmod1.selectedRows()]\n self.updateStats(rows)", "def __itemChanged(self, event):\n if event in (items.ItemChangedType.DATA, items.ItemChangedType.MASK):\n self._updateFromItem()", "def on_historyList_itemDoubleClicked(self, item):\n self.on_executeButton_clicked()", "def post_delete_menu_item(sender, instance, **kwargs):\n BusinessLocationESService().delete_menu_item(instance)\n # Update Vt\n VtESService().save_vt(instance.vt)", "def handle_event(self, event):\n if event.key == BattleActions.SELECT.value:\n prev_item = self.pokemon.held_item\n self.pokemon.held_item = self.item\n self.bag.subtract_item(self.item)\n self.bag.add_item(prev_item)\n self.is_dead = True", "def click_de_items(self):\n self.button.click(menu_catalog.M0305_DE_ITEMS)", "def onItemChanged(item=None):\n if item:\n selector.blockSignals(True)\n if item.data(50) == \"Unchecked\":\n item.setCheckState(QtCore.Qt.CheckState(1))\n item.setData(50, \"Partially\")\n elif item.data(50) == \"Partially\":\n item.setCheckState(QtCore.Qt.CheckState(2))\n item.setData(50, \"Checked\")\n else:\n item.setCheckState(QtCore.Qt.CheckState(0))\n item.setData(50, \"Unchecked\")\n selector.blockSignals(False)\n enabled = []\n partially = []\n unchecked = []\n for index in range(selector.count()):\n if selector.item(index).checkState() == QtCore.Qt.Checked:\n enabled.append(selector.item(index).data(32))\n elif (selector.item(index).checkState() ==\n QtCore.Qt.PartiallyChecked):\n partially.append(selector.item(index).data(32))\n else:\n unchecked.append(selector.item(index).data(32))\n p.SetString(\"Enabled\", \",\".join(enabled))\n p.SetString(\"Partially\", \",\".join(partially))\n p.SetString(\"Unchecked\", \",\".join(unchecked))\n onWorkbenchActivated()", "def OnResults(self, keyskeep, keysrem):\n self.OnClose()\n self.onselected(keyskeep,keysrem)" ]
[ "0.715858", "0.5882167", "0.5864435", "0.5815277", "0.5800642", "0.5764711", "0.5699734", "0.56143653", "0.55654794", "0.55569565", "0.5551007", "0.55418116", "0.55223393", "0.55121684", "0.55031186", "0.54963636", "0.54109526", "0.53590965", "0.533903", "0.5323001", "0.5314258", "0.5266964", "0.5261972", "0.5214238", "0.5207466", "0.5193559", "0.5168475", "0.5165545", "0.51574284", "0.51554364" ]
0.784819
0
Register `callback` to `Has Been Modified` event
def addHasBeenModifiedListener(self, callback: 'callable'): self._has_been_modified_listeners.append(callback)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def set_modified_callback(self, modified_callback):\n self.modified_callback = modified_callback", "def set_modified_callback(self, callback):\n slw = super(CheckBoxListWalker, self)\n urwid.connect_signal(slw, 'modified', callback)\n return", "def add_change_callback(self, callback_function):\n if callback_function not in self.changeCallbacks:\n self.changeCallbacks.append(callback_function)", "def after_change(self, callback):\n self._after_change_callback = callback if callable(callback) else _void", "def notify_modification(self):\n self._trigger_modification(done=True)", "def on_changed(self, func):\n return self._observers.connect('changed', lambda val: func(val))", "def on_changed(self, func):\n return self._observers.connect('changed', lambda val: func(val))", "def process_IN_MODIFY(self, event):", "def on_add(self, callback):\n self._add_callback = callback if callable(callback) else _void", "def addCallback(self,newCallback):\n self.callback.append(newCallback)", "def register_callback(self, callback):\n self.callbacks.add(callback)", "def set_modified_callback(self, callback):\n slw = super(RadioButtonListWalker, self)\n urwid.connect_signal(slw, 'modified', callback)\n return", "def notifyDirty(self, function, **kwargs):\n self._sig_dirty.subscribe(function, **kwargs)", "def _data_updated_callback(self, attr, old, new):\n pass", "def _modificationStatusChanged(self, m, editor):\n raise RuntimeError('Not implemented')", "def hook(callback):\n hooks.append(callback)", "def set_update_received_callback(self, callback):\n self.__update_received = callback", "def watch(self, callback):\n raise NotImplementedError", "def observe(self, fn):\n self.observers.append(fn)\n return fn", "def register_callback(self, func):\n self.callback = func", "def register_callback(self, callback):\n self._callbacks.append(callback)", "def inotify_code_changed():\n wm = pyinotify.WatchManager()\n notifier = pyinotify.Notifier(wm, EventHandler())\n\n def update_watch(sender=None, **kwargs):\n if sender and getattr(sender, 'handles_files', False):\n # No need to update watches when request serves files.\n # (sender is supposed to be a django.core.handlers.BaseHandler subclass)\n return\n\n mask = (\n pyinotify.IN_MODIFY |\n pyinotify.IN_DELETE |\n pyinotify.IN_ATTRIB |\n pyinotify.IN_MOVED_FROM |\n pyinotify.IN_MOVED_TO |\n pyinotify.IN_CREATE |\n pyinotify.IN_DELETE_SELF |\n pyinotify.IN_MOVE_SELF\n )\n\n wm.add_watch('/home/matthew/Projects/mattbot', mask)\n\n # Block until an event happens.\n update_watch()\n notifier.check_events(timeout=None)\n notifier.read_events()\n notifier.process_events()\n notifier.stop()\n\n # If we are here the code must have changed.\n return EventHandler.modified_code", "def changeAdded(change):", "def register_callback(self, callback: Callable[[], None]) -> None:\r\n print(\"register callback called\")\r\n self._callbacks.add(callback)", "def watch(self, name, callback):\n self.external_watchers[name].add(callback)", "def process_IN_MODIFY(s, event):\n s.doReload(event)", "def add_callback(self, callback):\n if callback is not None:\n self.callbacks.append(callback)", "def on_data(self, callback, remove=False):\n self._data_handlers.register_callback(callback, remove=remove)", "def changed_event(self):\n return True", "def set_hook_changed(self, cell):\n self._executor.set_hook_changed(cell)" ]
[ "0.76073563", "0.6915502", "0.6815548", "0.6611758", "0.64308393", "0.6395239", "0.6395239", "0.6341299", "0.63348705", "0.6313795", "0.6290722", "0.6210409", "0.6202026", "0.62005883", "0.6170355", "0.6125656", "0.6091459", "0.60561305", "0.60443324", "0.6034484", "0.6003922", "0.59666383", "0.59629875", "0.5943596", "0.5929436", "0.5871834", "0.5868445", "0.5864551", "0.5862852", "0.5855175" ]
0.8029991
0
Register `callback` to `Item Selected` event
def addItemSelectedListener(self, callback: 'callable'): self._item_selected_listeners.append(callback)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def onSelected(self):\n pass", "def on_selected_new_item(self, item):\n pass", "def __init__(self, callback):\r\n self.callback = callback\r\n self.selected = False", "def addItemsDeselectedListener(self, callback: 'callable'):\n self._items_deselected_listeners.append(callback)", "def _on_select(self, object):\n pass", "def setBoxSelectCallback(self, id, callback):\n\n self.layer_mapping[id].callback_box_select = callback", "def OnSelect(self,event):\r\n index = event.GetSelection()\r\n item = self.items[index]\r\n self.data.select(item)\r\n if self.gInfoBox:\r\n self.gInfoBox.DiscardEdits()\r\n self.gInfoBox.SetValue(self.data.getInfo(item))", "def select(self,item):\r\n pass", "def _on_item_selection_changed(self, event):\n item = event.GetItem()\n if item is not None:\n self._model.change_value(event.GetColumn(), item)", "def on_selected(self):\n self.colour = self.selected_colour\n self.is_selected = True\n self.redraw()", "def selected(self, item):\n self.elementoSeleccionado = item", "def item_selected(self, _widget, _idx):\n # get item title\n self.sel_fmt = str(self.types_list.getItemNameAt(_idx))\n \n # enable \"ok\" button if any item selected\n self.button_ok.setEnabled(True)\n # update editor checkbox\n self.checkbox_edit.setStateCheck(False)\n self.checkbox_edit.setEnabled(self._formats[self.sel_fmt][1])", "def onSelected(self, item):\n if not item:\n self.clearBidData()\n else:\n self.enableAddOrder()", "def onSelectionChanged(self, event = None):\n\t\tif self.ignore:\n\t\t\tevent.Skip()\n\t\t\treturn\n\t\titem = event.GetItem()\n\t\tself.lastSelection = item\n\t\tif not item.IsOk():\n\t\t\treturn\n\t\t\n\t\tif item not in self.tree.GetSelections(): # Make selection work on 64-bit Win7\n\t\t\tself.tree.SelectItem(item)\n\t\t\n\t\tobj = self.tree.GetPyData(item)\n\t\tif obj == \"1\":\n\t\t\treturn\n\t\tself.item = item\n\t\tif obj and type(obj) != types.StringType:\n\t\t\tif self.lastobj != obj:\n\t\t\t\tLogging.info(\"Switching to \", obj)\n\t\t\t\tlib.messenger.send(None, \"clear_cache_dataunits\")\n\t\t\t\tlib.messenger.send(None, \"tree_selection_changed\", obj)\n\t\t\t\tself.markGreen([item])\n\t\t\t\tself.lastobj = obj\n\t\tself.multiSelect = 0", "def on_select(self, event):\r\n if self.linked_box:\r\n print(self is event.widget) # TODO delete this line\r\n index = self.curselection()[0] # this is currently set up to only allow selection of one item at a time.\r\n value = self.get(index), # this is a tuple\r\n\r\n link_id = self.cursor.execute(self.sql_select + \" WHERE \" + self.field + \"=?\", value).fetchone()[1]\r\n # this sql statement returns all the columns we're displaying\r\n self.linked_box.requery(link_id)\r\n\r\n # get the artist ID from the database row\r\n # artist_id = connect.execute(\"SELECT artists._id FROM artists WHERE artists.name=?\", artist_name).fetchone()\r\n # alist = []\r\n # for row in connect.execute(\"SELECT albums.name FROM albums WHERE albums.artist = ? ORDER BY albums.name\", artist_id):\r\n # # querying the database to retrieve the artist ID\r\n # alist.append(row[0]) # appending the names to a list\r\n # albums_LV.set(tuple(alist))\r\n #\r\n # # This will reset/clear the songs list if you select a different artist\r\n # songs_LV.set((\"Choose an album\",))\r", "def vue_data_item_selected(self, event):\n viewer_id, selected_items = event['id'], event['selected_items']\n\n self._update_selected_data_items(viewer_id, selected_items)", "def _registry_key_selected(self, event) -> None:\r\n selected_item = self.selected_item\r\n self.callbacks[Events.KEY_SELECTED](selected_item.path, selected_item.is_explicit)\r\n self.address_bar.set_address(selected_item.path)", "def list_view_on_selected(self, widget, selected_item_key):\n self.lbl.set_text('List selection: ' + self.listView.children[selected_item_key].get_text())", "def onItemSelected(self, silent: bool = False):\n # if silent selection is True, ignore the event\n if self._silent_selection_events:\n return\n\n # Detect change in selected items by comparing old selection to the new ones\n current_selected_items = self.getSelectedItems()\n if current_selected_items != self._last_selected_items:\n self._last_selected_items = current_selected_items\n if not silent:\n self.history.storeHistory('Selection Changed')\n for callback in self._item_selected_listeners:\n callback()", "def getSelectedItem(*args):", "def selectItem(*args):", "def selected(self):\r\n EditableComboBox.selected(self)\r\n self.emit(SIGNAL(\"open(QString)\"), self.currentText())", "def set_callback(self,callback = None):\n self.callback = callback", "def selection_cb(self, widget, data = None):\n\t\tmodel, iter = widget.get_selected()\n\t\tremove = self.get_data(\"remove\")\n\t\tedit = self.get_data(\"edit\")\n\t\tif iter:\n\t\t\tremove.set_sensitive(True)\n\t\t\tedit.set_sensitive(True)\n\t\telse:\n\t\t\tremove.set_sensitive(False)\n\t\t\tedit.set_sensitive(False)", "def setSelectionHandler(self,selection_handler, *args):\n\t\tself.selection_handler = selection_handler\n\t\tfor arg in args:\n\t\t\tself.selection_external_data.append(arg)", "def _OnSelect(self, event, name=None):\n self.selected = name\n if self.mapper:\n self.mapper.set_cmap(cm.get_cmap(name))\n if self.canvas:\n self.canvas.draw()\n if self.callback:\n self.callback(name)", "def selection_changed(self):\n self.emit('selection_changed')", "def register(self, callback):\n self.callback = callback", "def _on_item_activated(self, event):\n item = event.GetItem()\n if item is not None:\n self._model.change_value(event.GetColumn(), item)", "def setup(self):\n\n self.select_file.on_change(\"value\", self.callback_select_file)" ]
[ "0.74830544", "0.7206682", "0.65960443", "0.629474", "0.6282777", "0.6229242", "0.6177195", "0.6114044", "0.6001839", "0.59780097", "0.59424186", "0.592199", "0.5911459", "0.58842665", "0.58607274", "0.58559954", "0.5835282", "0.58032197", "0.5770527", "0.5763029", "0.5760007", "0.5758641", "0.57551646", "0.5752918", "0.5747856", "0.57113665", "0.56892306", "0.5641704", "0.56403744", "0.5627836" ]
0.783389
0
Register `callback` to `Items Deselected` event
def addItemsDeselectedListener(self, callback: 'callable'): self._items_deselected_listeners.append(callback)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def onItemsDeselected(self, silent: bool = False):\n try:\n current_selected_items = self.getSelectedItems()\n if current_selected_items == self._last_selected_items:\n return\n\n # TODO monitor usage of this function, may be call more than once\n self.resetLastSelectedStates()\n if not current_selected_items:\n self._last_selected_items = None\n if not silent:\n self.history.storeHistory('Deselected Everything')\n for callback in self._items_deselected_listeners:\n callback()\n except Exception as e:\n dumpException(e)", "def delete_callback(self):\n pass", "def on_del(self, callback):\n self._del_callback = callback if callable(callback) else _void", "def on_del(self, callback):\n self._del_callback = callback if callable(callback) else _void", "def delete_callback(self, chain, value):", "def deregister(self):\n self.callback = None", "def __onRemoveClicked(self):\n\t\tresults = self.deleteSelectedListWidgetItems(self.ui.listWidget, \"Remove Items?\", \"Are you sure that you want to remove the selected items?\")\n\t\t# force the iteration... removal from the list is our only goal.\n\t\tfor item in results:\n\t\t\tpass", "def link_delete_callback(self):\n pass", "def onSelected(self):\n pass", "def remove_callback(self, chain):", "def unregister(self, event, callback):\n if self._events_tree[event].isListed(callback):\n self._events_tree[event].remove(callback)\n self._events_cbs[event][0] = self._events_tree.getCallbacksSequence()\n else:\n self._events_cbs[event][1].remove(callback)", "def unsubscribe(self, callback: Callable) -> None:\n self.callbacks.discard(callback)", "def addItemSelectedListener(self, callback: 'callable'):\n self._item_selected_listeners.append(callback)", "def OnClearSelected(self, event):\n\n for i in range(self.m_dataViewListCtrlCloud.GetItemCount()):\n if self.m_dataViewListCtrlCloud.GetToggleValue(i, 0):\n series = self.m_dataViewListCtrlCloud.GetValue(i, 1)\n self.controller.db.deleteSeriesData(series)\n self.m_dataViewListCtrlCloud.DeleteItem(i)\n print('Row removed: ', i)", "def on_deactivate(self):", "def on_unselected(self):\n self.colour = self.normal_colour\n self.is_selected = False\n self.redraw()", "def hook_frame_unselected(self):", "def on_delete(self):\n selItems = self.twLibTree.selectedItems()\n if selItems:\n itemType = selItems[0].itemType\n if itemType == 'file':\n mess = 'Delete selected lib file ?\\nAre you sure ?'\n else:\n mess = 'Delete selected lib folders and his children ?\\nAre you sure ?'\n self.confDelUi = pQt.ConfirmDialog(mess, ['Delete'], [partial(self.delLibFile, itemType)])\n self.confDelUi.exec_()\n else:\n txt = str(self.lDelInfo.text()).split('\\n')\n txt.append(\"\\n!!! Select at least one item in libTree !!!\")\n self.lDelInfo.setText('\\n'.join(txt))", "def onRemoveIndustry(self, item):\n self.frame.mode.removeIndustry(self.lstIndustry.getMultiSelectedItems(), self.mySystemDict['id'])", "def on_deactivate(self) -> None:", "def onSelected(self, item):\n if not item:\n self.clearBidData()\n else:\n self.enableAddOrder()", "def listen_del(self, f):\n self._coms.register_leaving_callback(f)", "def onOrderSelected(self, item):\n if self.lstOrders.getMultiSelectedItems() == []:\n self.clearBidData()\n else:\n self.btnCancelOrder.enable()", "def unregister(self, callback):\n\t\tcallbacks = []\n\t\tfor i in range(0, len(self.callbacks)):\n\t\t\tif self.callbacks[i][0] != callback:\n\t\t\t\tcallbacks.append(self.callbacks[i])\n\t\t\t\t\n\t\tself.callbacks = callbacks\n\t\tself.events[str(callback)] = []", "def OnItemSelected(self, event):\r\n\r\n self.CloseDialog()", "def selection_cb(self, widget, data = None):\n\t\tmodel, iter = widget.get_selected()\n\t\tremove = self.get_data(\"remove\")\n\t\tedit = self.get_data(\"edit\")\n\t\tif iter:\n\t\t\tremove.set_sensitive(True)\n\t\t\tedit.set_sensitive(True)\n\t\telse:\n\t\t\tremove.set_sensitive(False)\n\t\t\tedit.set_sensitive(False)", "def unsubscribe(callback):\n if callback in _subscribers:\n del _subscribers[callback]", "def deselect(self):\n if self._selected:\n \tself._selected = False\n\t\tself.log(\"device {} is now deselected\".format(self._secondary_address))", "def on_selected_new_item(self, item):\n pass", "def OnDeselect( self ):\n bbox = self.data.getPythonTag( TAG_BBOX )\n if bbox is not None:\n bbox.lines.removeNode()\n self.data.clearPythonTag( TAG_BBOX )" ]
[ "0.7072436", "0.6625081", "0.6555107", "0.6555107", "0.6282118", "0.5912221", "0.5908873", "0.5859858", "0.5848628", "0.58395785", "0.5802043", "0.57907784", "0.5779993", "0.5763108", "0.5749542", "0.57416254", "0.57236415", "0.5723615", "0.57224953", "0.571479", "0.57145846", "0.56744677", "0.5674465", "0.5663261", "0.56209123", "0.5617457", "0.56069434", "0.55605906", "0.55334425", "0.5524902" ]
0.85139054
0
Register `callback` to `Drag Enter` event
def addDragEnterListener(self, callback: 'callable'): self.getView().addDragEnterListener(callback)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def enter_notify_event(self, widget, event):\n enter_focus = self.t_.get('enter_focus', False)\n if enter_focus:\n # set focus on widget\n pass\n return self.make_callback('enter')", "def dragEnterEvent(self, e):\n # TODO: Do it properly.\n # TODO: Redraw widget while dragging.\n e.accept()", "def append_cursor_enter_callback(self):", "def dragEnterEvent(self, event):", "def enterKey_cb(widget, dialog):\n dialog.response(gtk.RESPONSE_ACCEPT)", "def dragEnterEvent(self, dee):\n dee.accept(hasattr(Globals.dragObject, 'trackFrame'))", "def dnd_enter(self, source, event):\n\n self._canvas_cursor = self._canvas['cursor']\n if self._dnd_target and source is not self and hasattr(source, 'rgb'):\n self._canvas['cursor'] = self._dnd_cursor or tks.dnd.CURSOR_WIDGET\n self._canvas['relief'] = tk.RAISED\n else:\n self._canvas['cursor'] = tks.dnd.CURSOR_FORBIDDEN\n # self._canvas.focus_set()", "def handle_enter():\n enter_event = QtGui.QKeyEvent(\n QEvent.KeyPress, Qt.Key_Enter, Qt.KeyboardModifiers())\n QtGui.QApplication.sendEvent(self, enter_event)", "def dragEnterEvent(self, e: QtGui.QDragEnterEvent):\n src = e.source()\n if isinstance(src, QtWidgets.QTreeWidget):\n e.accept()", "def mouse_enter(self):\n pass", "def dragEnterEvent(self, event: QtGui.QDragEnterEvent) -> None:\n if event.mimeData().hasImage:\n event.accept()\n else:\n event.ignore()", "def enterEvent(self, ev):\n self.setFocus(Qt.MouseFocusReason)\n self.__pointerLeftWidget = False\n self.setCursor(self.defaultCursor)\n QGraphicsView.enterEvent(self, ev)", "def enter(event):\n if tooltip.event:\n widget.after_cancel(tooltip.event)\n tooltip.event = widget.after(_TOOLTIP_DELAY, tooltip.showtip, text)", "def dragEnterEvent(self, event):\n if event.mimeData().hasImage:\n event.accept()\n else:\n event.ignore()", "def on_enter(self):\n raise NotImplemented(\"on_enter method should be implemented.\")", "def dragEnterEvent(self, event):\n\n mimeData = event.mimeData().text()\n if not self.__nodeEditor.getNetworkManager().isValidLayerType(mimeData):\n event.ignore()", "def dragEnterEvent(self, event):\r\n source = event.mimeData()\r\n if source.hasUrls() or source.hasText():\r\n event.acceptProposedAction()", "def dragEnterEvent(self, event):\r\n source = event.mimeData()\r\n if source.hasUrls() or source.hasText():\r\n event.acceptProposedAction()", "def ev_windowenter(self, event: WindowEvent) -> None:", "def ev_windowenter(self, event: tcod.event.WindowEvent) -> T | None:", "def enter(self):\n\t\tself._translate(True)\n\t\tinputCore.manager.emulateGesture(keyboardHandler.KeyboardInputGesture.fromName(\"enter\"))", "def hit_enter():\n keyboard.press_and_release('Enter')", "def _OnPressEnter1(self):\n\t self.epsg1.set( self.epsg1.get() )\n\t self.epsg1_entry.focus_set()\n\t self.epsg1_entry.selection_range(0, Tkinter.END)\n\t print('epsg code set to %s ' % (str(self.epsg1.get())))", "def enter():\n pass", "def enter(self):\n\t\tself.actionObject().key_down(Keys.ENTER).key_up(Keys.ENTER).perform()", "def _on_enter(self):\n last_line_num = self.LineFromPosition(self.GetLength())\n current_line_num = self.LineFromPosition(self.GetCurrentPos())\n new_line_pos = (last_line_num - current_line_num)\n if self.debug:\n print >>sys.__stdout__, repr(self.input_buffer)\n self.write('\\n', refresh=False)\n # Under windows scintilla seems to be doing funny\n # stuff to the line returns here, but the getter for\n # input_buffer filters this out.\n if sys.platform == 'win32':\n self.input_buffer = self.input_buffer\n old_prompt_num = self.current_prompt_pos\n has_executed = PrefilterFrontEnd._on_enter(self,\n new_line_pos=new_line_pos)\n if old_prompt_num == self.current_prompt_pos:\n # No execution has happened\n self.GotoPos(self.GetLineEndPosition(current_line_num + 1))\n return has_executed", "def hoverEnterEvent(self, event: QGraphicsSceneHoverEvent):\n self.setCursor(Qt.ArrowCursor)", "def hoverEnterEvent(self, event: QGraphicsSceneHoverEvent):\n self.setCursor(Qt.ArrowCursor)", "def enter_press_log_watcher(self, event): # makes it so you can use enter instead of having to press the button\r\n if event.keycode == 13:\r\n self.choose_watcher_num()", "def register_callback(self, event, func) -> bool:\n\n if event == 'newLine':\n self.newLine_callback = func\n return True\n \n return False" ]
[ "0.7131148", "0.6930939", "0.67850393", "0.6747207", "0.646453", "0.63263386", "0.6168104", "0.6134008", "0.6123509", "0.61054265", "0.59283495", "0.58997786", "0.58778363", "0.58587426", "0.5825897", "0.57303315", "0.56985587", "0.56985587", "0.56480694", "0.5639754", "0.56339103", "0.55421996", "0.5472696", "0.54637265", "0.5440968", "0.5440134", "0.5404618", "0.5404618", "0.53606886", "0.5324461" ]
0.75144684
0
Register `callback` to `Drop` event
def addDropListener(self, callback: 'callable'): self.getView().addDropListener(callback)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def drop_event(self, widget, event):\n # make a call back with a list of URLs that were dropped\n #self.logger.debug(\"dropped filename(s): %s\" % (str(paths)))\n #self.make_ui_callback('drag-drop', paths)\n raise NotImplementedError", "def on_drop(self):\n print(\"You have dropped\", self.name)", "def SetCallbackFunc( self, dropCallbacFunc=None ) :\n \n # Create a dropFiles event association for this control.\n # [ SetDropTarget ] is a built-in method for (all ?) controls.\n self.folderDropTarget.SetDropTarget( ddt.FilesDropTarget( self.folderDropTarget ) )\n \n # Install the callback-function for this class's parent-widget dropFiles-event.\n self.folderDropTarget.dropFunc = dropCallbacFunc", "def dropEvent(self, event):\r\n source = event.mimeData()\r\n if source.hasUrls():\r\n files = mimedata2url(source)\r\n if files:\r\n files = [\"r'%s'\" % path for path in files]\r\n if len(files) == 1:\r\n text = files[0]\r\n else:\r\n text = \"[\" + \", \".join(files) + \"]\"\r\n self.shell.insert_text(text)\r\n elif source.hasText():\r\n lines = unicode(source.text())\r\n self.shell.set_cursor_position('eof')\r\n self.shell.execute_lines(lines)\r\n event.acceptProposedAction()", "def makeDropoutMessage(dropout_layer, layer_callback):\n layer_callback.type = 4\n layer_callback.drop.p = dropout_layer.p", "def dropEvent(self, event):\r\n source = event.mimeData()\r\n if source.hasUrls():\r\n files = mimedata2url(source)\r\n if files:\r\n self.plugin.load(files)\r\n elif source.hasText():\r\n editor = self.currentWidget()\r\n if editor is not None:\r\n editor.insert_text( source.text() )\r\n event.acceptProposedAction()", "def dropEvent(self, de):\n # dragging a track\n if hasattr(Globals.dragObject, \"trackFrame\"):\n de.accept()\n trackFrame = Globals.dragObject.trackFrame\n oldParent = trackFrame.parentWidget()\n if oldParent:\n args = (trackFrame, self, oldParent.parentWidget())\n else:\n args = (trackFrame, self, None)\n self.emit(PYSIGNAL('dropped'), (args))\n # not yet used\n #Animation.animate(trackFrame, self, doneFunc=self.slotAnimationDone)", "def dropEvent(self, event):\n if event.mimeData().hasImage:\n event.setDropAction(Qt.CopyAction)\n file_path = event.mimeData().urls()[0].toLocalFile()\n self.set_image(file_path)\n self.folderLocation.setText(file_path)\n \n event.accept()\n else:\n event.ignore()", "def _on_drop(self, event):\n data = event.mimeData().data(constants.QGRAPH_DD_MIME_TYPE)\n if not data.isNull():\n data_stream = QDataStream(data, QIODevice.ReadOnly)\n parsed = json.loads(data_stream.readString().decode('utf8'))\n\n # Refer to `mime.py` for docs about format\n version = parsed['version']\n if version not in (1, 2):\n raise ValueError(\"Unsupported version of QmxGraph MIME data: {}\".format(version))\n\n x = event.pos().x()\n y = event.pos().y()\n\n if version in (1, 2):\n vertices = parsed.get('vertices', [])\n scale = self.api.get_zoom_scale()\n for v in vertices:\n # place vertices with an offset so their center falls\n # in the event point.\n vertex_x = x + (v['dx'] - v['width'] * 0.5) * scale\n vertex_y = y + (v['dy'] - v['height'] * 0.5) * scale\n self.api.insert_vertex(\n x=vertex_x,\n y=vertex_y,\n width=v['width'],\n height=v['height'],\n label=v['label'],\n style=v.get('style', None),\n tags=v.get('tags', {}),\n )\n\n if version in (2,):\n decorations = parsed.get('decorations', [])\n for v in decorations:\n self.api.insert_decoration(\n x=x,\n y=y,\n width=v['width'],\n height=v['height'],\n label=v['label'],\n style=v.get('style', None),\n tags=v.get('tags', {}),\n )\n\n event.acceptProposedAction()\n else:\n event.ignore()", "def drop(self, event):\n self.config(cursor='arrow')", "def dropEvent(self, event: QtGui.QDropEvent) -> None:\n if event.mimeData().hasImage:\n event.setDropAction(Qt.CopyAction)\n self.image = event.mimeData().urls()[0].toLocalFile()\n x = self.width()\n y = self.height()\n im = QPixmap(self.image).scaled(x, y) # , aspectRatioMode=Qt.KeepAspectRatio)\n im.save(os.getcwd() + \"/tmp.jpg\")\n self.image = (os.getcwd() + \"/tmp.jpg\")\n self.setPixmap(im)\n # self.setPixmap(QPixmap(self.image))\n self.setStyleSheet(\"\")\n event.accept()\n else:\n event.ignore()", "def on_insert(self, callback):\n self._insert_callback = callback if callable(callback) else _void", "def dropEvent(self, event):\n\n # Get the id color to drop the items into\n drop_id_color = self.itemAt(event.pos())\n drop_id_color = self.invisibleRootItem() \\\n if drop_id_color is None else drop_id_color\n\n # If the drop position is not valid we pass\n if drop_id_color is None:\n event.ignore()\n return\n\n # If the drop position is not an id color item we pass\n if drop_id_color.data(0, QtCore.Qt.UserRole) != \"color\":\n event.ignore()\n return\n\n # Get the drop items - the selected tree items\n drop_items = [x for x in self.selectedItems()\n if x.data(0, QtCore.Qt.UserRole) == \"object\"] or None\n\n # If not items selected we pass\n if drop_items is None:\n event.ignore()\n return\n\n # Drop the items into the new tree parent\n self._drop_tree_items(drop_items, drop_id_color)\n\n event.accept()\n\n return None", "def player_drop(self, item):\n dropped = self.drop(item)\n if dropped:\n self.handler.message_box.add_msg(\"You drop the {}!\".format(dropped),\n data.COLOURS['player_item_text'])", "def dropEvent(self, QDropEvent):\n srcItems = self.selectedItems()\n dstInd = (self.indexAt(QDropEvent.pos()).row() + 1)\n kbMod = QDropEvent.keyboardModifiers()\n #-- Create New Items --#\n for n, srcItem in enumerate(srcItems):\n itemDict = self.treeParent.getItemDict(srcItem)\n newItem = self.treeParent.on_addVar(index=(dstInd + n))\n self.treeParent.setItem(newItem, **itemDict)\n #-- Remove Items --#\n if not kbMod == QtCore.Qt.ControlModifier:\n for srcItem in srcItems:\n self.takeTopLevelItem(self.indexOfTopLevelItem(srcItem))\n self.treeParent.reindexVar()", "def on_add(self, callback):\n self._add_callback = callback if callable(callback) else _void", "def on_item_dropped(self, url):\n print 'Weld.on_item_dropped:', url\n #make sure all struct are present\n if not(self.project and self.project.level):\n print >> sys.stderr, 'it\\'s too early to drop stuff: '\\\n 'create a project and a level first !'\n return\n\n #retrieve data if it comes from weld\n if url in self.resMan:\n props = self.resMan.file_props(url)\n if props is None:\n print >> sys.stderr, curr_f(), ': url(\\'%s\\') in self.resMan '\\\n 'but can\\'t retrieve props.' % (url)\n return\n props = self.project.level.resMan.add_resource(self.resMan.base_path,\n props)\n url = props['url']\n if props == {} or url not in self.project.level.resMan:\n print >> sys.stderr, curr_f(), 'could not retrieve file and/or '\\\n 'dependencies for props:', pp(props)\n return\n\n #instanciate it\n if url in self.project.level.resMan:\n props = self.project.level.resMan.file_props(url)\n dtp = self.project.level.qsteelwidget.dropTargetPosition(Config.instance().drop_target_vec)\n props['position'] = dtp\n props['rotation'] = self.project.level.qsteelwidget.dropTargetRotation()\n if props['resource_type'] == 'meshes':\n props['meshName'] = props['name']\n self.project.level.instanciate(props)\n s = 'dropped agent \\'%s\\' with id %i' % (props['name'], props['agentId'])\n print s\n Ui.instance().show_status(s)\n else:\n Ui.instance().show_status('can only drop meshes so far')", "def on_del(self, callback):\n self._del_callback = callback if callable(callback) else _void", "def on_del(self, callback):\n self._del_callback = callback if callable(callback) else _void", "def on_data(self, callback, remove=False):\n self._data_handlers.register_callback(callback, remove=remove)", "def addDragEnterListener(self, callback: 'callable'):\n self.getView().addDragEnterListener(callback)", "def DoDrop(self, docks, panes, target, pt, offset=wx.Point(0, 0)):\r\n\r\n if target.IsToolbar():\r\n return self.DoDropToolbar(docks, panes, target, pt, offset)\r\n elif target.IsFloating():\r\n return self.DoDropFloatingPane(docks, panes, target, pt)\r\n else:\r\n return self.DoDropNonFloatingPane(docks, panes, target, pt)", "def toolDropped(*args, **kwargs)->None:\n pass", "def dropMimeData(self, p_int, QMimeData, Qt_DropAction): # real signature unknown; restored from __doc__\r\n return False", "def addDropzone( self, dropzone ):\n self._dropzones.append(dropzone)", "def instantiateShootCallback():\n d = defer.Deferred()\n d.callback(1)", "def register_callback(self):\n raise Exception('not implemented')", "def register(self, callback):\n self.callback = callback", "def dropEvent(self, e: QtGui.QDropEvent):\n src = e.source()\n if src is not self:\n for item in src.selectedItems():\n clone = item.clone()\n clone.setFlags(clone.flags() | Qt.ItemIsEditable)\n self.addTopLevelItem(clone)\n super().dropEvent(e) # Call the original function", "def register_callback(self, callback):\n self.callbacks.add(callback)" ]
[ "0.74034536", "0.6766096", "0.646628", "0.6448156", "0.6177318", "0.6154016", "0.60600996", "0.6026161", "0.5953534", "0.5910036", "0.583305", "0.5640529", "0.5630467", "0.55396706", "0.5532099", "0.54424274", "0.544116", "0.5429553", "0.5429553", "0.5398703", "0.5338513", "0.53249454", "0.53040445", "0.5266502", "0.5214597", "0.5195842", "0.51558733", "0.5151203", "0.51397794", "0.51288915" ]
0.8091536
0
Returns the class representing the Edge. Override if needed Returns Type[Edge]
def getEdgeClass(self) -> Type[Edge]: return Edge
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __repr__(self):\n return f\"EdgeType.{self.name}\"", "def edge(cls, edge):\n return cls(Lnk.EDGE, int(edge))", "def edge_types(self) -> List[EdgeType]:\n return list(self._edge_store_dict.keys())", "def edge(self) -> EdgeConfig:\n return self._edge", "def E(self, edge_type, feed=None, reverse=False):\n return super(Graph, self).E(edge_type, feed, reverse)", "def get_edge_model(cls, linkname='children'):\n return getattr(cls._meta.model, linkname).rel.through", "def edge(self, which='inner'):\n def edge_shape(site):\n def in_shape(x): return self.shape(Site(site.family, site.tag + x))\n sites = [in_shape(x) for x in self._directions]\n if which == 'inner':\n return self.shape(site) and not all(sites)\n elif which == 'outer':\n return not self.shape(site) and any(sites)\n return Shape(edge_shape)", "def type(self) -> Type[ClassType]:\n return self._type", "def __repr__(self):\n return 'Edge(%s, %s)' % (repr(self[0]), repr(self[1]))", "def MakeEdge(self, *args):\n return _ShapeBuild.ShapeBuild_Edge_MakeEdge(self, *args)", "def get_node_type(self):\n return self.node_type", "def save_edge(self, edge: Edge) -> Edge:", "def last_edge(self):\n return self._edge", "def type(self):\n return self.VERTEX", "def type(self):\n return self.VERTEX", "def get_class(self):\n return devices.get_class(self.type)", "def get_edge(self, edge):\n if len(edge) != 2:\n raise TypeError\n try:\n return self[edge[0]][edge[1]]\n except KeyError:\n return None", "def node_cls(self):\n return resolve_resource(self._node_cls)", "def get_current_edge(self):\r\n edge = self.get_selected_part()\r\n if edge is None:\r\n edge = self.get_part(type=\"edge\", sub_type=\"h\", row=1, col=1)\r\n return edge", "def type(self):\n if self._type is None:\n self._type = None if len(self) == 0 else self.top.__class__\n return self._type", "def node_type(self):\n return self._node_type", "def _class(self):\n return self.__class", "def get_arrow_type(self) -> str:\n return ARROW_TYPES.inv[self.arrowType()]", "def getClass(self):\n return _libsbml.ASTNode_getClass(self)", "def get_class(self):\n\t\treturn self.CLASS", "def edge_attribute(self):\n return self._edge_attribute", "def __init__(self, node_class=Node, edge_class=Edge):\n self.node_class = node_class\n self.edge_class = edge_class", "def get_elementType(self):\n return self._element_type", "def get_type(self):\n return self._type_obj", "def edge(self, u):\n return self._ll_tree.get_edge(u)" ]
[ "0.69667274", "0.63873905", "0.6312679", "0.6288949", "0.6173397", "0.5997334", "0.5914608", "0.5758434", "0.5737543", "0.56359076", "0.56304675", "0.56136644", "0.5600077", "0.55952835", "0.55952835", "0.5592612", "0.5577853", "0.5570068", "0.55699664", "0.55614847", "0.5558628", "0.5554742", "0.55497533", "0.5532477", "0.55316436", "0.55139905", "0.54562366", "0.54520047", "0.5439496", "0.5428083" ]
0.9205564
0
When the function self.node_class_selector is set, we can use different Node classes
def setNodeClassSelector(self, class_selecting_function: callable): self.node_class_selector = class_selecting_function
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def node_selector(self, node_selector: Dict[str, str]):\n\n self._node_selector = node_selector", "def getNodeClassFromData(self, data: OrderedDict):\n return Node if self.node_class_selector is None else self.node_class_selector(data)", "def __init__(self, node_class=Node, edge_class=Edge):\n self.node_class = node_class\n self.edge_class = edge_class", "def test_match_with_node_class(self):\n class OneNode(Node):\n \"\"\"Node example\"\"\"\n\n query = Query().match(OneNode)\n expected = '\\n'.join((\n 'MATCH (_a:OneNode)',\n 'RETURN _a',\n ))\n self.assertEqual(str(query), expected)\n\n class TwoNode(Node):\n \"\"\"Node example\"\"\"\n class Neo:\n \"\"\"Neo with labels\"\"\"\n labels = ('Two', 'Node')\n\n query = Query().match(TwoNode, 'q')\n expected = '\\n'.join((\n 'MATCH (q:Node:Two)',\n 'RETURN q',\n ))\n self.assertEqual(str(query), expected)", "def create_node_instance(self, node_type=None):\n if node_type in self.aliases:\n node_type = self.aliases[node_type]\n\n _NodeClass = self.__nodes.get(node_type)\n if _NodeClass:\n return _NodeClass()", "def node_selector(self) -> Dict[str, str]:\n return self._node_selector", "def parseNodeUsingClass(cls, node, xPath, linkData, **kwargs):\n\n if( node.tag != Protare.moniker ) : raise TypeError( \"Invalid node name.\" )\n\n kwargs = {attr: node.get(attr) for attr in\n ('projectile', 'target', 'evaluation', 'path', 'interaction', 'checksum', 'algorithm')}\n\n guessedInteraction, kwargs['interaction'] = guessInteractionModule.guessInteraction(kwargs['interaction'], kwargs['projectile'], kwargs['target'])\n\n protare = Protare( **kwargs )\n\n protare.guessedInteraction = guessedInteraction\n\n return protare", "def choose_class(self, *args, **kwargs):", "def create_node(self, node_class, *args, **kwds):\n assert isinstance(node_class, str)\n cls = nodelist.all_nodes[node_class]\n node = cls(*args, **kwds)\n self.add_node(node)\n return node", "def setSelectModeNode(self):\n self._nodeSelectMode = True\n self._dataSelectMode = False\n self._elemSelectMode = False", "def node_selector(self) -> Optional[Mapping[str, str]]:\n return pulumi.get(self, \"node_selector\")", "def node_selector(self) -> Optional[Mapping[str, str]]:\n return pulumi.get(self, \"node_selector\")", "def node_selector(self) -> Optional[Mapping[str, str]]:\n return pulumi.get(self, \"node_selector\")", "def node_selector(self) -> Optional[Mapping[str, str]]:\n return pulumi.get(self, \"node_selector\")", "def node_selector(self) -> Optional[Mapping[str, str]]:\n return pulumi.get(self, \"node_selector\")", "def node_selector(self) -> Optional[Mapping[str, str]]:\n return pulumi.get(self, \"node_selector\")", "def node_selector(self) -> Optional[Mapping[str, str]]:\n return pulumi.get(self, \"node_selector\")", "def node_selector(self) -> Optional[Mapping[str, str]]:\n return pulumi.get(self, \"node_selector\")", "def node_selector(self) -> Optional[Mapping[str, str]]:\n return pulumi.get(self, \"node_selector\")", "def node_selector(self) -> Optional[Mapping[str, str]]:\n return pulumi.get(self, \"node_selector\")", "def node_selector(self) -> Optional[Mapping[str, str]]:\n return pulumi.get(self, \"node_selector\")", "def node_selector(self) -> Optional[Mapping[str, str]]:\n return pulumi.get(self, \"node_selector\")", "def node_selector(self) -> Optional[Mapping[str, str]]:\n return pulumi.get(self, \"node_selector\")", "def node_selector(self) -> Optional[Mapping[str, str]]:\n return pulumi.get(self, \"node_selector\")", "def node_selector(self) -> Optional[Mapping[str, str]]:\n return pulumi.get(self, \"node_selector\")", "def node_selector(self) -> Optional[Mapping[str, str]]:\n return pulumi.get(self, \"node_selector\")", "def node_selector(self) -> Optional[Mapping[str, str]]:\n return pulumi.get(self, \"node_selector\")", "def node_selector(self) -> Optional[Mapping[str, str]]:\n return pulumi.get(self, \"node_selector\")", "def node_selector(self) -> Optional[Mapping[str, str]]:\n return pulumi.get(self, \"node_selector\")", "def node_selector(self) -> Optional[Mapping[str, str]]:\n return pulumi.get(self, \"node_selector\")" ]
[ "0.67419666", "0.6661993", "0.62911785", "0.6190321", "0.60168195", "0.6001381", "0.59519595", "0.5862142", "0.58119506", "0.5756025", "0.57396466", "0.57396466", "0.57396466", "0.57396466", "0.57396466", "0.57396466", "0.57396466", "0.57396466", "0.57396466", "0.57396466", "0.57396466", "0.57396466", "0.57396466", "0.57396466", "0.57396466", "0.57396466", "0.57396466", "0.57396466", "0.57396466", "0.57396466" ]
0.75932586
0
Return corresponding Node class from data.
def getNodeClassFromData(self, data: OrderedDict): return Node if self.node_class_selector is None else self.node_class_selector(data)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_node(self):\n split_data = self._data.split(',',1)\n if len(split_data) == 1:\n return self.node_class(split_data[0])\n else:\n return self.node_class(split_data[0], Parser(split_data[1],\n self.node_class))", "def _to_node(self, data):\n return Node(\n id = data['ps'],\n name = data['ps'],\n state = NodeState.UNKNOWN,\n public_ip = [data['ip']],\n private_ip = [],\n driver = self.connection.driver,\n extra = {\n 'current_size' : data['memory_mb'],\n 'account_id' : data['account_id'],\n 'type' : data['type']\n }\n )", "def deserialize(self, data: str) -> 'Node':\n if not data:\n return None\n splits = data.split(' ')\n return self._rebuild(deque(splits))", "def deserialize(self, data):\n vals = iter(data.split(\",\"))\n\n def to_node():\n c = vals.next()\n if c == '#':\n return None\n else:\n node = TreeNode(int(c))\n node.left = to_node()\n node.right = to_node()\n return node\n\n return to_node()", "def _to_node(self, data, ex_cloud_service_name=None, virtual_ips=None):\n\n remote_desktop_port = \"\"\n ssh_port = \"\"\n public_ips = virtual_ips or []\n\n if data.instance_endpoints is not None:\n if len(data.instance_endpoints) >= 1:\n public_ips = [data.instance_endpoints[0].vip]\n\n for port in data.instance_endpoints:\n if port.name == \"Remote Desktop\":\n remote_desktop_port = port.public_port\n\n if port.name == \"SSH\":\n ssh_port = port.public_port\n\n return Node(\n id=data.role_name,\n name=data.role_name,\n state=self.NODE_STATE_MAP.get(data.instance_status, NodeState.UNKNOWN),\n public_ips=public_ips,\n private_ips=[data.ip_address],\n driver=self.connection.driver,\n extra={\n \"instance_endpoints\": data.instance_endpoints,\n \"remote_desktop_port\": remote_desktop_port,\n \"ssh_port\": ssh_port,\n \"power_state\": data.power_state,\n \"instance_size\": data.instance_size,\n \"ex_cloud_service_name\": ex_cloud_service_name,\n },\n )", "def deserialize(self, data):\n self.data = data\n \n if(data[0] == \"X\") :\n return None\n else :\n t = TreeNode(int(self.data[: self.data.find(\",\")]))\n t.left = self.deserialize(self.data[self.data.find(\",\") + 1 :])\n t.right = self.deserialize(self.data[self.data.find(\",\") + 1 :])\n return t", "def node_cls(self):\n return resolve_resource(self._node_cls)", "def load_cls(node):\n return node.get_attr(Type).load()", "def deserialize(self, data: str) -> 'Node':\n if not data:\n return None\n nodes = data.split(\"#\")\n root = Node(int(nodes[0]), [])\n queue = deque([root])\n index = 1\n while queue:\n node = queue.popleft()\n while nodes[index] != SEPERATOR:\n new = Node(int(nodes[index]), [])\n node.children.append(new)\n queue.append(new)\n index += 1\n index += 1\n return root", "def from_dict(cls, d):\n clsname = d['type']\n\n if clsname == cls.__name__:\n raise Exception('Cannot instantiate abstract class \"Node\"')\n\n clstype = getattr(sys.modules[__name__], clsname)\n return clstype.from_dict(d)", "def create_node_instance(self, node_type=None):\n if node_type in self.aliases:\n node_type = self.aliases[node_type]\n\n _NodeClass = self.__nodes.get(node_type)\n if _NodeClass:\n return _NodeClass()", "def deserialize(self, data):\n def build():\n val = array.next()\n if val == '#':\n return None\n node = TreeNode(int(val))\n node.left = build()\n node.right = build()\n return node\n array = iter(data.split())\n return build()", "def convertNode(self, builder, typeName, data):\n\t\tif typeName not in self.nodeTypeMap:\n\t\t\traise Exception('Node type \"' + typeName + '\" hasn\\'t been registered.')\n\n\t\tconvertedData = self.nodeTypeMap[typeName](self, data)\n\n\t\ttypeNameOffset = builder.CreateString(typeName)\n\t\tdataOffset = builder.CreateByteVector(convertedData)\n\n\t\tObjectData.Start(builder)\n\t\tObjectData.AddType(builder, typeNameOffset)\n\t\tObjectData.AddData(builder, dataOffset)\n\t\treturn ObjectData.End(builder)", "def create_node(self, data):\n node = RealNode(data, layer=self)\n self.append_node(node)\n return node", "def deserialize(self, data):\n data = data.split(\",\")\n # print(data)\n self.idx = 0\n \n def dfs():\n if data[self.idx] == 'N':\n self.idx += 1\n return None\n node = TreeNode(int(data[self.idx]))\n self.idx += 1\n node.left = dfs()\n node.right = dfs()\n return node\n return dfs()", "def deserialize(self, data):\n if len(data) == 0:\n return None\n start = data.find('[')\n end = data.rfind(']')\n node = None\n if start == -1:\n #print('data:'+str(data))\n node = Node(int(data),[])\n return node\n else:\n node = Node(int(data[:start]),[])\n middle = data[start+1:end]\n level = 0\n start = 0\n for i in range(len(middle)):\n if middle[i] == '[':\n level += 1\n elif middle[i] == ']':\n level -= 1\n elif middle[i] == ' ' and level == 0:\n node.children.append(self.deserialize(middle[start:i]))\n start = i + 1\n node.children.append(self.deserialize(middle[start:])) #last node\n return node", "def deserialize(self, data):\n node, pos = self.parse_help(data, 0)\n return node", "def deserialize(self, data):\n if len(data) == 0:\n return None\n root = TreeNode(data[0])\n root.left = self.deserialize(data[1]) \n root.right = self.deserialize(data[2])\n return root", "def deserialize(self, data: str) -> TreeNode:\n if not data or data == '#':\n return\n nodes = data.split(',')\n\n def preorder(i):\n if i >= len(nodes) or nodes[i] == '#':\n return i, None\n root = TreeNode(nodes[i])\n j, root.left = preorder(i + 1)\n k, root.right = preorder(j + 1)\n return k, root\n\n return preorder(0)[1]", "def deserialize(self, data):\n\n def preOrder(it):\n v = next(it)\n if v == 'None':\n return None\n node = TreeNode(int(v))\n node.left = preOrder(it)\n node.right = preOrder(it)\n return node\n\n data = data.split(' ')\n it = iter(data)\n return preOrder(it)", "def deserialize(self, data):\n if not data: return None\n\n i = 0\n\n while i < len(data) and data[i].isalnum(): i += 1\n\n return Node(int(data[0 : i]), self.helper(data[i + 1 : len(data) - 1]))", "def get_node_type(self):\n return self.node_type", "def __init__(self, data, node):\n self.data = data\n self.node = node", "def deserialize(cls, data):\r\n dtype = data.get('_type')\r\n if dtype == 'vertex':\r\n vertex_type = data['element_type']\r\n if vertex_type not in vertex_types:\r\n raise ElementDefinitionException('Vertex \"{}\" not defined'.format(vertex_type))\r\n translated_data = vertex_types[vertex_type].translate_db_fields(data)\r\n return vertex_types[vertex_type](**translated_data)\r\n elif dtype == 'edge':\r\n edge_type = data['_label']\r\n if edge_type not in edge_types:\r\n raise ElementDefinitionException('Edge \"{}\" not defined'.format(edge_type))\r\n translated_data = edge_types[edge_type].translate_db_fields(data)\r\n return edge_types[edge_type](data['_outV'], data['_inV'], **translated_data)\r\n else:\r\n raise TypeError(\"Can't deserialize '{}'\".format(dtype))", "def deserialize(self, data: str) -> TreeNode:\n items = [None if x == \"null\" else int(x) for x in data[1:-1].split(\",\")]\n\n def walk(items_it):\n try:\n val = next(items_it)\n except StopIteration:\n return None\n if val is None:\n return None\n else:\n res = TreeNode(val)\n res.left = walk(items_it)\n res.right = walk(items_it)\n return res\n\n return walk(iter(items))", "def deserialize(self, data):\n if not data: return None\n store = data.split('!')\n dummy = TreeNode('3')\n tmp = dummy\n flag = True\n stack = []\n\n for s in store:\n if s != '#':\n node = TreeNode(s)\n stack.append(node)\n if flag:\n tmp.left = node\n else:\n tmp.right = node\n flag = True\n tmp = node\n else:\n if stack:\n tmp = stack.pop()\n else:\n break\n flag = False\n return dummy.left", "def node_type(self):\n return self._node_type", "def get_data_class(self):\n return self.data_class", "def deserialize(self, data: str) -> TreeNode:\n data_queue = collections.deque(data.split(\",\"))\n if data_queue[0] == \"\":\n return None \n \n root = self._deserialize(data_queue, -1, 10001)\n return root", "def as_node(cls, obj):\n if isinstance(obj, cls):\n return obj\n elif is_string(obj):\n # Assume filepath.\n return FileNode(obj)\n elif obj is None:\n return obj\n else:\n raise TypeError(\"Don't know how to convert %s to Node instance.\" % obj)" ]
[ "0.7123047", "0.6497989", "0.6464411", "0.6370129", "0.63173854", "0.630167", "0.62856746", "0.62843543", "0.6283823", "0.6280483", "0.6257206", "0.61838216", "0.6130464", "0.6090139", "0.6087587", "0.60795814", "0.6051329", "0.6007779", "0.5979347", "0.5955102", "0.59264773", "0.5919687", "0.5911278", "0.587959", "0.5871637", "0.58562493", "0.5848289", "0.5848128", "0.58280456", "0.5827922" ]
0.87743944
0
Returns current NodeGraphicsView instance. Returns NodeGraphicsView
def getView(self) -> 'NodeGraphicsView': return self.grScene.views()[0]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def graphicsItem(self):\n if self._graphicsItem is None:\n self._graphicsItem = LayerNodeGraphicsItem(self)\n return self._graphicsItem", "def node(self):\n return Node(self)", "def view(self):\n return self._view_class(self)", "def View(self):\n return self._view", "def getCurrentView(self):\n if self.viewFrame._expanded == -1: #four view\n self.currentView = None\n if self.viewFrame._expanded == 0: #top view\n self.currentView = self.topView\n if self.viewFrame._expanded == 1: #front view\n self.currentView = self.frontView\n if self.viewFrame._expanded == 2: #left view\n self.currentView = self.leftView\n if self.viewFrame._expanded == 3: #perspect view\n self.currentView = self.perspView\n\n return self.currentView", "def getViewComponent(self):\n return self.viewComponent", "def get_view(self):\n return self.view", "def get_node(self):\n return self.__node", "def get_node(self):\r\n return self._node", "def GetView(self):\r\n return self.model.GetView()", "def current_graph(self):\n if self._linear_viewer.isVisible():\n return self._linear_viewer\n else:\n return self._flow_graph", "def _get_renderer(self) :\n \n return self._renderer", "def give_geom(self):\n sgeom = self.get_smesh().GetShapeToMesh()\n if sgeom:\n node = self.node\n gnode = Node(node.get_std(), node.get_bld(), sgeom.GetStudyEntry())\n return Geom(gnode)", "def _current_selection_view_factory(self, window, **traits):\n\n from enthought.pyface.workbench.traits_ui_view import \\\n TraitsUIView\n \n from mapero.dataflow_editor.service.api import CurrentSelection\n current_selection = window.get_service( CurrentSelection )\n tui_current_view = TraitsUIView(\n obj = current_selection,\n view = 'view_selection', \n id = CURRENT_SELECTION_VIEW,\n name = \"Mapero Object Editor\",\n window=window,\n relative_to=CATALOG_TREE_VIEW,\n **traits\n )\n return tui_current_view", "def getView(self):\r\n return cv2.resize(self._view, (0,0),\r\n fx=self._view_scale,\r\n fy=self._view_scale)", "def get_view(self):\n for w in self.child_widgets():\n return w", "def getNode(self):\n node = Element.getNode(self)\n node.tag = 'node'\n node.attrib['entity'] = self.entity.id\n return(node)", "def get_view ( self, object ):\n return self.view", "def _get_viewer_container(self):\n self.viewer = self.traj._tempmol.draw3d(style='licorice')\n return self.viewer", "def getCurrentNodeEditorWidget(self):\n activeSubWindow = self.mdiArea.activeSubWindow()\n if activeSubWindow:\n return activeSubWindow.widget()\n return None", "def getCurrentNodeEditorWidget(self):\n activeSubWindow = self.mdiArea.activeSubWindow()\n if activeSubWindow:\n return activeSubWindow.widget()\n return None", "def get_visualization():\n if Visualization.__current_visualization is None:\n Visualization.set_visualization(NoVisualization())\n return Visualization.__current_visualization", "def nodegraph(self):\n return self._nodegraph", "def get_renderer ( self, object ):\n return self.renderer", "def getOneNodeGraph(self):\n layer = self.makeLayer()\n self.addNodeToLayer(layer)\n\n return self.graph", "def node(self):\n return self._node", "def node(self):\n return self._node", "def my_view(cls):\n return cls.__my_view", "def graph(self) -> rx.PyDiGraph:\n return self._graph", "def widget(self) -> ttk.Treeview:\r\n return self.wrapper" ]
[ "0.65113175", "0.5761256", "0.5724514", "0.5651946", "0.5542698", "0.554057", "0.5528475", "0.55219746", "0.55018574", "0.5440726", "0.5386133", "0.5385987", "0.5375258", "0.53598917", "0.53235984", "0.52993315", "0.5290957", "0.5271756", "0.52637786", "0.52583975", "0.52583975", "0.520458", "0.5199793", "0.5188822", "0.5188155", "0.51660514", "0.51660514", "0.51636547", "0.51099306", "0.51002276" ]
0.8466191
0
Returns the QGraphicsItem at position in the current graphics view
def getItemAt(self, pos: Union[QPoint, QPointF]) -> 'QGraphicsItem': if isinstance(pos, QPointF): pos = QPoint(pos.x(), pos.y()) return self.getView().itemAt(pos)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def getItemAtClick(self, event):\n pos = event.pos()\n obj = self.itemAt(pos)\n return obj", "def getItemAtClick(self, event):\n pos = event.pos()\n obj = self.itemAt(pos)\n return obj", "def pos(self):\n return Point(self.currentItem.mapFromScene(self._scenePos))", "def pos(self):\n return Point(self.currentItem.mapFromScene(self._scenePos))", "def pos(self):\n return Point(self.currentItem.mapFromScene(self._scenePos))", "def itemAt(self, *__args): # real signature unknown; restored from __doc__ with multiple overloads\r\n return QListWidgetItem", "def GetItemRect(self):\r\n\r\n return self.rect", "def GetClickedItem( ctrl, evt ):\n return ctrl.HitTest( wx.Point( evt.GetX(), evt.GetY() ) )[0]", "def scenePos( self ):\n pos = self.pos()\n pitem = self.parentItem()\n \n while (pitem):\n pos = pitem.pos() + pos\n pitem = pitem.parentItem()\n \n return pos", "def get_current_item(self, *args):\n return _ida_hexrays.vdui_t_get_current_item(self, *args)", "def GetCurrentItem(self):\r\n\r\n return self._current", "def _get_current_plot_item(self):\n return self.io_model.img_dict_keys[self.data_opt - 1]", "def pos(self):\n pos = self.widget.pos()\n return Pos(pos.x(), pos.y())", "def GetPosition(self):\n return self._pos", "def graphicsItem(self):\n if self._graphicsItem is None:\n self._graphicsItem = LayerNodeGraphicsItem(self)\n return self._graphicsItem", "def get_item(self):\n return self.item", "def get_item(self):\n return self.item", "def __call__(self, pos):\n return self.__getitem__(pos)", "def __call__(self, pos):\n return self.__getitem__(pos)", "def getPosition(self):\n return self.position", "def get_pos(self):\r\n return self.pos", "def get_pos(self):\n return self.rect.midtop", "def paint_item(self, posx, index):\r\n raise NotImplementedError()", "def getPosition(self):\n return self.x", "def get_selected(self):\n\n # if there are items in the list\n if self.currentIndex() != -1:\n modelitem = self._dictmodel.itemFromIndex(\n self._modelindexes[ self.currentIndex() ]\n )\n return modelitem", "def getPosition(self):\n\t\treturn self._position", "def get_pos(self):\n return self.pos", "def FindToolByIndex(self, pos):\r\n \r\n if pos < 0 or pos >= len(self._items):\r\n return None\r\n\r\n return self._items[pos]", "def __getitem__(self,pt):\n return self.maze[pt.y][pt.x]", "def getPositionAnimCurve(self, index, view) -> AnimCurve:\n ..." ]
[ "0.6820099", "0.6820099", "0.63604426", "0.63604426", "0.63604426", "0.6219268", "0.6179353", "0.60181355", "0.59481406", "0.5877858", "0.5876254", "0.5874284", "0.58510846", "0.5842215", "0.57888067", "0.57836163", "0.57836163", "0.5732763", "0.5732763", "0.5723859", "0.5714488", "0.56920147", "0.5662448", "0.5648558", "0.5642954", "0.56362283", "0.56357485", "0.5625156", "0.5620805", "0.56037074" ]
0.7488466
0
Converts a turkish text from uppercase to lowercase
def tr_upper_to_lower(text): out = [] for ch in text: if ch in tr_upper_to_lower_dict: out.append(tr_upper_to_lower_dict[ch]) else: out.append(ch.lower()) return "".join(out)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def LCase(text):\n return text.lower()", "def normalize_case(text):\n text = str(text)\n return text.lower()", "def toLowerCase(self) -> None:\n self.text = self.text.lower()", "def LOWER(text):\n return text.lower()", "def to_lower(self, text):\n return text.lower()", "def lower(text):\n text = text.lower()\n return text", "def preprocess(text):\n return text.lower()", "def to_lowercase(text: str) -> str:\n text = text.lower()\n return text", "def _transliterate_text(self, _text):\n return _text.upper()", "def lowercase_text(text):\n newText = format_lower_case(text)\n Text(\"%(text)s\").execute({\"text\": newText})", "def clean_cases(text):\n return text.lower()", "def UCase(text):\n return text.upper()", "def normalize_txt(txt):\n return unicodedata.normalize('NFD', txt).encode('ascii', 'ignore').decode('utf-8', 'ignoree').lower()", "def normalize_text(w):\n return str(w, \"utf-8\").lower().replace(\"-\", \"\")", "def standardize(text):\n # FIXME regex restricts us to only ascii\n # FIXME move regex compilation outside\n p = re.compile('[^a-zA-Z]')\n retval = p.sub('', text)\n retval = retval.lower()\n return retval", "def convert_to_uppercase(text):\n return text.upper()", "def _lowercase(text: str) -> str:\n return text.lower()", "def _transform_to_lowercase(self, doc: str):\n processed_tweet = doc.lower()\n return processed_tweet", "def preprocess_text(self):\n self.text_received = self.text_received.replace(\" \", \"\").lower()", "def lowercase(raw_text):\n lowercase_text = [text.lower() for text in raw_text]\n return lowercase_text", "def normalize_text(text):\n # mystring.replace('\\n', ' ').replace('\\r', '')\n return text.replace('\\n', ' ').replace('\\r', '').lower()", "def normalize(text):\n return text.lower().translate(TRANSLATION_TABLE)", "def invert_capitalization(word):\n if word.islower():\n return word.upper()\n else:\n return word.lower()", "def lower(self) -> str:", "def asciify(text: str) -> str:\n return \"\".join(\n filter(\n lambda x: x in list(string.ascii_letters) or x.isspace(), \n unidecode.unidecode(text).lower()\n )\n )", "def make_alphabetic(text):\n text = re.sub(r'[^A-Za-z\\s]', '', text)\n return text.lower()", "def normalize_text(text):\n return normalize_case(normalize_punctuation(text))", "def fix_string_case(text):\n fixed = []\n for i in text:\n if is_case_sensitive(i):\n fixed.append(i)\n else:\n fixed.append(i.lower())\n return ''.join(fixed)", "def asciitize(text):\n if sys.version_info[0] < 3:\n # python 2\n if isinstance(text, unicode):\n text = text.encode('ascii', 'ignore')\n if isinstance(text, str):\n text = text.decode('ascii', 'ignore')\n else:\n # python 3\n if isinstance(text, str):\n text = text.encode('ascii', 'ignore')\n if isinstance(text, bytes):\n text = text.decode('ascii', 'ignore')\n return text", "def lowerCase(self,phrase):\n if(\"normalizeText\" in self._classes):\n return self._normalize.lowerCase(phrase)" ]
[ "0.7528299", "0.7351002", "0.73361063", "0.7315024", "0.7306285", "0.72254044", "0.7197993", "0.7032057", "0.69283414", "0.6910168", "0.69022477", "0.68720585", "0.6856971", "0.68008673", "0.6776845", "0.67689604", "0.6744032", "0.6560823", "0.655094", "0.6513768", "0.6511833", "0.64323956", "0.63850784", "0.6330625", "0.6305916", "0.6285023", "0.6259206", "0.62374485", "0.62233555", "0.61990947" ]
0.77457714
0
Import securities transactions from OFX/XML/CSV datafile; persist to DB.
def import_transactions(args: argparse.Namespace) -> Sequence[models.Transaction]: engine = create_engine() output: list = [] EXTMAP = {"ofx": ofx.read, "qfx": ofx.read, "xml": flex.read, "csv": CSV.read} with sessionmanager(bind=engine) as session: for path in args.file: # Dispatch file according to file extension ext = path.split(".")[-1].lower() readfn = EXTMAP.get(ext, None) if readfn is None: raise ValueError("") print(path) transactions = readfn(session, path) session.add_all(transactions) output.extend(transactions) session.commit() return output
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create_from_csv(self, file_path):\n securities = []\n\n with open(file_path, \"r\") as f:\n # skip the first line (=column names)\n next(f)\n\n for line in f:\n security_code, num_shares = line.strip(\"\\n\").split(\",\")\n # omit the trailing 0\n symbol = security_code[:-1]\n num_shares = int(num_shares)\n\n if symbol in self.securities.keys():\n self.securities[symbol].shares = num_shares\n\n return securities", "def load_data_to_db(self, path):\n table_names = ['train_transaction', 'train_identity', 'test_transaction', 'test_identity']\n for table_name in table_names:\n pat = self.TRANSACTION_NON_NUMBER_PATTERN if 'transaction' in table_name else self.IDENTITY_NON_NUMBER_PATTERN\n print(\"Loading table: \" + table_name)\n fn = os.path.join(path, table_name + '.csv')\n self.dbinstance.build_table_from_csv(fn, pat, table_name)\n print(\"Loaded table \" + table_name)", "def import_prices(self):\n temp = dict(self.currencies_and_regions)\n for index, row in self.df.iterrows():\n self.set_journal_name(row[\"Journal Name \"])\n self.set_issn(row[\"ISSN\"])\n self.set_journal()\n self.set_currency(row[\"Currency\"])\n if not self.currency:\n continue\n cur = self.get_raw_currency(row[\"Currency\"])\n region = temp[cur]\n self.set_region(region)\n self.set_country(region)\n self.process_fte(row[\"Price Group\"])\n self.set_price(row[\"2021 rate\"])\n self.add_price_to_db()\n\n db.session.commit()", "def _parse_transactions_file(self, path_to_transactions_file: str) -> List[Transaction]:\n ticker_params_to_ticker = {\n (ticker.name, ticker.security_type, ticker.point_value): ticker for ticker in self.tickers\n }\n\n def get_matching_ticker(row: QFSeries) -> Ticker:\n \"\"\" Returns the matching specific ticker. In case if the ticker does not belong to the list of tickers\n passed as the parameter, the transaction is excluded. \"\"\"\n ticker_str = row.loc[\"Contract symbol\"]\n name = row.loc[\"Asset Name\"]\n sec_type = SecurityType(row.loc[\"Security type\"])\n point_value = row.loc[\"Contract size\"]\n ticker = ticker_params_to_ticker.get((name, sec_type, point_value), None)\n if isinstance(ticker, FutureTicker):\n ticker_type = ticker.supported_ticker_type()\n ticker = ticker_type(ticker_str, sec_type, point_value)\n return ticker\n\n transactions_df = pd.read_csv(path_to_transactions_file)\n transactions = [Transaction(pd.to_datetime(row.loc[\"Timestamp\"]),\n get_matching_ticker(row),\n row.loc[\"Quantity\"],\n row.loc[\"Price\"],\n row.loc[\"Commission\"]) for _, row in transactions_df.iterrows()]\n transactions = [t for t in transactions if t.ticker is not None]\n return transactions", "def upload_csv_data(self, upload_file):\n db = DataBase(self.DATABASE_DATA)\n db.insert_data_from_file(\n 'triagedata.historicdata',\n ('clinic_id', 'severity', 'date_received', 'date_seen'),\n upload_file,\n ','\n )", "def csv(self, file, table=None):\n\n if table:\n table.import_from_csv_file(file)\n else:\n db = self.db\n # This is the preferred method as it updates reference fields\n db.import_from_csv_file(file)\n db.commit()", "def _import_insee_city(self, cr, uid, ids, data_dir, context=None):\n if context is None:\n context = {}\n filepath = os.path.abspath(os.path.join(data_dir, 'comsimp2011.csv'))\n city_obj = self.pool.get('insee.city')\n department_obj = self.pool.get('insee.department')\n with open(filepath, 'rb') as cityfile:\n reader = csv.DictReader(cityfile)\n for row in reader:\n args = [('dep', '=', row['DEP'])]\n department_ids = department_obj.search(cr, uid, args)\n department_id = department_ids and department_ids[0] or None\n ncc = row['ARTMAJ'] and row['ARTMAJ'].strip(\"()\") + \\\n row['NCC'] or row['NCC']\n nccenr = row['ARTMIN'] and row['ARTMIN'].strip(\"()\") + \\\n row['NCCENR'] or row['NCCENR']\n values = {\n 'cdc': row['CDC'],\n 'cheflieu': row['CHEFLIEU'],\n 'reg': row['REG'],\n 'dep': row['DEP'],\n 'department_id': department_id,\n 'com': row['COM'],\n 'ar': row['AR'],\n 'ct': row['CT'],\n 'tncc': row['TNCC'],\n 'artmaj': row['ARTMAJ'],\n 'ncc': ncc,\n 'artmin': row['ARTMIN'],\n 'nccenr': nccenr,\n }\n city_obj.create(cr, uid, values, context=context)", "def action_import(self):\n ctx = self._context\n account_obj = self.env[\"account.account\"]\n import_obj = self.env['import.journal.entries.advanced']\n import_line_obj = self.env[\"journal.entries.csv.import\"]\n if 'active_id' in ctx:\n import_id = import_obj.browse(ctx['active_id'])\n if not self.data:\n raise exceptions.Warning(_(\"Necesitas seleccionar un archivo!\"))\n # Decode the file data\n data = base64.b64decode(self.data).decode('utf-8')\n file_input = StringIO(data)\n file_input.seek(0)\n reader_info = []\n if self.delimeter:\n delimeter = str(self.delimeter)\n else:\n delimeter = ','\n reader = csv.reader(file_input, delimiter=delimeter,\n lineterminator='\\r\\n')\n try:\n reader_info.extend(reader)\n except Exception:\n raise exceptions.Warning(_(\"Archivo no valido\"))\n keys = reader_info[0]\n # check if keys exist\n if not isinstance(keys, list) or ('cuenta' not in keys):\n raise exceptions.Warning(_(\"No se encuentran 'cuentas' contable en el archivo\"))\n del reader_info[0]\n values = {}\n actual_date = fields.Date.today()\n for i in range(len(reader_info)):\n val = {}\n field = reader_info[i]\n values = dict(zip(keys, field))\n account = False\n if 'cuenta' in values and values['cuenta']:\n account_id = account_obj.search([('code', '=', values['cuenta'])]) \n if account_id:\n account = account_id[0]\n else:\n account = account_id\n\n val[\"ref\"] = values[\"descripcion\"]\n val[\"document_number\"] = values[\"num_documento\"]\n val[\"document_date\"] = datetime.strptime(values[\"fecha\"] , \"%d-%m-%Y\")\n val['account_id'] = account.id\n val['parent_id'] = import_id.id\n val['debit'] = values['debito']\n val['credit'] = values['credito']\n val['processed'] = False\n validate = import_line_obj.create(val)\n if validate:\n if validate.account_id:\n validate.is_ok = True", "def import_customers(ctx):\n load_csv(ctx, 'data/sample/customers.csv', 'res.partner')", "def payment_engine(transaction_filename: str):\n try:\n transaction_list = TransactionList(pd.read_csv(transaction_filename))\n account_manager = AccountManager()\n transaction_list.process(account_manager)\n accounts = account_manager.accounts_data()\n print(accounts.to_csv(index=False))\n except FileNotFoundError:\n pass", "def load_transaction_data(data_file):\n # Load the transaction data from the csv into a dataframe\n parse_dates = ['Date']\n try:\n df = pd.read_csv(data_file, parse_dates=parse_dates)\n except IOError as e:\n print('Failed to open', data_file,':', e)\n print('Run \"python update-transation-date.py\" to create one, or edit')\n print('\"PATH_TO_YOUR_TRANSACTIONS\" in quarterly-report.py if your data is in a different file')\n quit()\n df.set_index(['Date'], inplace=True)\n df['Amount'] = df['Amount'].astype(float)\n\n # Get rid of Mint columns that we don't care about\n df.drop(['Category', 'Original Description','Notes'], axis=1, inplace=True)\n df.sort_index(inplace=True)\n return df", "def import_rentals(input_data):\n error_count = 0\n insert_count = 0\n LOGGER.info('Starting rental import')\n for onerent in input_data:\n try:\n Rental(onerent['rental_id'], onerent['user_id'], onerent['product_id']).save(full_clean=True,\n force_insert=True)\n insert_count += 1\n except ValidationError as valerror:\n LOGGER.exception(\"Error importing data from csv: %s \", valerror.message)\n error_count += 1\n except OperationError as operror:\n LOGGER.exception(\"Error importing data from csv: %s \", operror)\n error_count += 1\n return insert_count, error_count", "def load_expenditures():\n\n Expenditure.query.delete()\n\n with open(expenditure_file) as f:\n for _ in range(1):\n next(f)\n \n for row in f:\n row = row.rstrip()\n expenditure_data = row.split(\",\")\n print(expenditure_data)\n\n id = expenditure_data[0]\n category_id = expenditure_data[1]\n price = expenditure_data[2]\n date_of_expenditure = expenditure_data[3]\n expenditure_userid = expenditure_data[4]\n where_bought = expenditure_data[5]\n description = expenditure_data[6]\n\n expenditure = Expenditure(\n id = id,\n category_id = category_id,\n price = price,\n date_of_expenditure = get_datetime(date_of_expenditure),\n expenditure_userid = expenditure_userid,\n where_bought = where_bought,\n description = description\n )\n\n db.session.add(expenditure)\n\n db.session.commit()", "def import_prices(self):\n temp = dict(self.currencies_and_regions)\n for index, row in self.df.iterrows():\n self.set_mini_bundle_name(row[\"Journal Name \"])\n self.set_issns(row[\"ISSN\"])\n self.set_currency(row[\"Currency\"])\n if not self.currency:\n continue\n cur = self.get_raw_currency(row[\"Currency\"])\n region = temp[cur]\n self.set_region(region)\n self.set_country(region)\n self.set_price(row[\"2021 rate\"])\n self.add_prices()\n\n # reset for next loop\n self.issns = []\n db.session.commit()", "def import_data(self):\n\t\tif not self.log_files or len(self.log_files) ==0:\n\t\t\tprint \"There is no log files need to import into database\"\n\t\telse:\n\t\t\tfor log_file in self.log_files:\n\t\t\t\tdata = self.read_file(log_file)\n\t\t\t\tself.conn.insert(data)", "def action_import(self):\n ctx = self._context\n \n data = base64.b64decode(self.data)\n file_input = cStringIO.StringIO(data)\n file_input.seek(0)\n reader_info = []\n if self.delimeter:\n delimeter = str(self.delimeter)\n else:\n delimeter = ','\n reader = csv.reader(file_input, delimiter=delimeter,\n lineterminator='\\r\\n')\n try:\n reader_info.extend(reader)\n except Exception:\n raise exceptions.Warning(_(\"Not a valid file!\"))\n keys = reader_info[0]", "def load_sundaes():\n\n print('load_sundaes')\n\n User.query.delete()\n\n for row in open(\"seed_data/sundaes.csv\"):\n row = row.rstrip()\n email, postal_code = row.split(',')\n\n\n usr = User(email=email,\n postal_code=postal_code)\n\n db.session.add(usr)\n\n db.session.commit()", "def import_counties():\n\n query = 'INSERT INTO texas_counties(county, region) VALUES(%s,%s)'\n with persistence() as db:\n # create new cursor instance\n cursor = db.cursor(cursor_factory=psycopg2.extras.RealDictCursor)\n\n for council, counties in COUNCIL_DATA.items():\n for county in counties:\n cursor.execute(query, (county, council))\n db.commit()", "def importxml(db, xmlinput):\n\n from io import StringIO\n import xml.dom.minidom\n\n try:\n doc = xml.dom.minidom.parseString(xmlinput)\n except:\n raise Exception(\"XML parse error\")\n\n parent = doc.childNodes[0].tagName\n csvout = csvheader(parent, doc.childNodes[0].childNodes)\n for subnode in doc.childNodes:\n csvout = csvout + csvdata(subnode.childNodes)\n fh = StringIO()\n fh.write(csvout)\n fh.seek(0, 0)\n db[parent].import_from_csv_file(fh)", "def import_db(import_file):\n import_data(import_file)", "def importer():\n\n #Lager liste der eg legg transaksjonar som blir henta og ikkje laga:\n get_list = []\n\n #Gjer txt-fila i mappen om til csv-fil\n file_fixer()\n\n with open(out_path) as file:\n reader = csv.reader(file)\n r_0 = next(reader)\n r_0.append(\"type\")\n r_0.append('amount')\n r_0.append('category')\n r_0.append('account')\n r_0.append('project')\n\n\n for row in reader:\n #Legger til dei fire kollonenne (amount, account, subaacount, project), tomme.\n row.append(\"\")\n row.append(\"\")\n\n #Omformatterer rader:\n row = format_fix(row)\n row.append(\"\")\n row.append(\"\")\n row.append(\"\")\n print(row)\n\n\n try:\n obj, created = Transaction.objects.get_or_create(\n date=row[0],\n transaction_type=row[1],\n description=row[2],\n amount=row[3]\n )\n\n except Transaction.MultipleObjectsReturned:\n continue\n\n if not created:\n get_list.append(obj.pk)\n\n return get_list", "def import_products_from_csv(self):\n shopify_product_template = self.env[\"shopify.product.template.ept\"]\n shopify_product_obj = self.env[\"shopify.product.product.ept\"]\n common_log_obj = self.env[\"common.log.book.ept\"]\n shopify_product_image_obj = self.env[\"shopify.product.image.ept\"]\n common_log_line_obj = self.env[\"common.log.lines.ept\"]\n model_id = common_log_line_obj.get_model_id(\"shopify.process.import.export\")\n\n if not self.choose_file:\n raise ValidationError(\"File Not Found To Import\")\n if not self.file_name.endswith(\".csv\"):\n raise ValidationError(\"Please Provide Only .csv File To Import Product !!!\")\n file_data = self.read_file()\n log_book_id = common_log_obj.create({\"type\": \"export\",\n \"module\": \"shopify_ept\",\n \"shopify_instance_id\": self.shopify_instance_id.id,\n \"active\": True})\n required_field = [\"template_name\", \"product_name\", \"product_default_code\",\n \"shopify_product_default_code\", \"product_description\",\n \"PRODUCT_TEMPLATE_ID\", \"PRODUCT_ID\", \"CATEGORY_ID\"]\n for required_field in required_field:\n if not required_field in file_data.fieldnames:\n raise Warning(\"Required Column Is Not Available In File\")\n sequence = 0\n row_no = 1\n shopify_template_id = False\n for record in file_data:\n message = \"\"\n if not record[\"PRODUCT_TEMPLATE_ID\"] or not record[\"PRODUCT_ID\"] or not record[\n \"CATEGORY_ID\"]:\n message += \"PRODUCT_TEMPLATE_ID Or PRODUCT_ID Or CATEGORY_ID Not As Per Odoo Product %s\" % (\n row_no)\n vals = {\"message\": message,\n \"model_id\": model_id,\n \"log_line_id\": log_book_id.id,\n }\n common_log_line_obj.create(vals)\n continue\n shopify_template = shopify_product_template.search(\n [(\"shopify_instance_id\", \"=\", self.shopify_instance_id.id),\n (\"product_tmpl_id\", \"=\", int(record[\"PRODUCT_TEMPLATE_ID\"]))])\n\n if not shopify_template:\n shopify_product_template_vals = (\n {\"product_tmpl_id\": int(record[\"PRODUCT_TEMPLATE_ID\"]),\n \"shopify_instance_id\": self.shopify_instance_id.id,\n \"shopify_product_category\": int(record[\"CATEGORY_ID\"]),\n \"name\": record[\"template_name\"],\n \"description\": record[\"product_description\"],\n \"exported_in_shopify\":False,\n \"website_published\":False\n })\n shopify_template = shopify_product_template.create(shopify_product_template_vals)\n sequence = 1\n shopify_template_id = shopify_template.id\n\n else:\n if shopify_template_id != shopify_template.id:\n shopify_product_template_vals = (\n {\"product_tmpl_id\": int(record[\"PRODUCT_TEMPLATE_ID\"]),\n \"shopify_instance_id\": self.shopify_instance_id.id,\n \"shopify_product_category\": int(record[\"CATEGORY_ID\"]),\n \"name\": record[\"template_name\"],\n \"description\": record[\"product_description\"]\n })\n shopify_template.write(shopify_product_template_vals)\n shopify_template_id = shopify_template.id\n\n # For adding all odoo images into shopify layer.\n # if shopify_template_id != shopify_template.id:\n shoify_product_image_list = []\n product_template = shopify_template.product_tmpl_id\n for odoo_image in product_template.ept_image_ids.filtered(lambda x: not x.product_id):\n shopify_product_image = shopify_product_image_obj.search_read(\n [(\"shopify_template_id\", \"=\", shopify_template_id),\n (\"odoo_image_id\", \"=\", odoo_image.id)], [\"id\"])\n if not shopify_product_image:\n shoify_product_image_list.append({\n \"odoo_image_id\": odoo_image.id,\n \"shopify_template_id\": shopify_template_id\n })\n if shoify_product_image_list:\n shopify_product_image_obj.create(shoify_product_image_list)\n\n if shopify_template and shopify_template.shopify_product_ids and \\\n shopify_template.shopify_product_ids[\n 0].sequence:\n sequence += 1\n shopify_variant = shopify_product_obj.search(\n [(\"shopify_instance_id\", \"=\", self.shopify_instance_id.id), (\n \"product_id\", \"=\", int(record[\"PRODUCT_ID\"])),\n (\"shopify_template_id\", \"=\", shopify_template.id)])\n if not shopify_variant:\n shopify_variant_vals = ({\"shopify_instance_id\": self.shopify_instance_id.id,\n \"product_id\": int(record[\"PRODUCT_ID\"]),\n \"shopify_template_id\": shopify_template.id,\n \"default_code\": record[\"shopify_product_default_code\"],\n \"name\": record[\"product_name\"],\n \"sequence\": sequence\n })\n shopify_variant = shopify_product_obj.create(shopify_variant_vals)\n else:\n shopify_variant_vals = ({\"shopify_instance_id\": self.shopify_instance_id.id,\n \"product_id\": int(record[\"PRODUCT_ID\"]),\n \"shopify_template_id\": shopify_template.id,\n \"default_code\": record[\"shopify_product_default_code\"],\n \"name\": record[\"product_name\"],\n \"sequence\": sequence\n })\n shopify_variant.write(shopify_variant_vals)\n row_no = +1\n # For adding all odoo images into shopify layer.\n product_id = shopify_variant.product_id\n odoo_image = product_id.ept_image_ids\n if odoo_image:\n shopify_product_image = shopify_product_image_obj.search_read(\n [(\"shopify_template_id\", \"=\", shopify_template_id),\n (\"shopify_variant_id\", \"=\", shopify_variant.id),\n (\"odoo_image_id\", \"=\", odoo_image[0].id)], [\"id\"])\n if not shopify_product_image:\n shopify_product_image_obj.create({\n \"odoo_image_id\": odoo_image[0].id,\n \"shopify_variant_id\": shopify_variant.id,\n \"shopify_template_id\": shopify_template_id,\n })\n if not log_book_id.log_lines:\n log_book_id.unlink()\n return {\n \"type\": \"ir.actions.client\",\n \"tag\": \"reload\",\n }", "def import_customers(input_data):\n error_count = 0\n insert_count = 0\n LOGGER.info('Starting Customer import')\n for onecust in input_data:\n try:\n Customer(onecust['user_id'], onecust['first_name'], onecust['last_name'],\n onecust['address'], onecust['phone_number'], onecust['email'])\\\n .save(full_clean=True, force_insert=True)\n insert_count += 1\n except ValidationError as valerror:\n LOGGER.exception(\"Error importing data from csv: %s \", valerror.message)\n error_count += 1\n except (OperationError, DuplicateKeyError) as operror:\n LOGGER.exception(\"Error importing data from csv: %s \", operror)\n error_count += 1\n\n return insert_count, error_count", "def ingest_rental_csv(csv_path):\n # Create a CSV import generator (next yields one db row)\n import_generator = import_csv_gen(csv_path)\n # Skip over the title row\n next(import_generator)\n # Iterate over all other rows\n while True:\n try:\n data = next(import_generator)\n if len(data) != 2:\n logger.error(f'Data with incorrect item count: {len(data)}')\n continue\n # extract items from list and add document to database\n with Connection():\n rental = Rental(\n product_id=data[RENTAL_PROD_ID],\n user_id=data[RENTAL_USER_ID]\n )\n rental.save() # This will perform an insert\n except StopIteration:\n break", "def loadTaxi(file):\n arr = []\n with open(file, newline='') as csvfile:\n reader = csv.DictReader(csvfile)\n for row in reader:\n row['fare_amount'] = float(row['fare_amount'])\n row['pickup_longitude'] = float(row['pickup_longitude'])\n row['pickup_latitude'] = float(row['pickup_latitude'])\n row['dropoff_longitude'] = float(row['dropoff_longitude'])\n row['dropoff_latitude'] = float(row['dropoff_latitude'])\n row['pickup_datetime'] = datetime.strptime(\n row['pickup_datetime'], '%Y-%m-%d %H:%M:%S %Z')\n arr.append(row)\n\n inserted_ids = db.taxi.insert_many(arr).inserted_ids\n print(\"{} taxi docs inserted\".format(len(inserted_ids)))", "def _import_cryptocom_double_entries(self, data: Any, double_type: str) -> None:\n double_rows: Dict[Any, Dict[str, Any]] = {}\n debited_row = None\n credited_row = None\n for row in data:\n if row['Transaction Kind'] == f'{double_type}_debited':\n timestamp = deserialize_timestamp_from_date(\n date=row['Timestamp (UTC)'],\n formatstr='%Y-%m-%d %H:%M:%S',\n location='crypto.com',\n )\n if timestamp not in double_rows:\n double_rows[timestamp] = {}\n double_rows[timestamp]['debited'] = row\n elif row['Transaction Kind'] == f'{double_type}_credited':\n timestamp = deserialize_timestamp_from_date(\n date=row['Timestamp (UTC)'],\n formatstr='%Y-%m-%d %H:%M:%S',\n location='crypto.com',\n )\n if timestamp not in double_rows:\n double_rows[timestamp] = {}\n double_rows[timestamp]['credited'] = row\n\n for timestamp in double_rows:\n credited_row = double_rows[timestamp]['credited']\n debited_row = double_rows[timestamp]['debited']\n if credited_row is not None and debited_row is not None:\n description = credited_row['Transaction Description']\n notes = f'{description}\\nSource: crypto.com (CSV import)'\n # No fees here\n fee = Fee(ZERO)\n fee_currency = A_USD\n\n base_asset = Asset(credited_row['Currency'])\n quote_asset = Asset(debited_row['Currency'])\n pair = TradePair(f'{base_asset.identifier}_{quote_asset.identifier}')\n base_amount_bought = deserialize_asset_amount(credited_row['Amount'])\n quote_amount_sold = deserialize_asset_amount(debited_row['Amount'])\n rate = Price(abs(base_amount_bought / quote_amount_sold))\n\n trade = Trade(\n timestamp=timestamp,\n location=Location.CRYPTOCOM,\n pair=pair,\n trade_type=TradeType.BUY,\n amount=base_amount_bought,\n rate=rate,\n fee=fee,\n fee_currency=fee_currency,\n link='',\n notes=notes,\n )\n self.db.add_trades([trade])", "def load_records():\n\n with open('seed_data/records.csv', 'rb') as csvfile:\n data = csv.reader(csvfile)\n for row in data:\n record_id, user_id, common_name, date_time, latitude, longitude, notes, seen, num_birds = row\n\n record = Record(record_id=record_id, user_id=user_id, common_name=common_name,\n date_time=date_time, latitude=latitude, longitude=longitude, \n notes=notes, seen=seen, num_birds=num_birds)\n\n db.session.add(record)\n\n db.session.commit()", "def load_all_transactions(filename):\n transacions = pd.read_csv(join(DATA_DIR, filename))\n print('\\nTher are a toral of {} transactions and {} features \\n'.format(transacions.shape[0],transacions.columns))\n return transacions", "def process_csv(self, user: User, csv_file):\n self.db_session.rollback()\n csv = pandas.read_csv(StringIO(csv_file.read().decode('utf-8')))\n missing_cols = [col_name for col_name in CSV_SENSOR_MAP.values() if col_name not in csv.columns.values]\n if missing_cols:\n raise OBDControllerError(f'CSV is missing the following columns: {\", \".join(missing_cols)}')\n\n csv = csv[CSV_SENSOR_MAP.values()]\n start_datetime = self._resolve_date_from_csv_row(csv.iloc[0])\n gen_session_id = str(start_datetime.timestamp()).replace('.', '')[:12]\n\n if self.db_session.query(OBDSession).filter(OBDSession.id == gen_session_id).first():\n return\n\n session = OBDSession.create(self.db_session, id=gen_session_id, user_id=user.id, date=start_datetime)\n _ = CarState.create_from_csv(self.db_session, session, csv)\n self.db_session.commit()", "def load_data(data_path):\n \n # Load the dataset\n df = pd.read_csv(data_path)\n \n # Perform feature transformations\n df[\"description_processed\"] = nlp_preprocessing(df[\"transaction_description\"])\n df['transaction_type'] = convert_transaction_amount(df['transaction_amount'])\n \n df.loc[~df['transaction_account_type'].isin(('transaction', 'savings', 'credit-card')), 'transaction_account_type'] = \"other\"\n \n return df" ]
[ "0.57314825", "0.56849045", "0.56194824", "0.5504415", "0.55042666", "0.548409", "0.5430128", "0.5427457", "0.5426252", "0.54128426", "0.54050434", "0.540121", "0.5381555", "0.5338282", "0.5322756", "0.53020173", "0.53004", "0.5272485", "0.5258901", "0.52493286", "0.5227675", "0.5204632", "0.5201966", "0.51892966", "0.5187598", "0.51720774", "0.51710725", "0.51443046", "0.5134972", "0.512045" ]
0.57197523
1
Book DB transactions matching CLI args to inventory; write Gains to disk.
def dump_gains(args: argparse.Namespace) -> None: engine = create_engine() dump_csv( engine, dtstart=args.dtstart, dtend=args.dtend, dtstart_gains=args.begin, consolidate=args.consolidate, lotloadfile=args.loadcsv, gaindumpfile=args.file, )
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def main():\n dump(inventory(), fp=stdout, indent=4)", "def main():\n\n # Local constants\n\n # Local variables\n args = sys.argv\n db = dblayer()\n g = graphutil()\n\n #****** start main() ******#\n \n # Check to see if too many args, or need help\n if len(args) < 2 or args[1] == \"help\":\n usage()\n\n # User chose add command\n if args[1] == \"add\":\n if len(args) < 3: usage()\n res = db.insert_card(parse(args[2].split(\"?\")[0]))\n\n if res is not None:\n print(\"\\n\" + res + \"\\n\")\n\n # User chose delete command\n elif args[1] == \"delete\":\n if len(args) < 3: usage()\n res = db.delete_card(args[2].split(\"?\")[0])\n\n if res is not None:\n print(\"\\n\" + res + \"\\n\")\n\n # User chose update command \n elif args[1] == \"update\":\n print()\n print(\"\\tGetting URLs...\")\n urls = db.get_urls()\n\n print(\"\\tUpdating prices...\")\n for url in urls:\n db.insert_price_data(parse(url[0]))\n\n print(\"\\tDone.\\n\")\n\n # User chose top25 command\n elif args[1] == \"top25\":\n t = PrettyTable(['Pokemon', 'Set', 'Normal Price', 'Foil Price', 'Price Date'])\t\n res = db.top25()\n for r in res:\n t.add_row([r[0], r[1], r[2], '$' + str(r[3]), r[4]])\n\n print(t)\n\n # User chose export command\n elif args[1] == \"export\":\n urls = db.get_urls()\n filename = 'export' + datetime.now().strftime(\"%Y%m%d%H%M\") + '.txt'\n\n with open(filename, 'w') as f:\n for url in urls:\n f.write(url[0] + \"\\n\")\n\n # User chose export_collection command \n elif args[1] == \"export_collection\":\n filename = 'collection_export' + datetime.now().strftime(\"%Y%m%d%H%M\") + '.csv'\n with open(filename, 'w', newline = '') as csvfile:\n headers = ['Pokemon', 'Set', 'Normal Price ($)', 'Foil Price ($)', 'Price Date']\n w = csv.writer(csvfile, delimiter=',')\n w.writerow(headers)\n\n res = db.export()\n \n for r in res:\n r = list(r)\n if r[2] == None: r[2] = ''\n if r[3] == None: r[3] = ''\n w.writerow([r[0], r[1], str(r[2]), str(r[3]), r[4]])\n\n # User chose import command\n elif args[1] == \"import\":\n if len(args) < 3: usage()\n f = open(args[2], \"r\")\n\n for l in f:\n db.insert_card(parse(l.strip().split(\"?\")[0]))\n\n # User chose worth command\n elif args[1] == \"worth\":\n prices = db.worth()\n\n locale.setlocale(locale.LC_ALL, '')\n print()\n print(\"\\tNormal: \" + locale.currency(prices[0], grouping=True))\n print(\"\\tFoil : \" + locale.currency(prices[1], grouping=True))\n print(\"\\tTotal : \" + locale.currency(prices[0]+prices[1], grouping=True))\n print()\n\n # User chose graph command\n elif args[1] == \"graph\":\n if len(args) < 3: usage()\n url = args[2].split(\"?\")[0]\n price_data = db.get_card_price_data(url)\n card_details = db.get_card_details(url)\n g.graph_card_worth(price_data, card_details)\n \n # User chose graph_worth command\n elif args[1] == \"graph_worth\":\n if len(args) < 2: usage()\n price_data = db.graph_worth()\n g.graph_collection_worth(price_data)\n\n # User chose ticker command\n elif args[1] == \"ticker\":\n if len(args) > 2: days_back = str(args[2])\n else: days_back = str(7)\n\n ret = db.ticker(days_back)\n\n locale.setlocale(locale.LC_ALL, '') \n data = []\n\n for key, value in ret.items():\n data.append([key, value[0], value[1], value[2], value[3], value[4]])\n \n data.sort(key=lambda x: float(x[5]))\n\n t = PrettyTable(['Pokemon Card', 'Start Price (' + datetime.strftime(datetime.today() - timedelta(days=int(days_back)), \"%Y-%m-%d\") + \")\", 'Current Price (' + data[0][3] + \")\", \"Change (+/-)\"])\n\n for x in reversed(data):\n if float(x[2]) > float(x[4]): x[5] = \"-\"\n else: x[5] = \"+\"\n x[5] += str(round(abs(float(x[2]) - float(x[4])), 2))\n t.add_row([x[0], locale.currency(x[2], grouping=True), locale.currency(x[4], grouping=True), x[5]])\n\n print(t)", "def save(self, name, args, user):\n # Make sure the given arguments are valid first.\n RollCommand.from_args(args)\n\n connection = self.connect()\n cursor = connection.cursor()\n cursor.execute(\n self.sql[\"save\"], {\"name\": name, \"args\": \" \".join(args), \"user\": user}\n )\n connection.commit()", "def test_cli_save():\n with open(os.path.join(self._tempdir, \".inventory.toml\"), \"w\") as f:\n toml.dump(self._inventory, f)\n\n with open(os.path.join(self._tempdir, \".config.toml\"), \"w\") as f:\n toml.dump(self._config, f)\n\n assert 0 == subprocess.call([\n sys.executable, \"-u\", \"-m\", \"avalon.inventory\", \"--save\"\n ], cwd=self._tempdir)", "def send_to_db(ck_transactions):\n db = DDDB()\n\n db.add_orders(ck_transactions)", "def do_buy(self, args):\n if not self._check_args(args):\n return\n else:\n self.wallet.get_coins_from_faucet(args)", "def do_store(self, arg):\r\n\r\n # put this value in a more suitably named variable\r\n itemToStore = arg.lower()\r\n\r\n # get a list of all \"description words\" for each item in the inventory\r\n invDescWords = getAllDescWords(inventory)\r\n \r\n # Nice little easter egg :) \r\n if itemToStore == 'troll in bag':\r\n print(bcolors.start + \"You cannot put troll in bag, troll is a creature.\" + bcolors.end)\r\n return\r\n\r\n # find out if the player doesn't have that item\r\n if itemToStore not in invDescWords:\r\n print('%s does not exist in your inventory, the ground, africa or your pockets, what a shame.' % (itemToStore))\r\n return\r\n \r\n\r\n # get the item name that the player's command describes\r\n \r\n try:\r\n item = getFirstItemMatchingDesc(itemToStore, inventory)\r\n \r\n # broken currently, needs some work doing to check if the STORAGE value exists in the current room then store the item.\r\n if item != None:\r\n print('You store %s in a safe place.' % (worldItems[item][SHORTDESC]))\r\n inventory.remove(item)\r\n worldRooms[location][STORAGE].append(item)\r\n except KeyError:\r\n return(\"Don't even think about it buster brown.\")\r\n \r\n #item = getFirstItemMatchingDesc(itemToStore, inventory)\r\n #if item != None:\r\n # print('You store %s in a safe place.' % (worldItems[item][SHORTDESC]))\r\n # inventory.remove(item) # remove from inventory\r\n # worldRooms[location][STORAGE].append(item) # add to the container\r", "def commit_req(): \r\n \r\n req_id = request.args[0]\r\n r_req = db.logs_req[req_id]\r\n inventory_store_id = request.vars.get(\"inventory_store_id\")\r\n\r\n # Create a new commit record\r\n commit_id = db.logs_commit.insert( datetime = request.utcnow,\r\n logs_req_id = req_id,\r\n inventory_store_id = inventory_store_id,\r\n for_inventory_store_id = r_req.inventory_store_id\r\n )\r\n \r\n #Only populate commit items if we know the store committing \r\n if inventory_store_id:\r\n #Only select items which are in the warehouse\r\n req_items = db( (db.logs_req_item.logs_req_id == req_id) & \\\r\n (db.logs_req_item.quantity_fulfil < db.logs_req_item.quantity) & \\\r\n (db.inventory_store_item.inventory_store_id == inventory_store_id) & \\\r\n (db.logs_req_item.item_id == db.inventory_store_item.item_id) & \\\r\n (db.logs_req_item.deleted == False) & \\\r\n (db.inventory_store_item.deleted == False)\r\n ).select(db.logs_req_item.id,\r\n db.logs_req_item.quantity,\r\n db.logs_req_item.item_packet_id,\r\n db.inventory_store_item.item_id,\r\n db.inventory_store_item.quantity,\r\n db.inventory_store_item.item_packet_id) \r\n \r\n for req_item in req_items:\r\n req_item_quantity = req_item.logs_req_item.quantity * \\\r\n req_item.logs_req_item.packet_quantity \r\n \r\n store_item_quantity = req_item.inventory_store_item.quantity * \\\r\n req_item.inventory_store_item.packet_quantity\r\n \r\n if store_item_quantity > req_item_quantity:\r\n commit_item_quantity = req_item_quantity\r\n else:\r\n commit_item_quantity = store_item_quantity\r\n commit_item_quantity = commit_item_quantity / req_item.logs_req_item.packet_quantity\r\n \r\n if commit_item_quantity: \r\n commit_item_id = db.logs_commit_item.insert( logs_commit_id = commit_id,\r\n logs_req_item_id = req_item.logs_req_item.id,\r\n item_packet_id = req_item.logs_req_item.item_packet_id,\r\n quantity = commit_item_quantity\r\n ) \r\n \r\n #Update the req_item.commit_quantity & req.commit_status \r\n session.rcvars.logs_commit_item = commit_item_id\r\n logs_commit_item_onaccept(None)\r\n \r\n # Redirect to commit\r\n redirect(URL(r = request,\r\n c = \"logs\",\r\n f = \"commit\",\r\n args = [commit_id, \"commit_item\"]\r\n )\r\n )", "def command_dbtool(self):\n dbtool.main(*self.args())", "def main(connection, info, args, world) :\n money = shelve.open(\"money-%s.db\" % (world.hostnicks[connection.host]), writeback=True)\n money[info[\"sender\"]] = {\"money\":100000, \"maxmoney\":100000, \"items\":[], \"coinchance\":[True for x in range(50)] + [False for x in range(50)]}\n money.sync()\n connection.ircsend(info[\"channel\"], \"%s: Your money data has been reset.\" % (info[\"sender\"]))", "def run(self, args):\n db_path: str = args.db\n start: int = args.start\n end: int = args.end\n\n checker = InvalidTransactionChecker()\n try:\n checker.open(db_path)\n checker.run(start, end)\n finally:\n checker.close()", "def main():\r\n db = connect_database()\r\n with db:\r\n if sys.argv[1] == \"-s\":\r\n select_all(db, sys.argv[2])\r\n elif sys.argv[1] == \"-i\":\r\n cus_data = []\r\n for i in range(2, len(sys.argv)):\r\n cus_data.append(sys.argv[i])\r\n insert_customer(db, cus_data)\r\n elif sys.argv[1] == \"-c\":\r\n create_tables()\r\n elif sys.argv[1] == \"-pw\":\r\n pop_waiting(db, sys.argv[2])\r\n elif sys.argv[1] == \"-ph\":\r\n pop_help(db, sys.argv[2])\r\n elif sys.argv[1] == \"-r\":\r\n refresh_tables(db)\r\n elif sys.argv[1] == \"-e\":\r\n export_helped_table(db)\r\n else:\r\n print errorArgument\r\n db.close()", "def write_trade() -> None:\n try:\n ddb_table.put_item(Item = data_to_insert)\n except Exception as e:\n _LOGGER.error('Problem updating dynamodb trade data. {0}'.format(e))\n raise Exception('Problem updating dynamodb trade data. {0}'.format(e))", "def main():\n parser = argparse.ArgumentParser(description='Saves MtGox trades for a time period')\n parser.add_argument('-s','--start', help='The start date in ' + input_dateformat + 'format', required=True)\n parser.add_argument('-e','--end', help='The end date'+ input_dateformat + 'format', required=True)\n args = vars(parser.parse_args())\n start=get_unixtime(args['start'], input_dateformat)\n end=get_unixtime(args['end'], input_dateformat)\n if end < start:\n print \"End timestamp must be later than start timestamp. Exiting\"\n sys.exit()\n print \"Will get trades from \", start, \"to\", end\n\n \"\"\" read the output file and adjust the start date, if it exists\n \"\"\"\n try:\n with open(outfile_name, \"r\") as in_file:\n goxdata = in_file.readlines() \n saved_start=get_unixtime(goxdata[0].split(\",\")[0], input_dateformat)\n saved_end=get_unixtime(goxdata[len(goxdata)-1].split(\",\")[0], input_dateformat)\n\n print \"File found, with start date:\", saved_start, \"and end date\", saved_end\n if start < saved_end:\n print \"Adjusted start time from \", start, \"to \", saved_end\n start = saved_end\n except IOError:\n print \"Output file not found. Will create a new one.\"\n\n \"\"\" get data from MtGox in chunks\n \"\"\"\n try:\n currstart = start\n endreached = False\n while endreached == False:\n # populate the trades dictionary with the next batch of data\n data = fetch_data(currstart)\n print \"Fetching data\", currstart\n if (data == '[]'):\n break \n trades = [mtgox_trade(a) for a in json.loads(data)]\n currstart = trades[-1].timestamp\n\n if trades[-1].timestamp > end:\n endreached = True\n\n # place trades into the out_file before getting the next batch from MtGox \n # so that if the program gets interrupt you have saved the trades obtained so far\n with open(outfile_name, \"a\") as out_file:\n for item in trades:\n # when you request data from a timestamp gox truncates your start time to seconds and then\n # send you everything including the initial second. So you must filter here trades\n # of the start_time second that are already in the database.\n if item.timestamp > start and item.timestamp < end:\n out_file.write(item.trade_to_string()+\"\\n\")\n\n except urllib2.HTTPError, e:\n print \"Error:\", str(e.code), str(e.reason)\n return\n except urllib2.URLError, e:\n print \"Error:\", e\n return", "def main(argv):\n # -- load our run database and make it global --\n global crysDB\n with open(\"crysDB.json\") as f:\n crysDB = json.load(f)\n\n # -- parse args --\n par = argparse.ArgumentParser(description=\"coherent crystal characterization suite\")\n arg = par.add_argument\n arg(\"-c\", \"--crys\", type=str, help=\"set crystal S/N\")\n arg(\"-p\", \"--proc\", type=str, help=\"process a crystal\")\n arg(\"-t\", \"--temp\", type=str, help='start temperature data taking')\n arg(\"-pt\", \"--printtemp\", type=str, help='print current temperature')\n arg(\"-a\", \"--all\", action=\"store_true\", help=\"process all crystals in the DB\")\n arg(\"-o\", \"--over\", action=\"store_true\", help=\"overwrite existing files\")\n arg(\"-z\", \"--zip\", action=\"store_true\", help='run gzip on raw files (on cenpa-rocks)')\n arg(\"-s\", \"--sync\", action=\"store_true\", help='sync DAQ with cenpa-rocks')\n args = vars(par.parse_args())\n\n # -- set parameters --\n crys_sn, overwrite = None, False\n\n if args[\"crys\"]:\n crys_sn = args[\"crys\"]\n\n if args[\"over\"]:\n overwrite = args[\"over\"]\n\n # -- run analysis --\n if args[\"proc\"]:\n sn = args[\"proc\"]\n process_crystal(sn, overwrite)\n\n if args[\"all\"]:\n all_sns = [k for k in crysDB if \"SN\" in k]\n for sn in all_sns:\n process_crystal(sn, overwrite)\n\n if args[\"sync\"]:\n sync_data()\n\n if args[\"zip\"]:\n # clean_gzip()\n zip_data(overwrite)\n\n if args[\"temp\"]:\n \"\"\"\n Run number should be the first run number entry (for 600V) in the ELOG.\n \"\"\"\n run_num = args[\"temp\"]\n measure_temp(run_num)\n\n if args[\"printtemp\"]:\n print_temp()", "def do_orders(self,args):\n try:\n orders = bitstamp.open_orders()\n orders = sorted(orders, key=lambda x: float(x['price']))\n buytotal,selltotal = 0,0\n numbuys,numsells = 0,0\n amtbuys,amtsells = 0,0\n buyavg,sellavg = 0,0\n numorder = 0 \n for order in orders:\n ordertype=\"Sell\" if order['type'] == 1 else \"Buy\"\n numorder += 1\n print '%s = %s | $%s @ %s BTC %s' % (numorder,ordertype,order['price'],order['amount'],order['id']) \n if order['type'] == 0:\n buytotal += D(order['price'])*D(order['amount'])\n numbuys += D('1')\n amtbuys += D(order['amount'])\n elif order['type'] == 1:\n selltotal += D(order['price'])*D(order['amount'])\n numsells += D('1')\n amtsells += D(order['amount'])\n if amtbuys:\n buyavg = D(buytotal/amtbuys).quantize(cPrec)\n if amtsells:\n sellavg = D(selltotal/amtsells).quantize(cPrec)\n print \"There are %s Buys. There are %s Sells\" % (numbuys,numsells)\n print \"Avg Buy Price: $%s. Avg Sell Price: $%s\" % (buyavg,sellavg)\n except Exception as e:\n print e", "def do_put(self, arg):\r\n\r\n # put this value in a more suitably named variable\r\n itemToStore = arg.lower()\r\n\r\n # get a list of all \"description words\" for each item in the inventory\r\n invDescWords = getAllDescWords(inventory)\r\n \r\n # Nice little easter egg :) \r\n if itemToStore == 'troll in bag':\r\n print(bcolors.start + \"You cannot put troll in bag, troll is a creature.\" + bcolors.end)\r\n return\r\n\r\n # find out if the player doesn't have that item\r\n if itemToStore not in invDescWords:\r\n print('You want to put \"%s\" in what?!' % (itemToStore))\r\n return\r\n \r\n\r\n # get the item name that the player's command describes\r\n item = getFirstItemMatchingDesc(itemToStore, inventory)\r\n if item != None:\r\n print('You put %s. in the container.' % (worldItems[item][SHORTDESC]))\r\n inventory.remove(item) # remove from inventory\r\n worldRooms[location][ITEMINV].append(item) # add to the container\r", "async def module_command_backup(self, ctx, parsed):\n if parsed.invoker != ctx.owner:\n return\n file = parsed.args[\"name\"]\n file = file.with_suffix(f\"{file.suffix}.sqlite\")\n await self.database_create_backup(file)\n await ctx.core_command_backup(parsed, file)", "def do_command(self, args):\n vendorops = dbops.Vendors()\n vendorops.add(args)", "def process(args):\n # Prepare database connection, table, and session.\n dsl = 'sqlite:///' + (args.output or DEFAULT_SQLITE_FILE)\n engine = create_engine(dsl, echo=True)\n Base.metadata.create_all(engine)\n Session.configure(bind=engine)\n session = Session()\n with open(args.filename[0], encoding=args.encoding) as fp:\n reader = csv.reader(fp) # Instantiate CSV reader with file pointer.\n _ = next(reader) # skip header line\n for t in reader:\n # Convert input values to declared name and type.\n dt = {}\n for i, f in enumerate(FIELDS):\n if f['type'] == 'integer':\n dt[f['id']] = int(t[i])\n elif f['type'] == 'float':\n dt[f['id']] = float(t[i])\n elif f['type'] == 'datetime':\n dt[f['id']] = datetime.datetime.strptime(t[i], f['format'])\n else:\n dt[f['id']] = t[i]\n # Instantiate SQLAlchemy data model object.\n p = StockPrice(**dt)\n # Show the same things with previous scripts.\n diff = p.diff()\n if diff > 0:\n message = 'up'\n elif diff < 0:\n message = 'down'\n else:\n message = 'same'\n # Write out day, up/down/same, and diff.\n print(f'{p.day}\\t{message:5}\\t{round(diff, 2)}')\n session.add(p)\n # Don't forget to commit the changes you add.\n session.commit()", "def do_bet(self, arg):\n\t\topts = get_options(parser.parser_add, arg)\n\t\tif opts is None: return\n\t\tkwargs = {}\n\t\tkwargs['name'] = ' '.join(opts.broken_name)\n\t\tkwargs['weight'] = opts.weight\n\t\tif opts.outcome is not None:\n\t\t\tkwargs['outcome'] = convert_outcome(opts.outcome)\n\t\tself.manager.add_bet(**kwargs)\n\t\tprint(display.format_bet(self.manager.bets[-1]))", "def commit(self):\n\t\t## Loops through ALL items\n\t\tfor k in self.data.keys():\n\t\t\tfor item in self[k]:\n\n\t\t\t\t## If the object needs committing, commit it!\n\t\t\t\tif item['meta']['needs_commit']:\n\t\t\t\t\t## Create file contents as an empty string\n\t\t\t\t\tfile_contents = \"\"\n\n\t\t\t\t\t## find any other items that may share this config file\n\t\t\t\t\textra_items = self._get_items_in_file(item['meta']['filename'])\n\t\t\t\t\tif len(extra_items) > 0:\n\t\t\t\t\t\tfor commit_item in extra_items:\n\t\t\t\t\t\t\t## Ignore files that are already set to be deleted:w\n\t\t\t\t\t\t\tif commit_item['meta']['delete_me']:\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t## Make sure we aren't adding this thing twice\n\t\t\t\t\t\t\tif item != commit_item:\n\t\t\t\t\t\t\t\tfile_contents += self.print_conf(commit_item)\n\n\t\t\t\t\t## This is the actual item that needs commiting\n\t\t\t\t\tif not item['meta']['delete_me']:\n\t\t\t\t\t\tfile_contents += self.print_conf(item)\n\n\t\t\t\t\t## Write the file\n\t\t\t\t\tf = open(item['meta']['filename'], 'w')\n\t\t\t\t\tf.write(file_contents)\n\t\t\t\t\tf.close()\n\n\t\t\t\t\t## Recreate the item entry without the commit flag\n\t\t\t\t\tself.data[k].remove(item)\n\t\t\t\t\titem['meta']['needs_commit'] = None\n\t\t\t\t\tself.data[k].append(item)", "def main():\n\n parser = init_parser()\n args = parser.parse_args()\n\n # Set up logging.\n level = logging.INFO\n if args.debug:\n level = logging.DEBUG\n logging.basicConfig(format='%(asctime)s %(levelname)s %(filename)s:' \\\n '%(lineno)s %(message)s ', level=level)\n logging.info(\"Logging started\")\n\n message = \"Backing up \"\n if args.source_code:\n message += \"source and \"\n message += \"data for: {0}\".format(args.app_id)\n logging.info(message)\n\n zk_connection_locations = appscale_info.get_zk_locations_string()\n zookeeper = zk.ZKTransaction(host=zk_connection_locations)\n db_info = appscale_info.get_db_info()\n table = db_info[':table']\n\n skip_list = args.skip\n if not skip_list:\n skip_list = []\n logging.info(\"Will skip the following kinds: {0}\".format(sorted(skip_list)))\n ds_backup = DatastoreBackup(args.app_id, zookeeper, table,\n source_code=args.source_code, skip_list=sorted(skip_list))\n try:\n ds_backup.run()\n finally:\n zookeeper.close()", "def backup_database():\n logger.info(\"start database_backup\")\n management.call_command('dbbackup', compress=True)\n logger.info(\"end database_backup\")", "def do_withdraw(self, args):\n \n amount = float(input(\"How much? \"))\n \n balance = self.cur.execute(\"SELECT * FROM balance ORDER BY date DESC\").fetchone()[2]\n if amount > balance:\n print(\"Insufficient funds! Withdrawl canceled.\")\n print(\"Use the `balance` command to check your account balance\")\n return\n \n balance -= amount\n now = time()\n self.cur.execute(\"INSERT INTO withdrawls VALUES (?,?)\", (now, amount))\n self.cur.execute(\"INSERT INTO balance VALUES (?,?,?)\", (now, 0.0, balance))\n self.db.commit()\n print(\"Withdrawl complete. Your new balance is $%.2f\" % balance)", "def book(self, irc, msg, args, thing):\n self.db.deleteExpired(self.registryValue('orderExpiry'))\n results = self.db.getCurrencyBook(thing)\n if len(results) == 0:\n irc.error(\"No orders for this currency present in database.\")\n return\n if len(results) > self.registryValue('maxOrdersInBookList'):\n irc.error(\"Too many orders to list on IRC. Visit the web \"\n \"order book, http://bitcoin-otc.com/vieworderbook.php?eitherthing=%s \"\n \"to see list of orders for this item.\" % (thing,))\n return\n self._getMtgoxQuote()\n L = [\"#%s %s %s %s %s %s @ %s %s (%s)\" % (id,\n time.ctime(refreshed_at),\n nick,\n buysell,\n amount,\n thing,\n self._getIndexedValue(price),\n otherthing,\n notes) \\\n for (id,\n created_at,\n refreshed_at,\n buysell,\n nick,\n host,\n amount,\n thing,\n price,\n otherthing,\n notes) in results]\n irc.replies(L, joiner=\" || \")", "def commit(self):\n for user_name, user in self._users.items():\n self._execute(\n \"UPDATE users \\\n SET credits = ? \\\n WHERE name == ?\",\n (user.credits, user_name)\n )\n for item_name, amount in user.items.items():\n self._execute(\n \"REPLACE INTO users_items VALUES (?, ?, ?)\",\n (user_name, item_name, amount)\n )", "def give_command(server, output, conf):\n args = output.args\n if len(args) == 2:\n # Default quantity\n target = args[0]\n item = args[1]\n qty = 1\n elif len(args) == 3:\n # Custom quantity\n target = args[0]\n item = args[1]\n qty = args[2]\n else:\n server.tell(output.name, 'Incorrect arguments')\n return\n\n item_id = get_item(item)\n if item_id is None:\n server.tell(output.name, 'Unknown item \"%s\"' % item)\n else:\n server.give(target, item_id, qty)\n\n return", "def inventory_db():\r\n \r\n config.parse_config()\r\n \r\n fake = Faker()\r\n dbname= '_'.join(['fakedb',\r\n fake.word(),\r\n fake.word(),\r\n fake.word(),\r\n ])\r\n \r\n config.cc.inventory.name = dbname\r\n \r\n # Create the database\r\n db= io_sql.sql_database()\r\n db.create_database(dbname)\r\n assert db.database_exists(dbname)\r\n del(db)\r\n \r\n print('Inventroy_db: ', dbname)\r\n \r\n # Pass the database to the test functions\r\n yield\r\n \r\n print('Done with inventory_db: ', dbname)\r\n \r\n # Delete the database after use\r\n db= io_sql.sql_database()\r\n db.delete_database(dbname)\r\n assert not db.database_exists(dbname)", "def do_command(self, args):\n chk_arg_count(args, 0)\n dbops.init_database()" ]
[ "0.5576415", "0.55608636", "0.547326", "0.54339856", "0.5421967", "0.5414153", "0.5369122", "0.5327051", "0.51939166", "0.5190003", "0.51846415", "0.51770884", "0.5095832", "0.50882393", "0.5086753", "0.5070294", "0.50603354", "0.5052992", "0.5031061", "0.5026271", "0.5021792", "0.49793154", "0.4977141", "0.4973407", "0.49621683", "0.4955625", "0.49543637", "0.49435842", "0.49363625", "0.49319592" ]
0.5756223
0
Prints debug message if verbosity is given
def debug(self, msg=""): if self.verbose: print("Debug: " + msg)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def debug(message: str) -> None:\n if is_verbose():\n print(message)\n else:\n sys.stdout.write(\".\")\n sys.stdout.flush()", "def ext_debug(self, message):\n for_verbosity = 4\n if self.verbosity_level >= for_verbosity:\n self.logger.debug(message)", "def __debugInfo(self, msg):\n\t\tif self.verbosity:\n\t\t\tprint(stylize(\"[*] DEBUG: {}\".format(msg), colored.fg(\"wheat_1\")))", "def printdebug(self, msg):\n if self.debug > 0:\n print(msg)", "def debug(self, message):\n for_verbosity = 3\n if self.verbosity_level >= for_verbosity:\n self.logger.debug(message)", "def debug(cls, message):\n if cls.verbose:\n print('[DEBUG] {0}'.format(message))", "def dprint(msg):\n if defaults.debug:\n print('debug: %s' % msg)", "def debug(string):\n if verbose:\n print string\n return", "def say(self, verbosity, msg):\n if self.verbosity >= verbosity:\n print(msg)", "def debug(message, output_no_verbose=False):\r\n global _quiet, _verbose\r\n if not _quiet and (output_no_verbose or _verbose):\r\n print(\"{0} - {1}\".format(datetime.datetime.now(), message))", "def debug(msg):\n if settings.DEBUG:\n print \"DEBUG: cli.%(msg)s\" % locals()", "def debug(self, msg):\n if self.ansible._debug or self.ansible._verbosity > 2:\n self.ansible.log(f'[DEBUG] {msg}')", "def debugLog(message):\n if debugFlag != None:\n print \"#debug: \" + str(message)", "def _debug_print(message):\n\n if _debug == True:\n print(message)", "def verbose_print(msg: str = '') -> None:\n assert isinstance(msg, str)\n if __verbose:\n print(msg)", "def print_debug(msg):\n if IS_DEBUG:\n print(msg)", "def d_action(option,opt_str,value,parser):\n cmdline_main.message(\"Enabling debugging message output.\")\n if hasattr(parameterized,'get_logger'):\n parameterized.get_logger().setLevel(parameterized.DEBUG)\n else: # For versions of the param package before 9 May 2013\n parameterized.min_print_level=parameterized.DEBUG", "def cli(debug):\n print(f\"Debug mode is {'on' if debug else 'off'}\")", "def debug(self, message):\r\n pass", "def d_print(msg):\n if (DEBUG == 1):\n print(msg)", "def debug(self, msg):\n if self._debug:\n print \"%s\" % (msg)", "def dprint(msg, debug):\n if debug:\n six.print_(msg)", "def printMessage(Message, verbosity):\n if(verbosity == 1):\n print(Message)", "def print_verbose(args, msg):\n if args.verbose:\n print(msg)", "def print_debug(self, message: str=\"\", src_file: str=\"\") -> None:\n if self._verbosity_level >= int(VerbosityLevel.VERBOSITY_LEVEL2):\n _mes = src_file + \": \" + message\n if self._print_statements_enabled:\n print(\"DEBUG \\t\\t- \", src_file + \": \\t\" + message)\n logging.debug(_mes)", "def verbosity(v):\n assert v in [0,1,2] # debug, warn, info\n GLOBAL['VERBOSITY'] = v", "def checkDebug(message):\n if debug == True:\n print(message)", "def check_and_print_debug_message(self, msg):\n if self._params.debug:\n print(\"Info: {}\".format(msg))", "def debug(msg):", "def debug(self, *args, **kwargs):\n self.msg(logging.DEBUG, *args, **kwargs)" ]
[ "0.7611738", "0.75555646", "0.75134826", "0.7447645", "0.74443406", "0.743769", "0.74119735", "0.73605067", "0.7323943", "0.7283614", "0.7250042", "0.7236865", "0.71943885", "0.71555024", "0.7141242", "0.7112227", "0.71070856", "0.708293", "0.70452696", "0.7045171", "0.7043726", "0.70435333", "0.7037378", "0.7032472", "0.7009594", "0.69692844", "0.6964271", "0.6940237", "0.6937423", "0.69252807" ]
0.78713787
0
This function is to update the db with listener stats
def update_stats(self, health_message): session = db_api.get_session() amphora_id = health_message['id'] listeners = health_message['listeners'] for listener_id, listener in listeners.items(): stats = listener.get('stats') stats = {'bytes_in': stats['rx'], 'bytes_out': stats['tx'], 'active_connections': stats['conns'], 'total_connections': stats['totconns'], 'request_errors': stats['ereq']} LOG.debug("Updating listener stats in db and sending event.") LOG.debug("Listener %s / Amphora %s stats: %s", listener_id, amphora_id, stats) self.listener_stats_repo.replace( session, listener_id, amphora_id, **stats) listener_stats = self.get_listener_stats(session, listener_id) self.emit( 'listener_stats', listener_id, listener_stats.get_stats()) listener_db = self.repo_listener.get(session, id=listener_id) lb_stats = self.get_loadbalancer_stats( session, listener_db.load_balancer_id) self.emit('loadbalancer_stats', listener_db.load_balancer_id, lb_stats.get_stats())
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def update_stats():\n list_db = get_list_database()\n\n list_db.group_stats_force_update()\n transaction_commit(None, 'GroupStatsUpdate')\n\n list_db.user_stats_force_update()\n transaction_commit(None, 'UserStatsUpdate')", "async def update_stats(self):\r\n\r\n\t\twhile True:\r\n\t\t\tlogging.info('Attempting to post server count')\r\n\t\t\ttry:\r\n\t\t\t\tawait self.dblpy.post_server_count()\r\n\t\t\t\tlogging.info(f'Posted server count ({len(self.bot.guilds)})')\r\n\t\t\texcept Exception as e:\r\n\t\t\t\tlogging.exception(f'Failed to post server count\\n{type(e).__name__}: {e}')\r\n\t\t\tawait asyncio.sleep(1800)", "def update_health(self, health):\n session = db_api.get_session()\n\n # We need to see if all of the listeners are reporting in\n expected_listener_count = 0\n lbs_on_amp = self.amphora_repo.get_all_lbs_on_amphora(session,\n health['id'])\n for lb in lbs_on_amp:\n listener_count = self.listener_repo.count(session,\n load_balancer_id=lb.id)\n expected_listener_count += listener_count\n\n listeners = health['listeners']\n\n # Do not update amphora health if the reporting listener count\n # does not match the expected listener count\n if len(listeners) == expected_listener_count:\n\n # if the input amphora is healthy, we update its db info\n self.amphora_health_repo.replace(session, health['id'],\n last_update=(datetime.\n datetime.utcnow()))\n else:\n LOG.warning('Amphora %(id)s health message reports %(found)i '\n 'listeners when %(expected)i expected',\n {'id': health['id'], 'found': len(listeners),\n 'expected': expected_listener_count})\n\n # We got a heartbeat so lb is healthy until proven otherwise\n lb_status = constants.ONLINE\n\n # update listener and nodes db information\n for listener_id, listener in listeners.items():\n\n listener_status = None\n # OPEN = HAProxy listener status nbconn < maxconn\n if listener.get('status') == constants.OPEN:\n listener_status = constants.ONLINE\n # FULL = HAProxy listener status not nbconn < maxconn\n elif listener.get('status') == constants.FULL:\n listener_status = constants.DEGRADED\n if lb_status == constants.ONLINE:\n lb_status = constants.DEGRADED\n else:\n LOG.warning(('Listener %(list)s reported status of '\n '%(status)s'), {'list': listener_id,\n 'status': listener.get('status')})\n\n try:\n if listener_status is not None:\n self._update_status_and_emit_event(\n session, self.listener_repo, constants.LISTENER,\n listener_id, listener_status\n )\n except sqlalchemy.orm.exc.NoResultFound:\n LOG.error(\"Listener %s is not in DB\", listener_id)\n\n pools = listener['pools']\n for pool_id, pool in pools.items():\n\n pool_status = None\n # UP = HAProxy backend has working or no servers\n if pool.get('status') == constants.UP:\n pool_status = constants.ONLINE\n # DOWN = HAProxy backend has no working servers\n elif pool.get('status') == constants.DOWN:\n pool_status = constants.ERROR\n lb_status = constants.ERROR\n else:\n LOG.warning(('Pool %(pool)s reported status of '\n '%(status)s'), {'pool': pool_id,\n 'status': pool.get('status')})\n\n members = pool['members']\n for member_id, status in members.items():\n\n member_status = None\n if status == constants.UP:\n member_status = constants.ONLINE\n elif status == constants.DOWN:\n member_status = constants.ERROR\n if pool_status == constants.ONLINE:\n pool_status = constants.DEGRADED\n if lb_status == constants.ONLINE:\n lb_status = constants.DEGRADED\n elif status == constants.NO_CHECK:\n member_status = constants.NO_MONITOR\n else:\n LOG.warning('Member %(mem)s reported status of '\n '%(status)s', {'mem': member_id,\n 'status': status})\n\n try:\n if member_status is not None:\n self._update_status_and_emit_event(\n session, self.member_repo, constants.MEMBER,\n member_id, member_status\n )\n except sqlalchemy.orm.exc.NoResultFound:\n LOG.error(\"Member %s is not able to update \"\n \"in DB\", member_id)\n\n try:\n if pool_status is not None:\n self._update_status_and_emit_event(\n session, self.pool_repo, constants.POOL,\n pool_id, pool_status\n )\n except sqlalchemy.orm.exc.NoResultFound:\n LOG.error(\"Pool %s is not in DB\", pool_id)\n\n # Update the load balancer status last\n # TODO(sbalukoff): This logic will need to be adjusted if we\n # start supporting multiple load balancers per amphora\n lb_id = self.amphora_repo.get(\n session, id=health['id']).load_balancer_id\n if lb_id is not None:\n try:\n self._update_status_and_emit_event(\n session, self.loadbalancer_repo,\n constants.LOADBALANCER, lb_id, lb_status\n )\n except sqlalchemy.orm.exc.NoResultFound:\n LOG.error(\"Load balancer %s is not in DB\", lb_id)", "def db_changed(self):\n self.dbstate.db.connect('person-add', self.update)\n self.dbstate.db.connect('person-delete', self.update)\n self.dbstate.db.connect('person-update', self.update)\n self.dbstate.db.connect('family-add', self.update)\n self.dbstate.db.connect('family-delete', self.update)\n self.dbstate.db.connect('family-update', self.update)", "def onUpdated(self):", "def update_server_stats(self):\n try:\n aio.run(self.client.execute, 'ANALYZE')\n except Exception:\n pass # swallow; CrateDB 4.1.0+ is required to run ANALYZE", "def update(self) -> None:\n self.app.notifier.set_value(\"Database update started on {}\".format(datetime.datetime.now().strftime(\"%c\")))\n self.app.notifier.clear()\n self.app.logger.info(\"Starting database update\")\n card_parser = JSonCardParser(self.app)\n card_parser.check_update()\n try:\n self.__update(card_parser)\n except mysql.connector.errors.ProgrammingError as exc:\n if exc.errno == mysql.connector.errorcode.ER_BAD_DB_ERROR:\n self.setup_db()\n self.__update(card_parser)\n else:\n raise\n else:\n self.app.logger.info(\"Finished database update\")\n self.app.notifier.set_value(\"Database update finished on {}\".format(datetime.datetime.now().strftime(\"%c\")))\n self.app.notifier.clear()", "def update_database(self) -> None:\n \n # Simulate that we update a database\n time.sleep(10)", "def dbUpdate():\n dbAddress = config.get('database', 'dbAddress')\n dbUser = config.get('database', 'dbUser')\n dbPassword = config.get('database', 'dbPassword')\n dbName = config.get('database', 'dbName')\n dbPort = config.getint('database', 'dbPort')\n con = MySQLdb.connect(host=dbAddress, port=dbPort, user=dbUser, passwd=dbPassword,\n db=dbName)\n c = con.cursor()\n\n date = datetime.datetime.now()\n c.execute(\"INSERT INTO sensor_data (date, dht_temp, dht_humidity, cpu_temp, \"\n \"solar_voltage, solar_current, battery_voltage, battery_current, \"\n \"load_voltage, load_current) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,\"\n \"%s)\",\n (date, dht_temp, dht_humidity, cpu_temp, sol_volt_v, sol_curr_ma,\n bat_volt_v, bat_curr_ma, load_volt_v, load_curr_ma))\n\n con.commit()\n con.close()", "async def update_stats(self, user, vote, click):\n \"\"\"Generally this function called from first page.\"\"\"\n # update server set\n # data =\n # jsonb_set(\n # jsonb_set(\n # data,\n # '{1}',\n # (select (((data->>1)::int+1)::text)::jsonb\n # from server limit 1)\n # ),\n # '{2}',\n # (select (((data->>2)::int+1)::text)::jsonb\n # from server limit 1)\n # )\n # where true;\n sql = (\"update server set\"\n \" data =\"\n \" jsonb_set(\"\n \" jsonb_set(\"\n \" jsonb_set(\"\n \" data,\"\n \" '{{1}}',\"\n \" (select (((data->>1)::int+{0})::text)::jsonb\"\n \" from server limit 1)\"\n \" ),\"\n \" '{{2}}',\"\n \" (select (((data->>2)::int+{1})::text)::jsonb\"\n \" from server limit 1)\"\n \" ),\"\n \" '{{3}}',\"\n \" (select (((data->>3)::int+{2})::text)::jsonb\"\n \" from server limit 1)\"\n \" )\")\n sql = sql.format(int(user), int(vote), int(click))\n await self.db.execute(sql)", "def update():", "def update():", "def update(self):\n self.getDbRecord().update()", "async def log_stats(self, stats_dict):\n\n cmd = \"PRAGMA table_info(trainer_stats)\"\n cur = self.sql.cur\n data = cur.execute(cmd).fetchall()\n valid_keys = []\n for entry in data:\n valid_keys.append(entry['name'])\n self.log.info(valid_keys)\n\n for key in stats_dict:\n if key not in valid_keys:\n raise ValueError()\n trainer_id = self.trainer_id\n for key in stats_dict:\n value = stats_dict[key]\n cmd = f\"\"\"UPDATE trainer_stats\n SET {key} = {key} + :value\n WHERE trainer_id = :trainer_id\"\"\"\n cur.execute(cmd, locals())\n await self.sql.commit(now=True)\n self.log.info(\"log completed\")", "def update( ):\r\n pass", "def periodicUpdate(self):\n try:\n logging.info(f'{self.cn} periodicUpdate = Start')\n isHaz = JsonSettings.parseJson('settings.json','isHazelcast')\n if self.db.isDb():\n self.insertStats()\n self.insertPorts()\n if isHaz:\n self.insertHaz() \n else:\n self.db.initDb()\n self.insertSys()\n self.insertStats()\n self.insertPorts()\n if isHaz:\n self.insertHaz() \n except Exception as e:\n logging.critical(f'{self.cn} Exception: {e}')\n logging.critical(f'{self.cn} StackTrace: \\n', exc_info=1)\n finally:\n logging.info(f'{self.cn} periodicUpdate = End')", "def _update_status(self):\n self._db_update({'status': self.status})", "def finish_translation_list_update():\n\n with _conn.cursor() as cur:\n cur.execute(\"ALTER TABLE translation_stats ENABLE TRIGGER update_translation_stats_timestamp;\")\n _conn.commit()", "def update_data():\n pass", "def update(self):\n\n if not self.db: self.validate()\n\n self.logging.debug( \"update(%s)\" % (self.db) )\n\n for name in self.tables:\n self.dbs_tables[name]['md5'] = get_md5( self.dbs_tables[name]['path'] )\n\n self._get_magnitudes()\n self._get_events()", "def update(self):\n\n self.stats = statistics.get()\n self.ticker = exchangerates.get_ticker()", "def update_all(self):\n self.update_head_node_ip()\n self.get_database_info()\n self.update_users()", "def at_server_reload(self):\n self.db.started = True", "def _add_background_updates(self) -> None:\n # Ugh, have to reset this flag\n self.store.db_pool.updates._all_done = False\n\n self.get_success(\n self.store.db_pool.simple_insert(\n \"background_updates\",\n {\n \"update_name\": \"populate_stats_process_rooms\",\n \"progress_json\": \"{}\",\n },\n )\n )\n self.get_success(\n self.store.db_pool.simple_insert(\n \"background_updates\",\n {\n \"update_name\": \"populate_stats_process_users\",\n \"progress_json\": \"{}\",\n \"depends_on\": \"populate_stats_process_rooms\",\n },\n )\n )", "def update(self):\n pass", "def update(self):\n pass", "def update(self):\n pass", "def update(self):\n pass", "def update(self):\n pass", "def update(self):\n pass" ]
[ "0.6679615", "0.64400375", "0.63026994", "0.6270449", "0.62358385", "0.6199205", "0.6033849", "0.6000455", "0.5929362", "0.5917533", "0.59089243", "0.59089243", "0.59047884", "0.58606374", "0.5841999", "0.57677644", "0.5690433", "0.5681239", "0.56774247", "0.5655227", "0.5647203", "0.56466633", "0.5626902", "0.56218195", "0.55885625", "0.55885625", "0.55885625", "0.55885625", "0.55885625", "0.55885625" ]
0.69017535
0
Creation of argument parser for the Seq2VAR experiments
def argument_parser_seq2var(): parser = argparse.ArgumentParser() parser.add_argument('--encoder-hidden', type=int, default=64, help='Number of hidden units.') parser.add_argument('--epochs', type=int, default=2000, help='Number of epochs to train.') parser.add_argument('--lr', action='store_true', default=5e-4, help='Learning rate.') parser.add_argument('--tau', type=int, default=0.5, help='Gumbel softmax temperature.') args, unknown = parser.parse_known_args() return args
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def setup_args():\n parser = ParlaiParser()\n parser.add_argument(\n '-n',\n '--num-episodes',\n default=-1,\n type=int,\n help='Total number of episodes to convert, -1 to convert all examples',\n )\n parser.add_argument(\n '-of',\n '--outfile',\n default=None,\n type=str,\n help='Output file where to save, by default will be created in /tmp',\n )\n parser.add_argument(\n '-s1id', '--speaker-0-id', type=str, help='Speaker id of agent who speaks first'\n )\n parser.add_argument(\n '-s1id',\n '--speaker-1-id',\n type=str,\n help='Speaker id of agent who speaks second',\n )\n parser.add_argument(\n '--prepended-context',\n type='bool',\n default=False,\n help='specify if the context is prepended to the first act',\n )\n parser.add_argument('-ltim', '--log-every-n-secs', type=float, default=10)\n parser.set_defaults(datatype='train:ordered')\n\n return parser", "def Args(parser):", "def parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('--v2g_slice', metavar=\"<file>\", type=str, required=True)\n parser.add_argument('--varid', metavar=\"<file>\", type=str)\n parser.add_argument('--outpref', metavar=\"<str>\", help='Output prefix', type=str, required=True)\n args = parser.parse_args()\n return args", "def _setup_parser():\n parser = argparse.ArgumentParser(add_help=True)\n parser.add_argument('--eval_model', type=str, default=None)\n parser.add_argument('--stack', type=int, default=1)\n parser.add_argument('--flare', action='store_true')\n parser.add_argument('--mixreg', action='store_true')\n\n env_group = parser.add_argument_group(\"Env Args\")\n env_group.add_argument('--env_name', type=str, default=ENV_NAME)\n env_group.add_argument('--num_envs', type=int, default=NUM_ENVS)\n env_group.add_argument('--num_levels', type=int, default=NUM_LEVELS)\n env_group.add_argument('--start_level', type=int, default=START_LEVEL)\n\n agent_group = parser.add_argument_group(\"Agent Args\")\n PPOAgent.add_to_argparse(agent_group)\n\n model_group = parser.add_argument_group(\"Model Args\")\n ImpalaPPO.add_to_argparse(model_group)\n\n return parser", "def build_parser(self, parser: ArgumentParser) -> None:", "def _init_parser():\n\t\n\t_parser = argparse.ArgumentParser()\n\t_parser.add_argument(\"--pull\", help=\"pull scripts from UR3\", action=\"store_true\")\n\t_parser.add_argument(\"--create\", help=\"create data base from script files\", action=\"store_true\")\n\t_parser.add_argument(\"--clear\", help=\"clear all data base\", action=\"store_true\")\n\treturn _parser", "def parse_cmd_line_args():\n\n parser = argparse.ArgumentParser(\n description='Run FEM-BV-VARX on system with periodic time-dependence')\n\n parser.add_argument('--n-components', dest='n_components', type=int,\n default=2, help='number of FEM-BV-VARX components')\n parser.add_argument('--n-init', dest='n_init', type=int, default=10,\n help='number of initializations to try')\n parser.add_argument('--max-tv-norm', dest='max_tv_norm', type=float,\n default=None, help='maximum TV norm bound')\n parser.add_argument('--memory', dest='memory', type=int, default=1,\n help='maximum memory in FEM-BV-VARX models')\n parser.add_argument('--tolerance', dest='tolerance', type=float,\n default=1e-4, help='convergence tolerance')\n parser.add_argument('--max-iterations', dest='max_iterations', type=int,\n default=500, help='maximum number of iterations')\n parser.add_argument('--n-features', dest='n_features', type=int, default=2,\n help='dimensionality of data')\n parser.add_argument('--n-samples', dest='n_samples', type=int, default=500,\n help='length of time-series')\n parser.add_argument('--period', dest='period', type=float, default=10,\n help='period of time-dependent parameters')\n parser.add_argument('--order', dest='order', type=int, default=1,\n help='order of AR process to generate data with')\n parser.add_argument('--noise-variance', dest='noise_variance', type=float,\n default=1.0, help='magnitude of noise variance')\n parser.add_argument('--random-seed', dest='random_seed', type=int, default=0,\n help='random seed')\n parser.add_argument('--plot-data', dest='plot_data', action='store_true',\n help='plot time-series of initial data')\n parser.add_argument('--plot-weights', dest='plot_weights', action='store_true',\n help='plot FEM-BV-VARX weights')\n parser.add_argument('--verbose', dest='verbose', action='store_true',\n help='produce verbose output')\n\n args = parser.parse_args()\n\n if args.n_components < 1:\n raise ValueError('Number of components must be at least 1')\n\n if args.n_init < 1:\n raise ValueError('Number of initializations must be at least 1')\n\n if args.max_tv_norm is not None and args.max_tv_norm < 0:\n raise ValueError('Maximum TV norm bound must be non-negative')\n\n if args.memory < 0:\n raise ValueError('FEM-BV-VARX memory must be non-negative')\n\n if args.tolerance <= 0:\n raise ValueError('Convergence tolerance must be positive')\n\n if args.max_iterations < 1:\n raise ValueError('Maximum number of iterations must be at least 1')\n\n if args.n_features < 1:\n raise ValueError('Number of data features must be at least 1')\n\n if args.n_samples < 1:\n raise ValueError('Number of samples must be at least 1')\n\n if args.period <= 0:\n raise ValueError('Period must be positive')\n\n if args.order < 0:\n raise ValueError('Order of generating process must be non-negative')\n\n if args.noise_variance <= 0:\n raise ValueError('Noise variance must be positive')\n\n return args", "def init_argparser() -> ArgumentParser:\n parser = ArgumentParser()\n from_config = parser.add_argument_group('From config file', 'Provide full experiment setup via config file')\n from_config.add_argument('-c', '--config', help='Path to json file containing classification config.')\n from_cmd = parser.add_argument_group('From commandline', 'Specify experiment setup via commandline arguments')\n\n # Model options\n from_cmd.add_argument(\"--recoding_type\", type=str, default=None,\n choices=[\"mc_dropout\", \"surprisal\", \"ensemble\"],\n help=\"Recoding model type used for trainign. Choices include recoding based on MC Dropout,\"\n \"perplexity and anchored ensembles. If not specified, a vanilla model without recoding\"\n \"is used.\")\n from_cmd.add_argument(\"--step_type\", type=str, default=None, choices=[\"fixed\", \"mlp\", \"learned\"],\n help=\"Specifies the way the step size is determined when using a recoding model.\")\n from_cmd.add_argument(\"--step_size\", type=float,\n help=\"Step size for recoding in case the fixed step predictor is used.\")\n from_cmd.add_argument(\"--embedding_size\", type=int, help=\"Dimensionality of word embeddings.\")\n from_cmd.add_argument(\"--hidden_size\", type=int, help=\"Dimensionality of hidden states.\")\n from_cmd.add_argument(\"--num_layers\", type=int, help=\"Number of network layers.\")\n from_cmd.add_argument(\"--mc_dropout\", type=float, help=\"Dropout probability when estimating uncertainty.\")\n from_cmd.add_argument(\"--dropout\", type=float, help=\"Dropout probability for model in general.\")\n from_cmd.add_argument(\"--num_samples\", type=int, help=\"Number of samples used when estimating uncertainty.\")\n\n # Training options\n from_cmd.add_argument(\"--weight_decay\", type=float, help=\"Weight decay parameter when estimating uncertainty.\")\n from_cmd.add_argument(\"--prior_scale\", type=float,\n help=\"Prior length scale. A lower scale signifies a prior belief that the input data is \"\n \"distributed infrequently, a higher scale does the opposite.\")\n from_cmd.add_argument(\"--learning_rate\", type=float, help=\"Learning rate during training.\")\n from_cmd.add_argument(\"--batch_size\", type=int, help=\"Batch size during training.\")\n from_cmd.add_argument(\"--num_epochs\", type=int, help=\"Number of training epochs.\")\n from_cmd.add_argument(\"--clip\", type=float, help=\"Threshold for gradient clipping.\")\n\n # Corpus options\n from_cmd.add_argument(\"--corpus_dir\", type=str, help=\"Directory to corpus files.\")\n from_cmd.add_argument(\"--max_seq_len\", type=int, help=\"Maximum sentence length when reading in the corpora.\")\n\n # Screen output optins\n from_cmd.add_argument(\"--print_every\", type=int, help=\"Batch interval at which training info should be printed.\")\n from_cmd.add_argument(\"--eval_every\", type=int,\n help=\"Epoch interval at which the model should be evaluated on validation set.\")\n\n # Model saving and logging options\n from_cmd.add_argument(\"--model_name\", type=str, help=\"Model identifier.\")\n from_cmd.add_argument(\"--model_save_path\", type=str,\n help=\"Directory to which current best model should be saved to.\")\n from_cmd.add_argument(\"--device\", type=str, default=\"cpu\", help=\"Device used for training.\")\n from_cmd.add_argument(\"--log_dir\", type=str, help=\"Directory to write (tensorboard) logs to.\")\n\n return parser", "def setup_parser():\n PARSER = argparse.ArgumentParser(description='Running GSI')\n\n PARSER.add_argument('analysis_datetime', type=str, help=\"analysis_datetime\")\n PARSER.add_argument('gsi_dir', type=str, help=\"gsi_dir\")\n PARSER.add_argument('gsi_processor', type=int, help=\"gsi_processor\")\n PARSER.add_argument('cycle_interval', type=int, help=\"cycle_interval\")\n PARSER.add_argument('model_vertical_level', type=int, help=\"model_vertical_level\")\n PARSER.add_argument('background_data', type=str, help=\"background_data\")\n PARSER.add_argument('crtm_root', type=str, help=\"crtm_root\")\n PARSER.add_argument('gsi_root', type=str, help=\"gsi_root\")\n \n PARSER.add_argument('--f_prepbufr', type=str, dest=\"f_prepbufr\", default='')\n PARSER.add_argument('--f_1bamua', type=str, dest=\"f_1bamua\", default='')\n PARSER.add_argument('--f_1bhrs4', type=str, dest=\"f_1bhrs4\", default='')\n PARSER.add_argument('--f_1bmhs', type=str, dest=\"f_1bmhs\", default='')\n PARSER.add_argument('--f_gpsro', type=str, dest=\"f_gpsro\", default='')\n PARSER.add_argument('--f_radwnd', type=str, dest=\"f_radwnd\", default='')\n PARSER.add_argument('--f_refInGSI', type=str, dest=\"f_refInGSI\", default='')\n PARSER.add_argument('--model_core', type=str, dest=\"model_core\", default='ARW')\n PARSER.add_argument('--cv_option', type=str, dest=\"cv_option\", default='NAM')\n PARSER.add_argument('--computing_platform', type=str, dest=\"computing_platform\", default='LINUX_PBS')\n PARSER.add_argument('--new_run', type=str, dest=\"new_run\", default='True')\n PARSER.add_argument('--outer_loop', type=int, dest=\"outer_loop\", default=2)\n PARSER.add_argument('--inner_loop', type=int, dest=\"inner_loop\", default=50)\n PARSER.add_argument('--if_clean', type=str, dest=\"if_clean\", default='no')\n\n '''\n python Main_Script.py 2017082112 /mnt/WRF/gsi_test/practice_11 4 1 50 /mnt/WRF/wrf_1FMTHf/wrfinput_d01 /opt/miniconda2/envs/wrf/crtm-2.2.3/CRTM_2.2.3 /opt/miniconda2/envs/wrf/comGSIv3.5_EnKFv1.1 --f_prepbufr /opt/miniconda2/envs/wrf/bufr_stuff/bin/test.bufr\n return PARSER.parse_args(['2017082112', '/home/szhang/gsi_directory/practice_10', \n 4, 1, 50,\n '/home/szhang/gsi_directory/practice_10/background_data', \n '/home/szhang/gsi_directory/practice_10/crtm_root', \n '/home/szhang/gsi_directory/practice_10/gsi_root', \n '--f_prepbufr', '/home/szhang/gsi_directory/practice_10/f_prepbufr'])\n '''\n return PARSER.parse_args()", "def parse_args():\n global Args\n parser = argparse.ArgumentParser()\n subparsers = parser.add_subparsers()\n pars_simulation(subparsers)\n pars_analyze(subparsers)\n Args = parser.parse_args()", "def robotics_arg_parser():\n parser = arg_parser()\n parser.add_argument('--env', help='environment ID', type=str, default='FetchReach-v0')\n parser.add_argument('--seed', help='RNG seed', type=int, default=0)\n parser.add_argument('--num-timesteps', type=int, default=int(1e6))\n return parser", "def define_parser():\n parser = argparse.ArgumentParser(\n description=\"Training a DQN agent on the Simulink Cartpole environment\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n )\n parser.add_argument(\n \"-b\",\n \"--batch_size\",\n metavar=\"batch_size\",\n type=int,\n default=32,\n help=\"Minibatch size for gradient update\",\n )\n parser.add_argument(\n \"-B\",\n \"--benchmark\",\n action=\"store_true\",\n help=\"Flag for training in Gym implementation CartPole-v1\",\n )\n parser.add_argument(\n \"-d\",\n \"--log_dir\",\n metavar=\"log_dir\",\n type=str,\n default=\"./logs\",\n help=\"Path for logs and optional saved policy\",\n )\n parser.add_argument(\n \"-e\",\n \"--epsilon_0\",\n metavar=\"epsilon_0\",\n type=float,\n default=1.0,\n help=\"Initial epsilon value\",\n )\n parser.add_argument(\n \"-f\",\n \"--train_freq\",\n metavar=\"train_freq\",\n type=int,\n default=1,\n help=\"Times to train per episode\",\n )\n parser.add_argument(\n \"-g\",\n \"--gamma\",\n metavar=\"discount_factor\",\n type=float,\n default=0.99,\n help=\"Discount factor of the Bellman update\",\n )\n parser.add_argument(\n \"-l\",\n \"--learning_rate\",\n metavar=\"learning_rate\",\n type=float,\n default=1e-4,\n help=\"Learning rate\",\n )\n parser.add_argument(\n \"-m\",\n \"--eps_min\",\n metavar=\"epsilon_min\",\n type=float,\n default=0.05,\n help=\"Minimum epsilon value\",\n )\n parser.add_argument(\n \"-p\",\n \"--exploration_fraction\",\n metavar=\"exploration_fraction\",\n type=float,\n default=0.1,\n help=(\n \"Fraction of entire training period over which the exploration rate \"\n \"is reduced\"\n ),\n )\n parser.add_argument(\n \"-r\",\n \"--buffer_size\",\n metavar=\"buffer_size\",\n type=int,\n default=10000,\n help=\"Size of replay buffer\",\n )\n parser.add_argument(\n \"-s\",\n \"--save_policy\",\n action=\"store_true\",\n help=\"Flag for saving the trained policy\",\n )\n parser.add_argument(\n \"-S\",\n \"--gradient_steps\",\n metavar=\"gradient_steps\",\n type=int,\n default=1,\n help=\"How many gradient steps to do after each rollout\",\n )\n parser.add_argument(\n \"-t\",\n \"--total_timesteps\",\n metavar=\"total_timesteps\",\n type=int,\n default=500000,\n help=\"Number of total timesteps to train\",\n )\n parser.add_argument(\n \"-T\",\n \"--tau\",\n metavar=\"tau\",\n type=float,\n default=1.0,\n help=\"Soft update coefficient (Polyak update), 1.0 for hard update\",\n )\n parser.add_argument(\n \"-u\",\n \"--update_interval\",\n metavar=\"update_interval\",\n type=int,\n default=5000,\n help=\"Timesteps between update of target network\",\n )\n parser.add_argument(\n \"-v\",\n \"--verbose\",\n metavar=\"verbose\",\n type=int,\n default=0,\n help=(\n \"Verbosity level: 0 for no output, 1 for info messages \"\n \"(such as device or wrappers used), 2 for debug messages\"\n ),\n )\n parser.add_argument(\n \"-w\",\n \"--wandb\",\n action=\"store_true\",\n help=\"Flag indicating the use of wandb (Weights & Biases)\",\n )\n parser.add_argument(\n \"-x\",\n \"--min_exp\",\n metavar=\"min_experiences\",\n type=int,\n default=5000,\n help=\"Minimum experiences in buffer to start with training\",\n )\n\n return parser", "def atari_arg_parser():\n parser = arg_parser()\n parser.add_argument('--env', help='environment ID', default='BreakoutNoFrameskip-v4')\n parser.add_argument('--seed', help='RNG seed', type=int, default=0)\n parser.add_argument('--num-timesteps', type=int, default=int(10e6))\n return parser", "def argParse():\n p = ap.ArgumentParser()\n p.add_argument('field',\n help='Name of field')\n p.add_argument('telescope',\n help='Name of telescope',\n choices=['io', 'callisto', 'europa',\n 'ganymede', 'artemis', 'saintex',\n 'nites', 'rcos20'])\n p.add_argument('filt',\n help='Name of filter')\n return p.parse_args()", "def setup_parser(parser):\n\n parser.add_argument('input', metavar='INPUT', type=str, nargs='*',\n help='read tracking result from file named INPUT')\n parser.add_argument('-x', nargs = 2, type=int, help='x-range')\n parser.add_argument('-y', nargs = 2, type=int, help='y-range')\n parser.add_argument('-t', nargs = 2, type=int, help='t-range')\n parser.add_argument('--count', type = int, default = 0, \n help = 'target number of observation per chunk')\n parser.add_argument('--apron', type = int, default = 4, \n help = 'size of the chunk overlap')", "def build_parser():\n def commaSplitter(str):\n \"\"\"\n Argparse a comm-seperated list\n \"\"\"\n # leave this here as a reminder of what I should do to make the argument parsing more robust\n\n # if sqrt != int(sqrt):\n # msg = \"%r is not a perfect square\" % string\n # raise argparse.ArgumentTypeError(msg)\n # return value\n return str.split(',')\n\n def existing_file(fname):\n \"\"\"\n Argparse type for an existing file\n \"\"\"\n if not os.path.isfile(fname):\n raise ValueError(\"Invalid file: \" + str(fname))\n return fname\n\n parser = argparse.ArgumentParser(description=__doc__)\n\n parser.add_argument('-p', '--prefix', help='dont really know what this does...',\n action='store', default='patient', dest='prefix')\n parser.add_argument('-d', '--date', help='dont really know what this does...',\n action='store', default='', dest='sampledate')\n parser.add_argument('template', type=argparse.FileType('r'), help='BEAST config template file')\n parser.add_argument('fasta', type=argparse.FileType('r'), help='file of sequences (in FASTA format)')\n\n return parser", "def make_parser():\n p = argparse.ArgumentParser(\n description=\"Visualize and analyze error from oblique/straight tag observations\"\n )\n\n p.add_argument(\"-n\", help=\"name of the test in the config file\")\n\n p.add_argument(\"-t\", help=\"throw out bad tags\", action=\"store_true\")\n\n p.add_argument(\"-v\", help=\"visualize data\", action=\"store_true\")\n\n p.add_argument(\"-i\", help=\"print result data\", action=\"store_true\")\n\n return p", "def build_parser():\n parser = argparse.ArgumentParser()\n parser.add_argument('-r', '--reference', required=True, help=\"Reference Genome URL\")\n parser.add_argument('-n', '--normal', required=True, help='Normal BAM URL. Format: UUID.normal.bam')\n parser.add_argument('-t', '--tumor', required=True, help='Tumor BAM URL. Format: UUID.tumor.bam')\n parser.add_argument('-d', '--dbsnp', required=True, help='dbsnp_132_b37.leftAligned.vcf URL')\n parser.add_argument('-c', '--cosmic', required=True, help='b37_cosmic_v54_120711.vcf URL')\n parser.add_argument('-u', '--mutect', required=True, help='Mutect.jar')\n parser.add_argument('-w', '--work_dir', required=True, help='Where you wanna work from? (full path please)')\n\n return parser", "def create_parser():\n parser = argparse.ArgumentParser(\n description=\"First example\",\n epilog=\"Batch 2017\")\n\n # script\n parser.add_argument('--script',\n required=True,\n action='store',\n dest='script',\n help=\"A script to execute\")\n\n parser.add_argument('--dataset',\n required=True,\n action='store',\n dest='dataset',\n help=\"A dataset to use\")\n#\n# parser.add_argument('--features',\n# required=True,\n# action='store',\n# dest='features',\n# help=\"Number of features\")\n return parser", "def create_parser():\n p = NewParser()\n\n p.add_argument('reference', type=str,\n help = \"Fasta reference file that reads were mapped to.\")\n\n p.add_argument('gff', type=str,\n help = \"GFF file containing reference genome annotations.\")\n\n p.add_argument('vcf', type=str,\n help = \"VCF file to parse.\")\n\n args = p.parse_args(sys.argv[1:])\n return args", "def cmdline_parser():\n\n # http://docs.python.org/dev/howto/argparse.html\n parser = argparse.ArgumentParser(description=__doc__)\n \n parser.add_argument(\"--verbose\",\n action=\"store_true\",\n help=\"Be verbose\")\n parser.add_argument(\"--debug\",\n action=\"store_true\",\n help=\"Enable debugging\")\n parser.add_argument(\"-b\", \"--bam\",\n required=True,\n help=\"Input BAM file matching vcf\")\n parser.add_argument(\"-i\", \"--vcf\",\n help=\"Input VCF file containing variants to analyze\"\n \" (clashes with --var)\")\n parser.add_argument(\"-v\", \"--var\",\n help=\"Report reads for this variant only. Format: chr:pos:ref-alt\"\n \" (clashes with --vcf)\")\n default = 0\n parser.add_argument(\"--mq-filter\",\n dest=\"min_mq\",\n type=int,\n default=default,\n help=\"Ignore reads with mapping quality below this value (default=%d)\" % default)\n default = 5\n parser.add_argument(\"--bq-filter\",\n dest=\"min_bq\",\n type=int,\n default=default,\n help=\"Ignore reads with bases below this value (default=%d)\" % default)\n parser.add_argument(\"-a\", \"--use-orphan\",\n action=\"store_true\",\n help=\"Don't ignore orphan-reads / anomalous read-pairs\")\n\n return parser", "def make_parser():\n\n parser = argparse.ArgumentParser(description='Inference engine.')\n subparsers = parser.add_subparsers(dest=\"subcommand\")\n subparsers.required = True\n solver_subparser = subparsers.add_parser('run')\n solver_subparser.add_argument(\n '-v', '--verbose', help='enable verbose mode.', action='store_true'\n )\n solver_subparser.add_argument(\n '-d', '--debug', help='enable debug mode.', action='store_true'\n )\n solver_subparser.add_argument(\n 'filename', type=str,\n help='filename containing the instructions to process.'\n )\n return parser", "def create_parser():\n parser = argparse.ArgumentParser(\n \"DomainTransfer\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n conflict_handler=\"resolve\",\n )\n args, _ = parser.parse_known_args()\n\n # environment\n parser.add_argument(\"--source_env\", type=str, default=\"SawyerPush-v0\")\n parser.add_argument(\"--source_noise_bias\", type=float, default=0.0)\n parser.add_argument(\"--source_noise_level\", type=float, default=0.0)\n parser.add_argument(\"--source_ob_noise_level\", type=float, default=0.0)\n\n parser.add_argument(\"--target_env\", type=str, default=\"SawyerPush-v0\")\n parser.add_argument(\"--target_noise_bias\", type=float, default=0.0)\n parser.add_argument(\"--target_noise_level\", type=float, default=0.0)\n parser.add_argument(\"--target_ob_noise_level\", type=float, default=0.0)\n\n parser.add_argument(\"--envs\", type=str2list, default=[])\n parser.add_argument(\"--eval_ckpt_paths\", type=str2list, default=[])\n parser.add_argument(\"--early_term\", type=str2bool, default=False)\n\n parser.add_argument(\"--seed\", type=int, default=123)\n\n add_env_args(parser)\n\n add_method_arguments(parser)\n\n return parser", "def _init_argparser():\n desc = 'SES status and metrics reporting utility (part of sasutils).'\n parser = argparse.ArgumentParser(description=desc)\n parser.add_argument('-d', '--debug', action=\"store_true\",\n help='enable debugging')\n\n group = parser.add_mutually_exclusive_group(required=True)\n group.add_argument('-c', '--carbon', action='store_true',\n help='output SES Element descriptors metrics in a '\n 'format suitable for Carbon/Graphite')\n group.add_argument('-s', '--status', action='store_true',\n help='output status found in SES Element descriptors')\n\n group = parser.add_argument_group('output options')\n group.add_argument('--prefix', action='store',\n default='sasutils.ses_report',\n help='carbon prefix (example: \"datacenter.cluster\",'\n ' default is \"sasutils.ses_report\")')\n group.add_argument('-j', '--json', action='store_true',\n help='alternative JSON output mode')\n return parser.parse_args()", "def make_parser():\n\n parser = ArgumentParser(description=\"Create dummy sensor stream esque data\")\n parser.add_argument('--tuples-per-emit', '-t', type=int, default=1,\n help='number of tuples to emit at once')\n parser.add_argument('--sensors', '-s', type=int, default=1,\n help='number of sensors to generate')\n\n return parser", "def generate_parser():\n description = \"%(prog)s -- Predict RNA expression from cCREs and Ideas states\"\n parser = argparse.ArgumentParser(description=description)\n parser.add_argument('-r', '--rna', dest=\"rna\", type=str, action='store', required=True,\n help=\"RNA expression file\")\n parser.add_argument('-s', '--state', dest=\"state\", type=str, action='store', required=True,\n help=\"State file\")\n parser.add_argument('-c', '--cre', dest=\"cre\", type=str, action='store', required=True,\n help=\"CRE file\")\n parser.add_argument('-l', '--lessone', dest=\"lessone\", type=int, action='store', default=0,\n help=\"Cell type to leave out\")\n parser.add_argument('-o', '--output', dest=\"output\", type=str, action='store', default='./out',\n help=\"Output prefix\")\n parser.add_argument('-i', '--iterations', dest=\"iterations\", type=int, action='store', default=100,\n help=\"Refinement iterations\")\n parser.add_argument('-t', '--threads', dest=\"threads\", type=int, action='store', default=1,\n help=\"Number of threads to use\")\n parser.add_argument('--initialization-dist', dest=\"init_dist\", type=int, action='store', default=1000,\n help=\"Beta initialization distance cutoff\")\n parser.add_argument('--promoter-dist', dest=\"promoter_dist\", type=int, action='store',\n help=\"If specified, learn betas for promoters up to promoter distance cutoff\")\n parser.add_argument('--cre-dist', dest=\"cre_dist\", type=int, action='store',\n help=\"CRE distance cutoff\")\n parser.add_argument('--cre-exclude-promoter', dest=\"cre_noprom\", action='store_true',\n help=\"Exclude promoter from CREs\")\n parser.add_argument('--sum-cres', dest=\"sum_cres\", action='store_true',\n help=\"Sum CREs instead of finding overall proportions\")\n parser.add_argument('--correlation', dest=\"correlation\", type=float, action='store', default=0.0,\n help=\"Initial correlation cutoff\")\n parser.add_argument('--pca', dest=\"pca\", type=float, action='store',\n help=\"Convert state ratios into PCAs explaining this much variance\")\n parser.add_argument('--trainstats', dest=\"train_stats\", action='store_true',\n help=\"Output training statistics\")\n parser.add_argument('--max-CREs', dest=\"max_cres\", action='store', type=int, default=0,\n help=\"Maximum number of CREs allowed to be selected per TSS at a time (0 is no max)\")\n parser.add_argument('--skip-training', dest=\"skip_training\", action='store_true',\n help=\"Skip CRE-TSS pairining refinement\")\n parser.add_argument('--shuffle-states', dest=\"shuffle_states\", action='store_true',\n help=\"Shuffle the state proportions of each CRE as a negative control\")\n parser.add_argument('-e', '--eRP', dest=\"eRP\", action='store', type=str,\n help=\"A previously generated eRP TSS-cCRE pair file. Passing this will ignore initial TSS-CRE pair selection\")\n parser.add_argument('--seed', dest=\"seed\", action='store', type=int,\n help=\"Random number generator state seed\")\n parser.add_argument('-v', '--verbose', dest=\"verbose\", action='store', type=int, default=2,\n help=\"Verbosity level\")\n return parser", "def setup_parser(self, parser, args):\r\n\r\n pass", "def setup_parser(self):\n parser = argparse.ArgumentParser(description=DESCRIPTION)\n parser.add_argument('words', metavar='W', nargs='+', help=POSITIONAL_HELP)\n parser.add_argument('-a','--any', dest=\"search_funct\", action=\"store_const\", \n const='any', default='all', help=SEARCH_HELP)\n parser.add_argument('-o','--only-id', action='store_true', help=ID_HELP)\n parser.add_argument('-u', '--update', action='store_true', help=UPDATE_HELP)\n return parser", "def build_arg_parser():\n\n main = ArgumentParser(description='AMFinder command-line arguments.',\n allow_abbrev=False,\n formatter_class=RawTextHelpFormatter)\n\n subparsers = main.add_subparsers(dest='run_mode', required=True,\n help='action to be performed.')\n\n _ = training_subparser(subparsers)\n _ = prediction_subparser(subparsers)\n _ = diagnostic_subparser(subparsers)\n\n return main", "def setup_parser():\n\n psr_desc=\"cfdi engine service interface\"\n psr_epi=\"select a config profile to specify defaults\"\n\n psr = argparse.ArgumentParser(\n description=psr_desc, epilog=psr_epi)\n\n psr.add_argument('-nmp', action='store_true', dest='nmp',\n help='unique process approach (useful in development)')\n\n psr.add_argument('-d', action='store_true', dest='debug',\n help='print debug information')\n\n psr.add_argument('-c', '--config', action='store',\n dest='config',\n help='load an specific config profile')\n\n psr.add_argument('-p', '--port', action='store',\n dest='port',\n help='launches service on specific port')\n\n return psr.parse_args()" ]
[ "0.6938465", "0.6919866", "0.6897542", "0.68405354", "0.6777029", "0.6741335", "0.6723699", "0.67178744", "0.6689901", "0.66441715", "0.66422004", "0.66412914", "0.6636828", "0.6636687", "0.66294044", "0.66255265", "0.66222453", "0.6601116", "0.65829134", "0.6547027", "0.65347916", "0.65209603", "0.65205616", "0.6517842", "0.6511035", "0.6502461", "0.6501715", "0.6497543", "0.64952457", "0.6475847" ]
0.7822685
0
Bind input ports to external output ports or source data. Positional arguments map to input ports numbered as '0', '1', etc. Keyword arguments set inputs by name. Argument values can either
def set_input(self, *arg, **kw): # Convert arguments into keyword arguments for i, a in enumerate(arg): kw[str(i)] = a for name, value in six.iteritems(kw): if name not in self._inputs: raise ValueError("Invalid port name '{0}'".format(name)) if isinstance(value, Port): port = value else: port = Task.create_source(value).get_output() port.connect(self._inputs[name]) self._dirty = True return self
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def modify_ports(self, ports, **kwargs):\n pass", "def __init__(self, *arg, **kw):\n #: Input connection mapping\n self._inputs = {}\n for name, port in six.iteritems(self.input_ports):\n self._inputs[name] = port(self, name=name)\n\n #: Output connection mapping\n self._outputs = {}\n for name, port in six.iteritems(self.output_ports):\n self._outputs[name] = port(self, name=name)\n\n #: data cache\n self._output_data = {}", "def cmd_port(args):", "def modify_rstp_ports(self, ports, **kwargs):\n pass", "def run(self, *arg, **kw):\n self.dirty = False\n for port in self.inputs:\n self.get_input_data(port)", "def __init__(__self__, *,\n from_port: pulumi.Input[int],\n to_port: pulumi.Input[int]):\n pulumi.set(__self__, \"from_port\", from_port)\n pulumi.set(__self__, \"to_port\", to_port)", "def __call__(self, *args, **kwargs) -> tp.Union[None, Port, tp.Tuple[Port]]:\n from blox_old.block.base.port_section import BlockPortsSection\n\n # Handle the case when In and Out are passed without ()\n args = list(chain(*map(lambda arg: [arg] if not isinstance(arg, BlockPortsSection) else arg, args)))\n\n if len(args) + len(kwargs) > len(self.In):\n raise BlockError(f\"Too many inputs provided, expected at most: {len(self.In)}, \"\n f\"given: {len(args) + len(kwargs)}\")\n\n for port_name, src in chain(zip(self.In.keys(), args), kwargs.items()):\n self.In[port_name] = src\n\n # Return the output ports\n return self.Out()", "def ports(self, ports):\n\n self._ports = ports", "def AssignPorts(self, *args, **kwargs):\n # type: (*Any, **Any) -> Union[List[str], None]\n payload = {}\n for i in range(len(args)):\n payload[\"Arg%s\" % (i + 1)] = args[i]\n for item in kwargs.items():\n payload[item[0]] = item[1]\n return self._execute(\"assignPorts\", payload=payload, response_object=None)", "def _bindlist(input_str):\n try:\n ip_port = input_str.split(':')\n if len(ip_port) == 1:\n _ip = ip_port[0]\n _port = None\n else:\n (_ip, _port) = ip_port\n if not _ip and not _port:\n raise AssertionError\n elif not _port:\n _port = '22' # default port if not given\n return _ip, int(_port)\n except ValueError:\n raise argparse.ArgumentTypeError(\n 'Address tuple must be of type IP_ADDRESS:PORT'\n )\n except AssertionError:\n raise argparse.ArgumentTypeError(\"Both IP:PORT can't be missing!\")", "def AssignPorts(self, *args, **kwargs):\n # type: (*Any, **Any) -> Union[List[str], None]\n payload = { \"Arg1\": self }\n for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i]\n for item in kwargs.items(): payload[item[0]] = item[1]\n return self._execute('assignPorts', payload=payload, response_object=None)", "def ConnectPorts(self, *args, **kwargs):\n # type: (*Any, **Any) -> None\n payload = { \"Arg1\": self }\n for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i]\n for item in kwargs.items(): payload[item[0]] = item[1]\n return self._execute('connectPorts', payload=payload, response_object=None)", "def make_external_ports(self, ports):\n\n self._set_unconnected_ports()\n for ip_name, _ports in ports.items():\n for _port in _ports:\n self._set_port(self._ips[ip_name], _port)", "def configure_dcbx_app(self, ports, **kwargs):\n pass", "def bind_acl_to_ports(self, acl_name=None, ports=None):\n pass", "def connect_ports(self, port1_name: str, ip1_name: str,\n port2_name: str, ip2_name: str):\n if (ip1_name not in self._ips.keys() or\n ip2_name not in self._ips.keys()):\n raise ValueError(\n f'No such IP in this module: {ip1_name}, {ip2_name}.'\n ' Use add_ip method to add the IPs first')\n # get the 'WrapperPort's\n port1 = self._ips[ip1_name].get_port_by_name(port1_name)\n port2 = self._ips[ip2_name].get_port_by_name(port2_name)\n\n if len(port1) != len(port2):\n warning(f'ports: {ip1_name}:{port1.name}({len(port1)}), '\n f'{ip2_name}:{port2.name}({len(port2)})'\n ' have different widths!')\n\n inst1_args = getattr(self, ip1_name)\n inst2_args = getattr(self, ip2_name)\n\n full_name1 = port_direction_to_prefix(port1.direction) + port1.name\n full_name2 = port_direction_to_prefix(port2.direction) + port2.name\n\n # If a port was connected previoulsy,\n # take the previoulsy created signal, instead of creating a new one\n if full_name1 in inst1_args.keys():\n sig = inst1_args[full_name1]\n elif full_name2 in inst2_args.keys():\n sig = inst2_args[full_name2]\n else:\n # neither of the ports was connected previously\n # create a new signal for the connection\n combined_name = port1.name + '_' + port2.name\n self._signals_between_ips.append(combined_name)\n sig = Signal(len(port1), name=combined_name)\n setattr(self, combined_name, sig)\n\n inst1_args[full_name1] = sig\n inst2_args[full_name2] = sig", "def bind(self, tensors_ref: List[\"NmTensor\"], port_names: Optional[str] = None):\n # Set names.\n if port_names is None:\n port_names = [tensor.name for tensor in tensors_ref]\n\n for name, tensor in zip(port_names, tensors_ref):\n # Check the presence of the port name in \"default\" dictionary.\n if name in self._default_outputs.keys():\n # Name present - use the name being combination of producer and port names.\n name = (\n str(tensor.producer_step_number) + \"_\" + tensor.producer_name + \"_\" + tensor.name\n ) # last = port name\n\n logging.debug(\n \"Setting unique name of the default output port `{}` produced in step {} by `{}` to `{}`\".format(\n tensor.name, tensor.producer_step_number, tensor.producer_name, name\n )\n )\n # Store the output.\n self._default_outputs[name] = GraphOutput(tensor.ntype, tensor.producer_step_module_port)", "def bind_ports(self, ip, ports): #{\n if isinstance(ports, int):\n ports = [ports]\n for p in ports:\n try:\n if p==0:\n port = self.socket.bind_to_random_port(\"tcp://%s\" % ip)\n else:\n self.socket.bind(\"tcp://%s:%i\" % (ip, p))\n port = p\n except zmq.ZMQError:\n # bind raises this if the port is not free\n continue\n except zmq.ZMQBindError:\n # bind_to_random_port raises this if no port could be found\n continue\n else:\n break\n else:\n raise zmq.ZMQBindError('Could not find an available port')\n\n url = 'tcp://%s:%i' % (ip, port)\n self.bound.add(url)\n self._ready = True\n\n return port", "def connect_walker_ports(self, port1: Port, port2: Port) -> None:\n self.port_end.req_ports = port1\n self.port_end.req_ports = port2", "def ConnectPort(self, *args, **kwargs):\n # type: (*Any, **Any) -> None\n payload = { \"Arg1\": self }\n for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i]\n for item in kwargs.items(): payload[item[0]] = item[1]\n return self._execute('connectPort', payload=payload, response_object=None)", "def set_inputs(self,inputs):\n raise NotImplementedError(\"Robot.set_inputs\")", "def apply_default_port(nodes):\n nodes = nodes.split(',')\n\n def append_port(node):\n if re.match(r'.*:\\d+$', node):\n return node\n return f'{node}:8091'\n return [append_port(x) for x in nodes]", "def configure_dcbx_cn(self, ports, **kwargs):\n pass", "def forward_ports(app, ports,ip):\n for p in ports[0:(len(ports)-1)]:\n\tprint p\n os.system('iptables -t nat -A PREROUTING -i eth0 -p tcp --dport %d -j DNAT --to %s:%d' % (p, ip, p))\n # the last port in ports is for remote access on 22 of LXC\n os.system('iptables -t nat -A PREROUTING -i eth0 -p tcp --dport %d -j DNAT --to %s:22' % (ports[len(ports)-1], ip))\n print \"Done port forwarding.\"", "def __bind(self, args = []):\n \n try: \n\n # Start the local chat server and be ready to receive incoming requests\n localServerPort = self.__agent.startLocalServer()\n\n # Sleep a little bit to allow the new thread to open the listening port\n sleep(0.3)\n \n serverIp, serverPort = self.__cm.getConnectionInfo()\n\n self.__cm.send(p.T_BIND, [serverIp, localServerPort])\n reply = self.__cm.receive()\n \n if (reply.type == p.T_ERR):\n raise Exception, \"Port binding was not succussful!\"\n\n except Exception,e:\n self.__handleError('Bind', e)", "def modify_mstp_ports(self, ports, instance=0, **kwargs):\n pass", "def port_in(self, port_in):\n\n self._port_in = port_in", "def port_in(self, port_in):\n\n self._port_in = port_in", "def configure_dcbx_pfc(self, ports, **kwargs):\n pass", "def set_input_socket_by(self, socket_name_dict):\n default_enable_socket_list = []\n for socket_name, c in self.__taskobject.inputs.items():\n if not c['optional']:\n default_enable_socket_list.append( socket_name )\n\n sdesl = set(default_enable_socket_list)\n ssndk = set(socket_name_dict.keys())\n enable_socket_set = ssndk - sdesl\n\n for socket_name in enable_socket_set:\n self.check_input_socketname(socket_name)\n\n enable = socket_name_dict[socket_name]\n socket = self.__inputs[socket_name] \n if enable:\n socket['enable'] = True\n if socket['data']:\n socket['data'].enable(True)\n else:\n socket['enable'] = False\n if socket['data']:\n socket['data'].enable(False)" ]
[ "0.65591216", "0.62802726", "0.6155446", "0.6079365", "0.60514534", "0.5908299", "0.589971", "0.58949035", "0.58860606", "0.58305275", "0.58104044", "0.571254", "0.56847984", "0.56562734", "0.5622147", "0.5540028", "0.55354255", "0.5529397", "0.55176777", "0.54293704", "0.54083896", "0.5369977", "0.53696746", "0.5358035", "0.5344471", "0.5330031", "0.53061634", "0.53061634", "0.5296442", "0.5286508" ]
0.7338786
0
Return the task attached to the given input port.
def get_input_task(self, name='0'): port = self.get_input(name).other if port is None: return None return port.task
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_output_task(self, name='0'):\n port = self.get_output(name).other\n if port is None:\n return None\n return port.task", "def task(self) -> Optional[pulumi.Input[int]]:\n return pulumi.get(self, \"task\")", "def get_task_input(self, task, input_id):\n return self._gdb_interface.get_task_input(task, input_id)", "def output_node(self, port: int):\n return self._output_nodes_map[port]", "def get_task_input(self, task, input_id):\n input_record = self._read_transaction(tx.get_task_input, task=task, input_id=input_id)\n return _reconstruct_task_input(input_record[\"i\"])", "def get_task(self, u_name):\n raise NotImplementedError()", "def task(self, name):\n with self.db_lock:\n return self.rcon.hget(self.task_key, name)", "def get_task(self, code: str) -> \"Task\": # noqa: F821\n if code not in self.tasks:\n raise PyDSTaskNoFoundException(\n \"Task with code %s can not found in process definition %\",\n (code, self.name),\n )\n return self.tasks[code]", "def task(self):\n return self._task", "def task(self):\n return self._task", "def task(self):\n return self._task", "def task(self):\n return self._task", "def task(self):\n return self._task", "def get_node_input(node: Node, in_port: int):\n out_port = node.in_port(in_port).get_source()\n return out_port.node if out_port else None", "def _get_task(self, task):\n try:\n return TASKS[task]\n except KeyError:\n raise ValueError(\"task %s \"\n \"is not supported. \" % task)", "def get_task(self):\n return self.queue.get()", "def get_task_by_name(self, task_name):\n for task in self.tasks:\n if task.name == task_name:\n logger.debug(\"Returning task with name '%s': '%s'\", task_name, task.to_xml_string())\n return task\n raise ValueError(\"A step task with the name {} can not be found.\".format(task_name))", "def single_input_node(self, port: int):\n input_nodes = self.input_nodes(port)\n if len(input_nodes) != 1:\n raise Error('The amount of input nodes for port \"{}\" is not equal to 1. '.format(port) +\n refer_to_faq_msg(33))\n return input_nodes[0]", "def get_task(self, name):\n res = Task()\n self.GetTask(name, res)\n return res", "def get_task(self, key: str) -> Task:\n raise NotImplementedError", "def get_input_data(self, name='0'):\n # get the task connected to the given port\n task = self.get_input_task(name)\n if task is None:\n raise Exception(\"Port {} is not connected\".format(name))\n # get the name of the output port on the connected task\n port_name = self.get_input(name).other.name\n return task.get_output_data(name=port_name)", "def _get_current_task():\r\n return current_task", "def _get_current_task():\r\n return current_task", "def task(self) -> base_model.BaseTask:\n return self._task", "def task(self, name):\n if name not in self._tasks:\n raise TaskNotFoundError\n\n return self._tasks[name]", "def getTask(self, name):\n for t in self.tasks:\n if isinstance(name, str):\n if t.name == name:\n return t\n else:\n if t.__class__ is name:\n return t\n return None", "def get_task_host(self):\n comp = self.get_task_role()\n host = (comp.host_ref\n if isinstance(comp.host_ref, basestring)\n else comp.host_ref.value())\n if isinstance(host, IPAddressable):\n host.fix_arguments()\n host = host.get_ip()\n return host", "def get_task_host(self):\n comp = self.get_task_role()\n host = (comp.host_ref\n if isinstance(comp.host_ref, basestring)\n else comp.host_ref.value())\n if isinstance(host, IPAddressable):\n host.fix_arguments()\n host = host.get_ip()\n return host", "def get_task(self): \n task = self.buffer[0]\n self.buffer = np.delete(self.buffer, 0, 0)\n return task", "def check_task(self): \n return self.buffer[0]" ]
[ "0.73200965", "0.679983", "0.6649884", "0.6367047", "0.62009317", "0.61478215", "0.61400616", "0.6135504", "0.6060349", "0.6060349", "0.6060349", "0.6060349", "0.6060349", "0.6053958", "0.6027328", "0.59848976", "0.5978327", "0.5977943", "0.59680456", "0.59365356", "0.5935393", "0.59084576", "0.59084576", "0.5882255", "0.5882036", "0.5863835", "0.58323073", "0.58323073", "0.5828066", "0.5821545" ]
0.82394207
0
Return the data from the named port.
def get_input_data(self, name='0'): # get the task connected to the given port task = self.get_input_task(name) if task is None: raise Exception("Port {} is not connected".format(name)) # get the name of the output port on the connected task port_name = self.get_input(name).other.name return task.get_output_data(name=port_name)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def out_data(self, port: int) -> Optional[Any]:\n try:\n return copy(self.outputs[port])\n except:\n return None", "def get_input_data_value(node: Node, port: int):\n return node.in_port(port).data.get_value()", "def _get_data(self):\n raw_data = self._get_raw_data()\n if not raw_data:\n return None\n result = {}\n for line in raw_data:\n if 'tcp' in line:\n parts = line.split()\n proto = parts[0]\n local_addr = parts[3]\n state = parts[5]\n ip, port = local_addr.rsplit(':', 1)\n port = str(port)\n result[port] = 1\n if state == 'LISTEN':\n if port not in self.charts['ports']:\n self.charts['ports'].add_dimension([port, port, 'absolute'])\n return result", "def make_data_port(self):\n err = None\n sock = None\n for res in socket.getaddrinfo(None, 0, socket.AF_INET, socket.SOCK_STREAM, 0, socket.AI_PASSIVE):\n af, socktype, proto, canonname, sa = res\n try:\n sock = socket.socket(af, socktype, proto)\n sock.bind(sa)\n except OSError as _:\n err = _\n if sock:\n sock.close()\n sock = None\n continue\n break\n if sock is None:\n if err is not None:\n raise err\n else:\n raise OSError(\"getaddrinfo returns an empty list\")\n sock.listen(1)\n port = sock.getsockname()[1]\n host = self.sock.getsockname()[0]\n response = self._send_port_command(host, port)\n return sock, response", "def _get_port(self):\n return self.__port", "def outReceived(self, data):\n if data[0:4] == \"port\":\n port = data.split(':')[1]\n self.deferred.callback(port)", "def recieve_data(self):\r\n try:\r\n while True:\r\n try:\r\n data, self.addr = self.sock.recvfrom(1024)\r\n return data\r\n except socket.timeout:\r\n print(\"There is no packet at all!\")\r\n break\r\n except Exception:\r\n print(\"Can't recieve a package\")", "def get_zgrab_port_data_connection(self):\n return self.m_connection.zgrab_port_data", "def Port(self) -> int:", "def read_socket(self):\n a_socket = socket.socket()\n a_socket.connect((self.host, self.port))\n data = a_socket.recv(4096)\n a_socket.close()\n return data", "def read_port(self, port):\n value = 0\n if port == 1:\n self.__port_b_value = self.__bus.read_byte_data(\n self.__ioaddress, self.GPIOB)\n value = self.__port_b_value\n else:\n self.__port_a_value = self.__bus.read_byte_data(\n self.__ioaddress, self.GPIOA)\n value = self.__port_a_value\n return value", "def getPort(self):\n return self._port", "def _get_port_details(self, port_name):\n # TODO: Need to add a check that the port was recorded\n component_class = self.celltype.model.component_class\n port = None\n for name in (port_name, port_name + '__cell'):\n try:\n port = component_class.send_port(name)\n except NineMLNameError:\n try:\n port = component_class.state_variable(name)\n except NineMLNameError:\n pass\n if port is None:\n raise Pype9UsageError(\n \"Unknown port or state-variable '{}' for '{}' \"\n \"component array (available '{}').\".format(\n port_name, self.name, \"', '\".join(chain(\n component_class.send_port_names,\n component_class.sub_component(\n 'cell').send_port_names))))\n if isinstance(port, StateVariable):\n communicates = 'analog'\n else:\n communicates = port.communicates\n return communicates, port.name", "def _grab_port(self):\r\n port = \"\"\r\n while self._char != -1 and self._char in \"0123456789\":\r\n port += self._char\r\n self._get_char()\r\n if len(port) == 0:\r\n self._error(\"port empty\")\r\n return int(port)", "def port():", "def _get_data(self, read_size):\n if NIX:\n return super(Keyboard, self)._get_data(read_size)\n return self._pipe.recv_bytes()", "def get_port(self):\n return self.port", "def get_port(self):\n return self.__port", "def __recv__(self):\n data = self.port.read(size=1)\n v = int.from_bytes(data, byteorder=\"little\")\n if(self.verbose):\n pc.color_stdout(\"RED\")\n print(\"<< %s\\t - %s\\t - %d\"% (hex(v),bin(v),v))\n pc.color_stdout(\"RESET\")\n return data", "def getData(self,cmd):\n self.ser.write(cmd.encode()+END.encode())\n out = self.ser.readline()\n\n if(out == \"\"):\n raise IOError(\"communication failed\")\n return out", "def getPort(self):\n return self._port", "def show_port(self, port, **_params):\r\n return self.get(self.port_path % (port), params=_params)", "def s_read(self, timeout = 1):\n if self.s.is_open:\n data = [] \n b = bytearray()\n try:\n self.s.timeout = 3\n data = self.s.read(1)\n \n if not len(data):\n return b\n\n self.s.timeout = .04\n data += self.s.read(500)\n except Exception as e:\n print(\"Could not read from port\" + str(e))\n\n start = data.find(b'\\x7e')\n end = data.find(b'\\x7f')\n\n txt_start = b''\n txt_end = b''\n if start < 0:\n txt_start = data\n elif end < 0:\n txt_start = data\n else:\n txt_start = data[0:start]\n txt_end = data[end+1:]\n\n txt = txt_start + txt_end\n if len(txt):\n if self.log_ascii:\n self.logfile.write(txt)\n\n # End logging \n if Connection.START_UP_STRING in data:\n raise Reset_Exception('ChipSHOUTER unit has reset - wait 5 seconds then reinitialize.') \n\n if start < 0 or end < 0 or end < start:\n b = bytearray()\n return b\n if self.log_input:\n self.logfile.write('\\nIN :' + str(len(data)) + '[' + hexlify(data) + ']' + '\\n')\n b.extend(data[start:end])\n return b\n else:\n raise IOError('Comport is not open, use ctl_connect()')", "def __get_response(serial_port):\n read_data = \"\"\n while not read_data.endswith(\"\\n>> \"):\n ready = select.select([serial_port], [], [], 25)[0]\n if ready:\n read_data += serial_port.read(serial_port.inWaiting()).decode(\n \"utf-8\", \"replace\")\n else:\n raise errors.DeviceError(\n \"Device cambrionix get response failed. \"\n \"Read timeout on serial port: {}\".format(serial_port))\n\n return read_data.splitlines()", "def Read_Bytes(self, size = 0):\r\n if size == 0: size = self.Port.inWaiting()\r\n data = self.Port.read(size)\r\n return data", "def port(self) -> int:", "def __read(self):\n if not self.__port:\n print(\"cannot perform __read() when unconnected\")\n return []\n\n buffer = bytearray()\n\n while True:\n # retrieve as much data as possible\n data = self.__port.read()\n\n # if nothing was recieved\n if not data:\n print(\"Failed to read port\")\n break\n\n buffer.extend(data)\n\n # end on chevron (ELM prompt character)\n if self.ELM_PROMPT in buffer:\n break\n\n # log, and remove the \"bytearray( ... )\" part\n print(\"read: \" + repr(buffer)[10:-1])\n\n # clean out any null characters\n buffer = re.sub(b\"\\x00\", b\"\", buffer)\n\n # remove the prompt character\n if buffer.endswith(self.ELM_PROMPT):\n buffer = buffer[:-1]\n\n # convert bytes into a standard string\n string = buffer.decode()\n\n # splits into lines while removing empty lines and trailing spaces\n lines = [ s.strip() for s in re.split(\"[\\r\\n]\", string) if bool(s) ]\n\n return lines", "def _get_data(self):\n c = Connector(self.host, self.username, self.password)\n return c.getLanDevices()", "def port(self) -> pulumi.Output[int]:\n return pulumi.get(self, \"port\")", "def port(self) -> pulumi.Output[int]:\n return pulumi.get(self, \"port\")" ]
[ "0.6669574", "0.63913363", "0.63741755", "0.6348516", "0.6304568", "0.6220529", "0.61653084", "0.61174357", "0.604259", "0.60177284", "0.60099936", "0.5995539", "0.5963908", "0.5963786", "0.5948678", "0.58976704", "0.5891747", "0.5881411", "0.58772135", "0.5842859", "0.58380896", "0.5824767", "0.5817986", "0.5813021", "0.5795511", "0.5795321", "0.5771136", "0.577001", "0.57614756", "0.57614756" ]
0.68804854
0
Return the task attached to the given output port.
def get_output_task(self, name='0'): port = self.get_output(name).other if port is None: return None return port.task
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def output_node(self, port: int):\n return self._output_nodes_map[port]", "def get_input_task(self, name='0'):\n port = self.get_input(name).other\n if port is None:\n return None\n return port.task", "def get_task_output(self, task, output_id):\n return self._gdb_interface.get_task_output(task, output_id)", "def get_output(self, name='0'):\n if name not in self._outputs:\n raise ValueError(\"Invalid port name '{0}'\".format(name))\n return self._outputs[name]", "def get_task_output(self, task, output_id):\n output_record = self._read_transaction(tx.get_task_output, task=task, output_id=output_id)\n return _reconstruct_task_output(output_record[\"o\"])", "def task(self) -> Optional[pulumi.Input[int]]:\n return pulumi.get(self, \"task\")", "def task(self):\n return self._task", "def task(self):\n return self._task", "def task(self):\n return self._task", "def task(self):\n return self._task", "def task(self):\n return self._task", "def get_task(self):\n return self.queue.get()", "def outputRetrieved(self, blTaskName, rng):\n return self._genericCommand('outputRetrieved', blTaskName, rng)", "def _get_port(self):\n return self.__port", "def get_task_uuid(self):\n\t\treturn call_sdk_function('PrlRunningTask_GetTaskUuid', self.handle)", "def task(self, name):\n with self.db_lock:\n return self.rcon.hget(self.task_key, name)", "def get_task(self, code: str) -> \"Task\": # noqa: F821\n if code not in self.tasks:\n raise PyDSTaskNoFoundException(\n \"Task with code %s can not found in process definition %\",\n (code, self.name),\n )\n return self.tasks[code]", "def out_aux_port(self, port):\n return self.auxout[port - 1]", "def get_task_host(self):\n comp = self.get_task_role()\n host = (comp.host_ref\n if isinstance(comp.host_ref, basestring)\n else comp.host_ref.value())\n if isinstance(host, IPAddressable):\n host.fix_arguments()\n host = host.get_ip()\n return host", "def get_task_host(self):\n comp = self.get_task_role()\n host = (comp.host_ref\n if isinstance(comp.host_ref, basestring)\n else comp.host_ref.value())\n if isinstance(host, IPAddressable):\n host.fix_arguments()\n host = host.get_ip()\n return host", "def get_task(self): \n task = self.buffer[0]\n self.buffer = np.delete(self.buffer, 0, 0)\n return task", "def _get_output_port_of_flowrule (infra, fr):\n for action in fr.action.split(\";\"):\n comm, arg = action.split(\"=\", 1)\n if comm == 'output':\n if \"://\" in arg:\n # target-less flow rule -> skip\n return\n arg = NFFGToolBox.try_to_convert(arg)\n return infra.ports[arg]\n else:\n raise RuntimeError(\"Couldn't find output InfraPort object for Flowrule %s\"\n \" in Infra%s!\" % (fr.id, infra.id))", "def get_task(self, u_name):\n raise NotImplementedError()", "def _get_current_task():\r\n return current_task", "def _get_current_task():\r\n return current_task", "def get_task(self, name):\n res = Task()\n self.GetTask(name, res)\n return res", "def GetPortDestProc(portp):\n spacep = portp.data.receiver\n out_str = \"Not found\"\n for tsk in kern.tasks:\n if tsk.itk_space == spacep:\n if tsk.bsd_info:\n destprocp = Cast(tsk.bsd_info, 'struct proc *')\n out_str = \"{0:s}({1: <d})\".format(destprocp.p_comm, destprocp.p_pid)\n else:\n out_str = \"unknown\"\n break\n \n return out_str", "def target(self):\n return self._task_target", "def get_serial(cls, port):\n if port in cls._open_ports:\n return cls._open_ports[port]\n else:\n return None", "def task(self) -> base_model.BaseTask:\n return self._task" ]
[ "0.73431987", "0.7269821", "0.67667603", "0.64185977", "0.62417954", "0.6162333", "0.61589986", "0.61589986", "0.61589986", "0.61589986", "0.61589986", "0.6016541", "0.5976228", "0.59619164", "0.5914219", "0.588327", "0.58810896", "0.5880721", "0.58404255", "0.58404255", "0.5821902", "0.58131754", "0.57946724", "0.5750727", "0.5750727", "0.57153076", "0.5710711", "0.570377", "0.56899583", "0.56602365" ]
0.8278482
0
Execute the task. This method requires at a minimum that all input ports are connected to valid data sources. Subclasses can customize the execution with keyword arguments. The reference implementation only checks that the input ports are all connected and raises an error if they aren't.
def run(self, *arg, **kw): self.dirty = False for port in self.inputs: self.get_input_data(port)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def execute(self, targets):\r\n raise TaskError('execute() not implemented')", "def run_dataflow(self, *args, **kwargs):\n raise NotImplementedError", "def evaluate(self, tick, task, inputs, nosend_ports=None):\n raise NotImplementedError(\"abstract\")", "def execute(self, inputs={}):\n self.validate()", "def run(self):\n self.assign_inputs()\n self.execute()\n self.collect_outputs()", "def execute(self):\n res = self.resolveInputVariables()\n if not res['OK']:\n LOG.error(\"Failed to resolve input variables:\", res['Message'])\n return res\n return S_OK()", "def run(self):\n self._validate_inputs()\n if self._destination_out_exists:\n print('Destination{} already skipping run'.format(self._inputs[-1]))\n try:\n if self.operator_func:\n self.operator_func(*self._inputs)\n else:\n raise RuntimeError('self.operator_func is not defined !!')\n except Exception as ex:\n print(ex)\n raise RuntimeError('self.operator_func failed !!')", "def set_input(self, *arg, **kw):\n # Convert arguments into keyword arguments\n for i, a in enumerate(arg):\n kw[str(i)] = a\n\n for name, value in six.iteritems(kw):\n if name not in self._inputs:\n raise ValueError(\"Invalid port name '{0}'\".format(name))\n\n if isinstance(value, Port):\n port = value\n else:\n port = Task.create_source(value).get_output()\n port.connect(self._inputs[name])\n\n self._dirty = True\n return self", "def execute_task(self):\n raise NotImplementedError(\"Execute Task method not implemented\")", "def evaluate(self, tick, task, inputs, nosend_ports=None, fail_on_unexpected_nosend=False):\n\n logger.debug(\"Transfers for job %s\" % tick)\n\n ports = []\n transfers = []\n transfer_results = {}\n for port, (valueid, worker) in inputs.iteritems():\n \n \n d = self.fetch_from(worker, valueid)\n \n def transfer_completed(transfer_result, valueid, port):\n if transfer_result: # `None` if the value was already present\n transfer_results[port] = transfer_result\n return self.get_value(valueid)\n \n\n d.addCallback(transfer_completed, valueid, port)\n ports.append(port)\n transfers.append(d)\n \n d = defer.DeferredList(transfers)\n \n def run(inputs):\n \"\"\"\n Runs in separate thread.\n \"\"\"\n logger.debug(\"Running job %s\" % tick)\n \n #start = time.clock()\n start = datetime.datetime.now()\n try:\n result = task.evaluate(inputs)\n except:\n result = failure.Failure()\n finally:\n #end = time.clock()\n end = datetime.datetime.now()\n \n logger.debug(\"Running job %s finished\" % tick)\n \n #duration = end - start\n duration = (end - start).total_seconds()\n return traverser.EvalResult(result, duration)\n \n @twistit.yieldefer\n def got_all(results):\n \n logger.debug(\"Transfers for job %s finished\" % tick)\n \n values = []\n for success, result in results:\n if not success:\n if result.check(pickle.PickleError):\n raise pickle.PickleError(\"Failed to unpickle input of %r.%r: %s\" %(tick, port, result))\n else:\n result.raiseException()\n else:\n values.append(result)\n\n inputs = dict(zip(ports, values))\n \n evalresult = yield threads.deferToThread(run, inputs)\n \n if not isinstance(evalresult.result, dict) and not isinstance(evalresult.result, failure.Failure):\n raise ValueError(\"Evaluation of task %r did not produce a dict or a failure. Got %r.\" % (task, evalresult.result))\n \n defer.returnValue(evalresult)\n \n def task_completed(evalresult):\n if isinstance(evalresult.result, dict):\n \n # Injest values into our store and replace the eval results with ValueIds.\n outputs = evalresult.result\n outs = {}\n datasizes = {}\n for port, value in outputs.iteritems():\n valueid = ValueId(graph.Endpoint(tick, port))\n \n pickle_supported = True\n if nosend_ports and port in nosend_ports:\n pickle_supported = False\n \n try:\n size = self.set_value(valueid, \n value, \n pickle_supported, \n pickle_supported and fail_on_unexpected_nosend)\n except NoPickleError as e:\n e = NoPickleError(\"Value of output port %r cannot be pickled.\" % port,\n cause=e.cause)\n # TODO: memory leak. We should remove the values we've set in\n # previous loop iterations.\n raise e\n \n outs[port] = valueid\n if size is not None:\n datasizes[port] = size \n \n evalresult.result = outs\n evalresult.datasizes = datasizes\n evalresult.transfer_results = transfer_results\n return evalresult\n \n d.addCallback(got_all)\n d.addCallback(task_completed)\n return d", "def call(self, inputs):\n raise NotImplementedError", "def _process_task_inputs(self):\n _input = self._task.input\n log.debug('Input parsing for %s and node %s from container', self._task.project_id, self._task.internal_id)\n log.debug(_input)\n\n input_ports = dict()\n for port in _input:\n log.debug(port)\n self._process_task_input(port, input_ports)\n\n log.debug('DUMPING json')\n #dump json file\n if input_ports:\n file_name = os.path.join(self._executor.in_dir, 'input.json')\n with open(file_name, 'w') as f:\n json.dump(input_ports, f)\n\n log.debug('DUMPING DONE')", "def __call__(self, inputs):\n self.inputs = inputs\n self.process_inputs()\n self.init_mesh()\n mesh_modified = self.run_tasks()\n self.write_output_mesh(mesh_modified)", "def run(self, *args, **kwargs):\n raise NotImplementedError('Tasks must define the run method.')", "def run(self):\n \n #calculate node\n print (\"{} run()\".format(self.getName()))\n\n #feed outputs\n result = 0\n for i in self.getInputPorts():\n v = i.getValue()\n # print v, self.getName()\n if v:\n result += float(v)\n\n for i in self.getOutputPorts(): #for every output port\n i.setValue(result) #set test value\n print (\"Output: {}\".format(i.getValue()))\n\n # print \"\"", "def execute(self):\n raise TaskError(\"Task %s: subclass should override execute() method!\" %\n self)", "def run_app():\n target = None\n negative_results = False\n\n description = 'Simple TCP port scanner'\n epilog = 'The author of this code take no responsibility for your use or misuse'\n parser = argparse.ArgumentParser(prog='TCPPortScan.py', description=description, epilog=epilog)\n parser.add_argument(\"target\", help=\"Your target to scan\")\n parser.add_argument('-p', '--port', help=\"Set a single port\", default=22, type=int)\n parser.add_argument('-r', '--range', help=\"Set a port range (eq 22-80)\")\n parser.add_argument(\"--all\", help=\"Show negative results (closed ports)\", action=\"store_true\")\n args = parser.parse_args()\n\n if len(args.target) < 1:\n print('You did not provide any target?')\n exit(1)\n else:\n target = args.target\n\n if args.all:\n negative_results = True\n\n if args.range:\n print(\"Start scanning ports {} on target {}\".format(args.range, target))\n range_list = args.range.split('-')\n for element in range(int(range_list[0]), int(range_list[1]) + 1):\n port_scan(target, element, negative_results)\n else:\n print(\"Start scanning port {} on target {}\".format(args.port, target))\n port_scan(target, args.port, negative_results)", "def run(self,\n inputs,\n num_executions=None,\n call_before_execution=None,\n call_after_execution=None,\n time_scale=None):\n from PsyNeuLink.Globals.Run import run\n return run(self,\n inputs=inputs,\n num_executions=num_executions,\n call_before_trial=call_before_execution,\n call_after_trial=call_after_execution,\n time_scale=time_scale)", "def run_task(self) -> Task:", "def eval_task(index, child_conns, parent_conns, shared_data, task, type):\n if type == 'GPU':\n set_gpu_device(index)\n if task.do_redirect:\n sys.stdin = file(os.devnull)\n sys.stdout = file(os.devnull)\n if task.do_redirect is None and os.name == 'posix':\n log_warn(\"WARNING: specify do_redirect=True if CUDA code is not\\\n compiling. see \\\n <http://playdoh.googlecode.com/svn/docs/playdoh.html#gpu>\")\n log_info(\"Evaluating task on %s #%d\" % (type, index + 1))\n # shared data: if there is shared data, pass it in the task's kwds\n # task fun must have fun(..., shared_data={})\n if len(shared_data) > 0:\n task.kwds['shared_data'] = shared_data\n result = task.fun(*task.args, **task.kwds)\n# log_debug(\"Task successfully evaluated on %s #%d...\" % (type, index))\n if type == 'GPU':\n# set_gpu_device(0)\n close_cuda() # ensures that the context specific to the process is\n # closed at the process termination\n child_conns[index].send(result)", "def run_and_check(self, *args, **kwargs) -> None:\n raise NotImplementedError", "def execute(self) :\n \n raise NotImplementedError()", "def call(self, task, **options):\n pass", "def __scan_progressive__(self, hosts, ports, arguments, callback, sudo):\n try:\n scan_data = self._nm.scan(hosts, ports, arguments, sudo)\n except PortScannerError:\n scan_data = None\n\n if callback is not None:\n callback(hosts, scan_data)", "def run_on_host(self, *args, **kwargs) -> Any:\n raise NotImplementedError", "def call(self, **params):\n # NOTE - use __call__??\n # TODO - move exec_script here?\n # TODO - call should handle param defaults\n from datapane.runner.exec_script import run\n\n run(self, params)", "def run(self):\n# log.trace(\" run task %s \", self.name)\n return self.target.send(self.params)", "def run(self):\n\n input_args = {}\n self._execute(input_args, self.args)", "def call(self, inputs, state):\n raise NotImplementedError", "def run(self):\n try:\n self._run()\n except Exception as err:\n # TODO: Do Task Failure to run exception handling\n pass" ]
[ "0.6244398", "0.6065953", "0.6056772", "0.60060936", "0.5825107", "0.5775887", "0.57420397", "0.56945634", "0.56765115", "0.5664168", "0.5568796", "0.5538208", "0.550687", "0.5504932", "0.54840845", "0.547578", "0.54067135", "0.534687", "0.5298878", "0.5262872", "0.52575904", "0.52464586", "0.52269775", "0.52126664", "0.51775986", "0.5171707", "0.5162262", "0.5160962", "0.5156201", "0.5149591" ]
0.6523009
0
Set dirty state on all downstream tasks.
def _reset_downstream(self, _, isdirty, *args): if isdirty: for name in self.outputs: task = self.get_output_task(name=name) if task: task.dirty = True
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _update_all_tasks(self) -> None:\n for task in self.tasks:\n task.update()", "def __update_task(self, tasks, **extra_args):\n for task in tasks:\n assert isinstance(\n task, Task), \"Core.update_job_state: passed an argument\" \\\n \" which is not a `Task` instance.\"\n task.update_state()", "def update_job_state(self, *tasks, **extra_args):\n pass", "def SetDirty(self, *args, **kwargs):\n pass", "def setDirty( self, state = True ):\n self._dirty = state", "def tasks(self, tasks):\n\n self._tasks = tasks", "def _update_tasks(self, tasks):\n\n self._print('Updating tasks {} with {} ...'.format(self._tasks, tasks))\n\n self._tasks.update(tasks)", "def mark_no_changes(self):", "def update_states(self) -> None:\n self.set_states()\n self.async_write_ha_state()", "def run(self):\n modify_tasks = filter(self._task_filter, acm.FAelTask.Select(''))\n print([task.Name() for task in modify_tasks])\n for task in modify_tasks:\n #new_task = task.Clone()\n self._update(task)\n try:\n task.Commit()\n except:\n print('Skipping: Task already exists')", "def test_update_task_states(self):\r\n changed = self.combinedoe.update_task_states()\r\n self.assertFalse(changed)\r\n\r\n current_task = self.combinedoe.current_task\r\n current_task.change_state(CombinedOpenEndedV1Module.DONE)\r\n changed = self.combinedoe.update_task_states()\r\n\r\n self.assertTrue(changed)", "def _on_state_update(self) -> None:\n super()._on_state_update()\n self._set_futures(True)", "def set_task_done(self):\n\n tasks = self._get_all_tasks()\n\n task_id = tasks[self.tasks_view.currentRow()].Id\n\n self.tasks_flow.set_status(task_id, 0)\n\n # Refresh the table\n self.write_tasks_table()", "def set_task_in_progress(self):\n\n tasks = self._get_all_tasks()\n\n task_id = tasks[self.tasks_view.currentRow()].Id\n\n self.tasks_flow.set_status(task_id, 1)\n\n # Refresh the table\n self.write_tasks_table()", "def __setstate__(self, state):\n state['_lock'] = Lock()\n self.__dict__.update(state)", "def _reset(self, *args):\n self.dirty = True", "def _pre_submit(self):\n if self._uuid is not None:\n return self._state\n for rdisk in self.resources:\n rdisk.flush()", "def clean_tasks(self, tasks, dryrun, cleanforget):\n cleaned = set()\n forget_tasks = cleanforget and not dryrun\n for task in tasks:\n if task.name not in cleaned:\n cleaned.add(task.name)\n task.clean(self.outstream, dryrun)\n if forget_tasks:\n self.dep_manager.remove(task.name)\n self.dep_manager.close()", "def temporary_changes(self):\n archived_data = deepcopy(self._data.__wrapped__)\n archived_settings = {\n k: deepcopy(getattr(self, k))\n for k in [\n \"settings_files\",\n \"_updates\",\n \"_fragments\",\n \"_combined_fragment\",\n ]\n }\n yield self\n\n # reinstate all saved data after context block is finished\n self._set_data(archived_data)\n for k, v in archived_settings.items():\n setattr(self, k, v)", "def dirty(self, graph: Graph) -> None:\n log.debug(\"%s dirty, needs write\", self.path)\n\n self.graphToWrite = graph\n if self.writeCall:\n self.writeCall.reset(self.flushDelay)\n else:\n # This awkward assignment is just to hide from mypy.\n setattr(self, 'writeCall',\n reactor.callLater(self.flushDelay, self.flush))", "def updateList(self):\n for state in list_:\n state.update(True)", "def flag_all_commit(self):\n\t\tfor k in self.data.keys():\n\t\t\tindex = 0\n\t\t\tfor item in self[k]:\n\t\t\t\tself.data[k][index]['meta']['needs_commit'] = True\n\t\t\t\tindex += 1", "def reset_task_state(self) -> None:\n self.set_task_state(task_state=self.sample_task_state())", "def set_task_state(self, task, state):\n self._write_transaction(tx.set_task_state, task=task, state=state)", "def force_invalidate(self, vts):\r\n for vt in vts.versioned_targets:\r\n self._invalidator.force_invalidate(vt.cache_key)\r\n vt.valid = False\r\n self._invalidator.force_invalidate(vts.cache_key)\r\n vts.valid = False", "def UNUSED_save_ifdirty(self):\n if (self.get_isdirty()):\n self.save()", "def update_task_states(self):\r\n changed = False\r\n if not self.ready_to_reset:\r\n self.task_states[self.current_task_number] = self.current_task.get_instance_state()\r\n current_task_state = json.loads(self.task_states[self.current_task_number])\r\n if current_task_state['child_state'] == self.DONE:\r\n self.current_task_number += 1\r\n if self.current_task_number >= (len(self.task_xml)):\r\n self.state = self.DONE\r\n self.current_task_number = len(self.task_xml) - 1\r\n else:\r\n self.state = self.INITIAL\r\n changed = True\r\n self.setup_next_task()\r\n return changed", "def set_task_finished(self):\n self.busy = False", "def sync_mark_dirty(self, chunk, coords):\n\n chunk.dirty = True", "def commit(self, force=False):\n if len(self.changed) > 0 or force: \n self.things_obj.set_all(self.things_dict, self.parent)\n logging.error('commited!!!!!!!!')" ]
[ "0.67158985", "0.6424232", "0.6123255", "0.59694195", "0.5936196", "0.56643915", "0.56304514", "0.5622691", "0.5592518", "0.55850524", "0.558018", "0.5550249", "0.5540967", "0.5538353", "0.5495823", "0.54849344", "0.54771364", "0.54654974", "0.54427445", "0.5415702", "0.54025656", "0.5400331", "0.53953636", "0.5388416", "0.5386584", "0.53791964", "0.53702956", "0.53651774", "0.5352551", "0.5347106" ]
0.71467745
0
Create an input port that accepts the given data type. An input port can accept one or more data types, but for compatibility with the ``create_output_port`` method, the default 2 argument call signature will generate an input port that accepts only the given data class. The keyword argument ``data_classes`` can be used to generate a port that accepts multiple types. >>> Port = Task.make_input_port(int) >>> int in Port({}).accepts() True >>> Port = Task.make_input_port(data_classes=(int, float)) >>> int in Port({}).accepts() True
def make_input_port(cls, data_class=None, data_classes=()): if data_class is not None: data_classes += (data_class,) class ReturnedInputPort(InputPort): """A subclass of InputPort accepting provided types.""" def accepts(self): """Return the classes accepted by the port.""" return data_classes return ReturnedInputPort
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def build_data_input(cls, name='input'):\n return cls(name, PortDirection.INPUT, type=PortType.DATA)", "def create_source(cls, data):\n class SourceOutput(OutputPort):\n\n \"\"\"A port attached to a source task.\"\"\"\n\n name = '0'\n description = str(data)\n\n def emits(self):\n \"\"\"Return the type of the provided datum.\"\"\"\n return type(data)\n\n class Source(Task):\n\n \"\"\"Generated source task.\"\"\"\n\n output_ports = {'0': SourceOutput}\n\n def get_input_data(self, name='0'):\n \"\"\"Return the datum associated with this source.\"\"\"\n return data\n\n def run(self, *arg, **kw):\n \"\"\"Do nothing.\"\"\"\n super(Source, self).run(*arg, **kw)\n self._output_data['0'] = data\n\n return Source()", "def make_input(name, data, dtype=None, **tags):\n from ..utils import make_placeholder_for\n input_var = make_placeholder_for(name, data, dtype=dtype, **tags)\n input_layer = InputLayer(input_var, shape=(None,) + data.shape[1:])\n return input_layer, input_var", "def make_output_port(cls, data_class=None):\n class ReturnedOutputPort(OutputPort):\n\n \"\"\"A subclass of InputPort accepting provided types.\"\"\"\n\n def emits(self):\n \"\"\"Return the class emitted by the port.\"\"\"\n return data_class\n\n return ReturnedOutputPort", "def CreateInput(self, name=None, type=None, data=None):\n\n\n inp = self._input_registry.Create(name, type, data)\n\n self._inputs.append(inp)\n\n return inp", "def test_input_type(self, input_cls):\n\n class Model(Module):\n def __init__(self):\n super().__init__()\n self.layer = Linear(4, 4)\n\n def forward(self, input):\n if isinstance(input, list):\n input = input[0]\n else:\n assert isinstance(input, dict), input\n input = input[\"in\"]\n return self.layer(input)\n\n model = FSDP(Model()).cuda()\n optim = SGD(model.parameters(), lr=0.1)\n\n for _ in range(5):\n in_data = torch.rand(64, 4).cuda()\n in_data.requires_grad = True\n if input_cls is list:\n in_data = [in_data]\n else:\n self.assertTrue(input_cls is dict)\n in_data = {\"in\": in_data}\n\n out = model(in_data)\n out.sum().backward()\n optim.step()\n optim.zero_grad()", "def set_input(self, *arg, **kw):\n # Convert arguments into keyword arguments\n for i, a in enumerate(arg):\n kw[str(i)] = a\n\n for name, value in six.iteritems(kw):\n if name not in self._inputs:\n raise ValueError(\"Invalid port name '{0}'\".format(name))\n\n if isinstance(value, Port):\n port = value\n else:\n port = Task.create_source(value).get_output()\n port.connect(self._inputs[name])\n\n self._dirty = True\n return self", "def mutate(self, info, input):\n # Convert input to dictionary\n data = api_utils.input_to_dictionary(input)\n data_source_type = Operation('ModelDataSourceType').create(**data)\n return CreateDataSourceType(data_source_type=data_source_type)", "def make_dataclass_validator(_cls: Type[Any], config: Type['BaseConfig']) -> 'CallableGenerator':\n dataclass_params = _cls.__dataclass_params__\n stdlib_dataclass_parameters = {param: getattr(dataclass_params, param) for param in dataclass_params.__slots__}\n cls = dataclass(_cls, config=config, **stdlib_dataclass_parameters)\n yield from _get_validators(cls)", "def InputPort(dynamic, name, environment, queueSizeSamples=1, queueSizeSeconds=-1):\n return Port.make_shared(InputPortInterface(dynamic, name, environment, queueSizeSamples, queueSizeSeconds))", "def set_input_type_class(self, input_type_class):\n if input_type_class is not None:\n self._input_type.expected = (input_type_class,)\n return self", "def create_input(self, dataset_name, dataset_idx=None, compounddatatype=None,\n min_row=None, max_row=None, x=0, y=0, clean=True):\n return self.create_xput(dataset_name, dataset_idx, compounddatatype, (min_row, max_row), (x, y), True,\n clean=clean)", "def get_synth_input_fn(batch_size, height, width, num_channels, data_format, num_classes, dtype=tf.float32):\n\n if data_format not in [\"NHWC\", \"NCHW\"]:\n raise ValueError(\"Unknown data_format: %s\" % str(data_format))\n\n if data_format == \"NHWC\":\n input_shape = [batch_size, height, width, num_channels]\n else:\n input_shape = [batch_size, num_channels, height, width]\n\n # Convert the inputs to a Dataset.\n inputs = tf.truncated_normal(input_shape, dtype=dtype, mean=127, stddev=60, name='synthetic_inputs')\n labels = tf.random_uniform([batch_size], minval=0, maxval=num_classes - 1, dtype=tf.int32, name='synthetic_labels')\n\n data = tf.data.Dataset.from_tensors((inputs, labels))\n\n data = data.repeat()\n\n data = data.prefetch(buffer_size=tf.data.experimental.AUTOTUNE)\n\n return data", "def __init__(\n self,\n input_types,\n output_types,\n id_priority_list=None,\n skip_on_failure=False,\n skip_w_regex=None,\n skip_on_success=False,\n idstruct_class=IDStruct,\n copy_from_doc=False,\n debug=False,\n ):\n # pylint: disable=R0913, W0102\n self.input_types = self._parse_input_types(input_types)\n self.output_types = self._parse_output_types(output_types)\n self.id_priority_list = id_priority_list or []\n\n self.skip_on_failure = skip_on_failure\n self.skip_on_success = skip_on_success\n\n if skip_w_regex and not isinstance(skip_w_regex, str):\n raise ValueError(\"skip_w_regex must be a string\")\n elif not skip_w_regex:\n self.skip_w_regex = None\n else:\n self.skip_w_regex = re.compile(skip_w_regex)\n\n self.idstruct_class = idstruct_class\n self.copy_from_doc = copy_from_doc\n\n self.histogram = Histogram()\n # Setup logger and logging level\n self.logger, _ = get_logger(\"datatransform\")\n\n self.debug = debug", "def testInputTypeError(self, batch_size, in_length, in_channels, out_channels,\n kernel_shape, padding, use_bias, out_shape,\n stride_shape, use_output_shape):\n conv1 = snt.Conv1DTranspose(\n output_channels=out_channels,\n output_shape=out_shape if use_output_shape else None,\n kernel_shape=kernel_shape,\n padding=padding,\n stride=stride_shape,\n name=\"conv1\",\n use_bias=use_bias)\n\n for dtype in (tf.uint32, tf.float64):\n x = tf.constant(np.ones([batch_size, in_length,\n in_channels]), dtype=dtype)\n err = \"Input must have dtype tf.float.*\"\n with self.assertRaisesRegexp(TypeError, err):\n conv1(x)", "def build_streaming_iterator(\n cls,\n data_path_and_name_and_type,\n preprocess_fn,\n collate_fn,\n key_file: str = None,\n batch_size: int = 1,\n dtype: str = np.float32,\n num_workers: int = 1,\n allow_variable_data_keys: bool = False,\n ngpu: int = 0,\n inference: bool = False,\n ) -> DataLoader:\n assert check_argument_types()\n # For backward compatibility for pytorch DataLoader\n if collate_fn is not None:\n kwargs = dict(collate_fn=collate_fn)\n else:\n kwargs = {}\n\n dataset = IterableESPnetDataset(\n data_path_and_name_and_type,\n float_dtype=dtype,\n preprocess=preprocess_fn,\n key_file=key_file,\n )\n if dataset.apply_utt2category:\n kwargs.update(batch_size=1)\n else:\n kwargs.update(batch_size=batch_size)\n\n cls.check_task_requirements(\n dataset, allow_variable_data_keys, train=False, inference=inference\n )\n\n return DataLoader(\n dataset=dataset,\n pin_memory=ngpu > 0,\n num_workers=num_workers,\n **kwargs,\n )", "def input_feeds(self, num_test_inputs, name2shape):\n input_data_list = []\n for _ in range(num_test_inputs):\n inputs = {}\n for name, shape in name2shape.items():\n inputs.update({name: np.random.randint(-1, 2, shape).astype(np.float32)})\n input_data_list.extend([inputs])\n data_reader = TestDataFeeds(input_data_list)\n return data_reader", "def create_port(self, fields=None, filters=None, mask=None, entity=None):\n entity = entity or self.entity.type.name\n fields = self.fields if fields is None else fields\n parameters = {k: None for k in self.context_types.input.rows}\n port = formfield.to_port(\n entity, fields,\n filters=filters,\n mask=mask,\n parameters=parameters,\n db=self.db)\n port = annotate_port(self.domain, port)\n return port", "def input_fn(params):\n batch_size = params[\"batch_size\"]\n\n num_examples = len(features)\n\n # This is for demo purposes and does NOT scale to large data sets. We do\n # not use Dataset.from_generator() because that uses tf.py_func which is\n # not TPU compatible. The right way to load data is with TFRecordReader.\n d = tf.data.Dataset.from_tensor_slices({\n \"unique_ids\":\n tf.constant(all_unique_ids, shape=[num_examples], dtype=tf.int32),\n \"input_ids\":\n tf.constant(all_input_ids, \n shape=[num_examples, seq_length],\n dtype=tf.int32),\n \"input_mask\":\n tf.constant(all_input_mask,\n shape=[num_examples, seq_length],\n dtype=tf.int32),\n \"input_type_ids\":\n tf.constant(all_input_type_ids,\n shape=[num_examples, seq_length],\n dtype=tf.int32),\n })\n\n d = d.batch(batch_size=batch_size, drop_remainder=False)\n return d", "def provider(input_types=None, should_shuffle=True, pool_size=-1,\n can_over_batch_size=True,\n calc_batch_size=None,\n cache=CacheType.NO_CACHE,\n init_hook=None, **kwargs):\n\n def __wrapper__(generator):\n class DataProvider(object):\n def __init__(self, file_list, **kwargs):\n self.logger = logging.getLogger(\"\")\n self.logger.setLevel(logging.INFO)\n self.input_types = None\n if 'slots' in kwargs:\n self.logger.warning('setting slots value is deprecated, '\n 'please use input_types instead.')\n self.slots = kwargs['slots']\n self.slots = input_types\n self.should_shuffle = should_shuffle\n self.pool_size = pool_size\n self.can_over_batch_size = can_over_batch_size\n self.calc_batch_size = calc_batch_size\n self.file_list = file_list\n self.generator = generator\n self.cache = cache\n if init_hook is not None:\n init_hook(self, file_list=file_list, **kwargs)\n if self.input_types is not None:\n self.slots = self.input_types\n assert self.slots is not None\n assert self.generator is not None\n\n if len(self.slots) == 1:\n self.generator = SingleSlotWrapper(self.generator)\n\n return DataProvider\n\n return __wrapper__", "def input_fn(sources, train, params):\n \n raise NotImplementedError", "def _fit(cls, project_id: str, name: str, data_type: DataType, training_type: TypeProblem,\n dataset: Union[Dataset, Tuple[Dataset, DatasetImages]], column_config: ColumnConfig,\n metric: metrics.Enum, holdout_dataset: Dataset = None,\n training_config: TrainingConfig = TrainingConfig(), **kwargs) -> 'Supervised':\n training_args = to_json(training_config)\n assert isinstance(training_args, Dict)\n training_args.update(to_json(column_config))\n\n if holdout_dataset:\n if isinstance(holdout_dataset, str):\n training_args['holdout_dataset_id'] = holdout_dataset\n else:\n training_args['holdout_dataset_id'] = holdout_dataset.id\n\n assert metric\n\n if isinstance(dataset, str):\n dataset_id = dataset\n elif isinstance(dataset, tuple):\n dataset_id = [d.id for d in dataset]\n else:\n dataset_id = dataset.id\n start_response = cls._start_usecase(project_id,\n name,\n dataset_id=dataset_id,\n data_type=data_type,\n training_type=training_type,\n metric=metric if isinstance(metric, str) else metric.value,\n **training_args)\n usecase = cls.from_id(start_response['_id'])\n print(usecase.training_type)\n events_url = '/{}/{}'.format(cls.resource, start_response['_id'])\n pio.client.event_manager.wait_for_event(usecase.resource_id,\n cls.resource,\n EventTuple('USECASE_VERSION_UPDATE', 'state', 'running',\n [('state', 'failed')]),\n specific_url=events_url)\n\n return usecase", "def create_generator(args):\n\n if args.dataset_type == 'csv':\n validation_generator = CSVGenerator(\n args.annotations,\n args.classes,\n image_min_side=args.image_min_side,\n image_max_side=args.image_max_side,\n config=args.config,\n shuffle_groups=False\n )\n else:\n raise ValueError('Invalid data type received: {}'.format(args.dataset_type))\n\n return validation_generator", "def accepts(self):\n return data_classes", "def create_nn_inputs_and_outputs(self, raw_data, is_training=None):\n raise NotImplementedError", "def create_port(self, body=None):\r\n return self.post(self.ports_path, body=body)", "def input_fn(params):\n batch_size = self.batch_size\n\n num_examples = len(features)\n\n d = tf.data.Dataset.from_tensor_slices({\n \"input_ids\":\n tf.constant(\n all_input_ids, shape=[num_examples, max_seq_len],\n dtype=tf.int32),\n \"input_mask\":\n tf.constant(\n all_input_mask,\n shape=[num_examples, max_seq_len],\n dtype=tf.int32),\n \"label_ids\":\n tf.constant(\n all_input_ids, shape=[num_examples, max_seq_len],\n dtype=tf.int32),\n \"label_mask\":\n tf.constant(\n all_input_mask,\n shape=[num_examples, max_seq_len],\n dtype=tf.int32),\n })\n\n if is_training:\n d = d.repeat()\n d = d.shuffle(buffer_size=100)\n\n d = d.batch(batch_size=batch_size)\n return d", "def __init__(self, data, dtype=None, map_func=None, name='Input'):\r\n self.name_scope = name\r\n # check input types\r\n assert isinstance(data, (np.ndarray, tf.Tensor, tuple, list)), \\\r\n '{}: Data must be from the following types: numpy array, tuple and list.'.format(self.name_scope)\r\n\r\n with tf.name_scope(name=name):\r\n # create placeholder and initialize the dataset\r\n self.placeholder = create_placeholder(data, dtype)\r\n self.feed_dict = {}\r\n for key, value in zip(self.placeholder, data):\r\n self.feed_dict[key] = value\r\n self.num_samples = data.shape[0] if isinstance(data, np.ndarray) else data[0].shape[0]\r\n self.dataset = tf.data.Dataset.from_tensor_slices(self.placeholder)\r\n # apply map_func\r\n if map_func is not None:\r\n self.dataset = self.dataset.map(map_func)\r\n self.iterator = None\r\n\r\n if FLAGS.VERBOSE:\r\n print('{} dataset output type is {}'.format(\r\n self.name_scope, self.dataset.output_types))\r\n print('{} dataset output shape is {}'.format(\r\n self.name_scope, self.dataset.output_shapes))", "def train_input_fn(df, batch_size=150):\n fts = df.drop(columns=['class'])\n labs = df.filter(items=['class']).values.astype(int)\n\n features = {k:list(v.values) for k,v in fts.items()}\n features = dict(features)\n x = fts.values\n x = np.array([[x]]).reshape((np.shape(x)[0], np.shape(x)[1], 1, 1))\n# x = tf.feature_column.input_layer(features, define_fc(),weight_collections=\"input_weights\", trainable=True)\n\n # Convert the inputs to a Dataset.\n dataset = tf.data.Dataset.from_tensor_slices({\"x_ph\":x,\"y_ph\":convert_to_one_hot(labs)})\n \n # Shuffle, repeat, and batch the examples.\n dataset = dataset.shuffle(1000).batch(batch_size).repeat()\n # Return the read end of the pipeline.\n return dataset.make_one_shot_iterator().get_next()", "def testInputTypeError(self, use_bias):\n conv1 = snt.SeparableConv1D(\n output_channels=3,\n channel_multiplier=1,\n kernel_shape=3,\n padding=snt.SAME,\n use_bias=use_bias,\n initializers=create_separable_constant_initializers(\n 1.0, 1.0, 1.0, use_bias))\n\n for dtype in (tf.uint32, tf.float64):\n x = tf.constant(np.ones([1, 5, 1]), dtype=dtype)\n err = \"Input must have dtype tf.float.*\"\n with self.assertRaisesRegexp(TypeError, err):\n conv1(x)" ]
[ "0.5783875", "0.5416487", "0.5152956", "0.51069313", "0.5068329", "0.48468444", "0.48388866", "0.48284078", "0.47701696", "0.47511247", "0.4733464", "0.47286028", "0.4718616", "0.46796426", "0.4669919", "0.46485522", "0.46478075", "0.46015683", "0.458119", "0.45772448", "0.45650214", "0.45145345", "0.45025486", "0.44969618", "0.4426902", "0.4414535", "0.43970084", "0.43791223", "0.43659", "0.4362328" ]
0.7779371
0
Create an output port that emits the given data type. >>> Port = Task.make_output_port(int) >>> int is Port({}).emits() True
def make_output_port(cls, data_class=None): class ReturnedOutputPort(OutputPort): """A subclass of InputPort accepting provided types.""" def emits(self): """Return the class emitted by the port.""" return data_class return ReturnedOutputPort
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def OutputPort(*args, **kw):\n return Port.make_shared(OutputPortInterface(*args, **kw))", "def CreateOutput(self, name=None, type=None, data=None):\n\n\n out = self._output_registry.Create(name, type, data)\n\n self._outputs.append(out)\n\n return out", "def port_out(self) -> int:\n return self.proto.port_out", "def build_model_output(cls, name='output'):\n return cls(name, PortDirection.OUTPUT, type=PortType.MODEL)", "def add_out_port(self, m: int, content: str, **opts) -> None:", "def set_output_type(self, output_type):\n if output_type is not None: self._output_type.value = output_type\n return self", "def build_data_output(cls, name='output', copy_input=None, schema=None):\n return cls(name, PortDirection.OUTPUT, type=PortType.DATA, copy_input=copy_input, schema=schema)", "def __init__(self, port):\n self.port = port\n self.action_type = 'output'", "def _get_output_type(self):\n return self.__output_type", "def _get_output_type(self):\n return self.__output_type", "def _get_output_type(self):\n return self.__output_type", "def _get_output_type(self):\n return self.__output_type", "def _get_output_type(self):\n return self.__output_type", "def _get_output_type(self):\n return self.__output_type", "def output_type(self):\n return self._output_type.value", "def output_node(self, port: int):\n return self._output_nodes_map[port]", "def get_number_of_output_ports(self):\n return 1", "def get_output(self, name='0'):\n if name not in self._outputs:\n raise ValueError(\"Invalid port name '{0}'\".format(name))\n return self._outputs[name]", "def generate_output_data(self):\n for socket_name, c in self.__taskobject.outputs.items():\n data = Data(self.__project, type=c['type'])\n if c['optional']:\n data.enable(False)\n self.__outputs[socket_name] = {'data': data, 'enable': False}\n else:\n data.enable(True)\n self.__outputs[socket_name] = {'data': data, 'enable': True}", "def _create_output_op(cls_name, output_ports, entry_block, bb_ret):\n\n # Determine if the body already has an output op.\n block_len = len(entry_block.operations)\n if block_len > 0:\n last_op = entry_block.operations[block_len - 1]\n if isinstance(last_op, hw.OutputOp):\n # If it does, the return from body_builder must be None.\n if bb_ret is not None and bb_ret != last_op:\n raise support.ConnectionError(\n f\"In {cls_name}, cannot return value from body_builder and \"\n \"create hw.OutputOp\")\n return\n\n # If builder didn't create an output op and didn't return anything, this op\n # mustn't have any outputs.\n if bb_ret is None:\n if len(output_ports) == 0:\n hw.OutputOp([])\n return\n raise support.ConnectionError(\n f\"In {cls_name}, must return module output values\")\n\n # Now create the output op depending on the object type returned\n outputs: list[Value] = list()\n\n # Only acceptable return is a dict of port, value mappings.\n if not isinstance(bb_ret, dict):\n raise support.ConnectionError(\n f\"In {cls_name}, can only return a dict of port, value mappings \"\n \"from body_builder.\")\n\n # A dict of `OutputPortName` -> ValueLike must be converted to a list in port\n # order.\n unconnected_ports = []\n for (name, port_type) in output_ports:\n if name not in bb_ret:\n unconnected_ports.append(name)\n outputs.append(None)\n else:\n val = support.get_value(bb_ret[name])\n if val is None:\n field_type = type(bb_ret[name])\n raise TypeError(\n f\"In {cls_name}, body_builder return doesn't support type \"\n f\"'{field_type}'\")\n if val.type != port_type:\n if isinstance(port_type, hw.TypeAliasType) and \\\n port_type.inner_type == val.type:\n val = hw.BitcastOp.create(port_type, val).result\n else:\n raise TypeError(\n f\"In {cls_name}, output port '{name}' type ({val.type}) doesn't \"\n f\"match declared type ({port_type})\")\n outputs.append(val)\n bb_ret.pop(name)\n if len(unconnected_ports) > 0:\n raise support.UnconnectedSignalError(cls_name, unconnected_ports)\n if len(bb_ret) > 0:\n raise support.ConnectionError(\n f\"Could not map the following to output ports in {cls_name}: \" +\n \",\".join(bb_ret.keys()))\n\n hw.OutputOp(outputs)", "def create_port(self, component):\n if self.fixed_size is not None and not self.array:\n raise ValueError(\n \"{}.{}: @{}port specified fixed_size but not array=True\".format(\n self, self.name,\n self.kind))\n ptype = self.get_port_type()\n return ptype(component, **self.data)", "def _build_packet_out(self, datapath, buffer_id, src_port, dst_port, data):\r\n actions = []\r\n if dst_port:\r\n actions.append(datapath.ofproto_parser.OFPActionOutput(dst_port))\r\n\r\n msg_data = None\r\n if buffer_id == datapath.ofproto.OFP_NO_BUFFER:\r\n if data is None:\r\n return None\r\n msg_data = data\r\n\r\n out = datapath.ofproto_parser.OFPPacketOut(\r\n datapath=datapath, buffer_id=buffer_id,\r\n data=msg_data, in_port=src_port, actions=actions)\r\n return out", "def make_port(self, options=mock_options):\n maker = self.port_maker(sys.platform)\n if not maker:\n return None\n\n port = maker(options=options)\n if hasattr(options, \"results_directory\"):\n port._options.results_directory = port.results_directory()\n return port", "def is_output(port):\n try:\n return port.mode == 'w'\n except Exception:\n return False", "def port(self, **kw):\n return self.portType(**kw)", "def get_port_type(self):\n raise NotImplementedError", "def create_running_output_stream(index):\n\n output = sounddevice.OutputStream(\n device=index,\n dtype=DATA_TYPE\n )\n output.start()\n return output", "def out_data(self, port: int) -> Optional[Any]:\n try:\n return copy(self.outputs[port])\n except:\n return None", "def get_output_task(self, name='0'):\n port = self.get_output(name).other\n if port is None:\n return None\n return port.task", "def send_on_output_port_change(self):\n return self._send_on_output_port_change" ]
[ "0.67926675", "0.58766013", "0.5834365", "0.57057595", "0.5663366", "0.5648713", "0.5592889", "0.550751", "0.54847336", "0.54847336", "0.54847336", "0.54847336", "0.54847336", "0.54847336", "0.54614824", "0.5394179", "0.53873235", "0.53818834", "0.53586745", "0.5345994", "0.5332621", "0.5279388", "0.52666223", "0.5261394", "0.52436656", "0.52030766", "0.5178116", "0.51628906", "0.51555806", "0.514558" ]
0.7136983
0
Load collector command file.
def load_collector_command_file(cmd_type, filename): assert cmd_type in COMMAND_TYPES, 'Invalid command type "%s"' % cmd_type if cmd_type in CONFIG_TYPES: cmd_filename = cmd_type + '.yaml' file_descr = CONFIG_TYPES[cmd_type] elif cmd_type in VOTING_LIST_TYPES: cmd_filename = None file_descr = VOTING_LIST_TYPES[cmd_type] elif cmd_type == 'user': assert cmd_type == 'user' cmd_filename = 'user.json' file_descr = 'user managment command' # load content from file config = load_cmd_file_content(cmd_type, cmd_filename, filename, file_descr) # FIXME don't validate voters list. there are some errors # in validation that need to be fixed in the future. if cmd_type == 'voters': return config # validate config file log.info('Validating %s', file_descr) try: config = config_validator.validate_config(config, cmd_type) except ValueError as err: log.error(err) return except schematics.exceptions.DataError as data_error: _log_config_validation_errors(data_error.errors) return log.info('Files in %s package are valid', file_descr) return config
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_load(self):\n command = constituencies.Command()\n command.handle('load', silent=True)", "def _load_command_dict(self, path=None):", "def do_load(self, line):\n cmd_args = io.parse_cmd_args(line, io.load_cmd_pattern)\n if cmd_args:\n success = self.manager.load(**cmd_args)\n if success:\n self.console_print(\"Yippee! load successful!\", settings.INFO_FORMAT)\n else:\n self.console_print(\"Sorry, the data could not be loaded from file.\", settings.ERROR_FORMAT)\n else:\n self.console_print(settings.COMMMAND_ARGS_ERROR_MSG, settings.ERROR_FORMAT)", "def load_cli():\n args=IO()\n\n if(args.command is None):\n logging.error('Please provide the appropriate input. Enter \"python -m packman -h\" for more details.')\n exit()\n\n logging.basicConfig(stream=args.logfile)\n\n if(args.pdbid is not None):\n molecule.download_structure(args.pdbid, save_name=args.filename.split('.')[0], ftype=args.filename.split('.')[1])\n\n try:\n extension = args.filename.split('.')[-1]\n mol = molecule.load_structure(args.filename,ftype=extension)\n except:\n logging.warning(\"The filename provided does not appear to have a format extension.\")\n mol = molecule.load_structure(args.filename)\n \n if(args.command == 'hinge'):\n hinge_cli(args,mol)\n elif(args.command == 'hdanm'):\n hdanm_cli(args,mol)\n elif(args.command == 'entropy'):\n entropy_cli(args,mol)\n elif(args.command == 'dci'):\n dci_cli(args,mol)\n\n return True", "def load(self):\n\n self.commands = {\n # Usual text commands (e.g. \"/echo 123\")\n 'user': {},\n 'owner': {\n 'load': self.load,\n 'modprobe': self.modprobe,\n 'rmmod': self.rmmod\n },\n # Modules for bot's reaction to a different message types\n 'text': {},\n 'photo': {},\n 'audio': {},\n 'video': {},\n 'sticker': {},\n 'voice': {}\n }\n\n for file in os.listdir('modules'):\n if file.endswith('.py'):\n command_type, command = file.split('_', 1)\n self.modprobe(self, command[:-3])", "def help_load(self):\n print(LOAD)", "def load_command(command_path):\n module_path, class_name = command_path.rsplit(\".\", 1)\n module = importlib.import_module(module_path)\n return getattr(module, class_name)()", "def __init__(self, name, config, handlers):\r\n # Get Class Collector config\r\n try:\r\n class_config = config['collectors']['CMDCollector']\r\n except KeyError:\r\n class_config = None\r\n super(CMDCollector, self).__init__(name, config, handlers)\r\n if class_config:\r\n self.config.merge(class_config)\r\n\r\n # vars = self.config['env_vars']\r\n # if not isinstance(vars, list):\r\n # vars = vars.split()\r\n # for var in vars:\r\n # key, param = var.split(':')\r\n # os.putenv(key, self.config[param])\r", "def _load_commands(self):\n\n entry_points = pkg_resources.iter_entry_points(\n config.PROVIDER_EP_NAMESPACE)\n for entry_point in entry_points:\n self.logger.debug('found provider %r', entry_point.name)\n self._commands[entry_point.name] = entry_point.load()", "def cmdload(dataset_id, v4):\n cmd_loader = CmdLoader(dataset_id, v4)\n cmd_loader.upload_data_to_florence()", "def help_load(self):\n help_str = \"\"\"Runs commands in script at file or URL.\n\n Usage: load [file_path]\n\n optional argument:\n file_path - a file path or URL pointing to a script (default: value stored in `default_file_name` parameter)\n\nScript should contain one command per line, just like command would be typed in console.\"\"\"\n self.stdout.write(\"{}\\n\".format(help_str))", "async def tool_load(self, ctx, *, cog: str):\n\n try:\n self.bot.load_extension(cog)\n except Exception as e:\n await zb.bot_errors(ctx,sp.format(e))\n else:\n await ctx.send('**`SUCCESS`**')", "def load(path):\n pass", "def load(args):\n subprocess.check_call([\"/bin/launchctl\", \"load\"] + values.get(args))", "def _load(self, directory):\n pass", "def load(cls, name):\n try:\n return importlib.import_module(cls._plugins[name])\n except Exception as err:\n print(\"** could not load command [%s]:\\n%s\" % (name, err))", "def execute(self, command: LoadCommand):\n command.execute()", "def load(self):\n pass", "def load(self):\n pass", "def load(self):\n pass", "def load(self):\n pass", "def load_commands():\n register_plugin(configure_client_details)\n register_plugin(search_venues)", "def load(self, path):\n pass", "def load(self, path):\n pass", "def load(self):\n cmd = ('ssh-add', self.path)\n p = Popen(cmd, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr)\n p.wait()", "async def load(self) -> None:\n pass", "def load_cmd_file(self, filepath):\n try:\n conf = yaml.load(open(filepath), Loader=yamlloader.ordereddict.CLoader)\n except (IOError, yaml.YAMLError) as err:\n raise CLGConfigError('(%s) unable to load file: %s' % (filepath, err))\n\n for param, value in conf.items():\n setattr(self, param.upper(), replace_paths(value))", "def parse_load_cmd(self, line):\n self.E_str = \"parse_load_cmd\"\n # Split the line by whitespace and get the values of any variables\n line, any_vars = self.find_vars_in_str(line)\n words = line.split()\n words = self.fix_words(words)\n\n # Read the data\n _, fpath, dtype, _, var_name = words\n fpath = gen_parse.rm_quotation_marks(fpath)\n fpath = gen_io.get_abs_path(fpath)\n\n # Create the variable object and save it\n Loaded_Data = f_dicts.load_fncs[dtype](fpath)\n\n # Grab the metadata and create a new variable\n metadata = {'file_type': dtype}\n for key in Loaded_Data.metadata:\n if key not in metadata: metadata[key] = Loaded_Data.metadata[key]\n\n if words[3] == \"as\" or var_name not in self.variables:\n self.set_var(var_name, {dtype: Loaded_Data}, metadata)\n elif words[3] == 'into' and var_name in self.variables:\n self.load_var_into(Loaded_Data, var_name, metadata)\n\n Var = getattr(self, var_name)\n Var.metadata.setdefault('data_loaded', []).append(dtype)", "def cli():\n fire.Fire(fetch_rss_file)", "def load(ctx):\n if not is_owner(ctx.update):\n return\n global cmds\n cmds.load_ext(ctx.args[0], ctx.update)" ]
[ "0.6637995", "0.6602988", "0.6421098", "0.5958425", "0.5942859", "0.58570313", "0.5780593", "0.57392687", "0.5670419", "0.5638143", "0.560007", "0.5599712", "0.5581758", "0.5579189", "0.55661297", "0.556542", "0.5560651", "0.5529598", "0.5529598", "0.5529598", "0.5529598", "0.55235267", "0.5523479", "0.5523479", "0.5490148", "0.5488374", "0.54742074", "0.5467406", "0.54351366", "0.5421465" ]
0.71159786
0
Check collector command file signature.
def check_cmd_signature(cmd_type, filename): log.debug('Checking command file %s (%s) signature', filename, cmd_type) # detect trust root file trust_container_filepath = os.path.join(CONFIG['active_config_files_path'], 'trust.bdoc') if cmd_type == 'trust' and not os.path.exists(trust_container_filepath): trust_container_filepath = filename try: open(trust_container_filepath) except OSError as err: err.strerror = "Trust root not found: %s" % trust_container_filepath raise err # execute verifier command cmd = ['ivxv-container-verifier', '-trust', trust_container_filepath, filename] proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) if proc.returncode: verifier_errors = { 64: 'Command was used incorrectly', 65: 'Failed to open container', 66: 'Input file did not exist or was not readable', 74: 'Failed read trust root', } err_msg = verifier_errors.get(proc.returncode, 'Unhandled error') raise subprocess.SubprocessError(': '.join([err_msg, proc.stderr])) # parse command output and create signatures list all_signatures = [] for line in proc.stdout.strip().split('\n'): if not re.match(r'.+,.+,[0-9]{11} ', line): raise LookupError('Invalid signature line: %s' % line) signer, timestamp_str = line.split(' ') timestamp = datetime.datetime.strptime( timestamp_str, RFC3339_DATE_FORMAT_WO_FRACT).timestamp() all_signatures.append([timestamp, signer, line]) all_signatures = sorted(all_signatures) # check signers authorization for trust root config if cmd_type == 'trust': log.debug('Check signers authorization against trust root config') config = load_collector_command_file(cmd_type, filename) trusted_signers = config.get('authorizations', []) authorized_signatures = [ [signature, 'admin'] for timestamp, signer, signature in all_signatures if signer in trusted_signers] return authorized_signatures, all_signatures # detect permission for command type if cmd_type == 'technical': permission = PERMISSION_TECH_CONF elif cmd_type in CONFIG_TYPES or cmd_type in VOTING_LIST_TYPES: permission = PERMISSION_ELECTION_CONF else: assert cmd_type == 'user' permission = PERMISSION_USERS_ADMIN # check signers authorization for other config files log.debug( 'Check signers authorization against collector management database') authorized_signatures = [] db = IVXVManagerDb() for timestamp, signer, signature in all_signatures: try: roles = db.get_value('user/{}'.format(signer)) except KeyError: log.debug('No database record for signer %s', signer) continue authorized_signatures += [[signature, role] for role in roles.split(',') if permission in ROLES[role]['permissions']] db.close() return authorized_signatures, all_signatures
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def check_sig(self):\n check_sig(self.path)\n dsc = self.get_dsc()\n if dsc is not None:\n check_sig(dsc)", "def checksignature(self):\n if(self.name=='ORBIT'): return\n if(self.ctpnum==0): return\n cmd=\"CheckSignature(\"+self.board+\",\"+self.signature+\",\"+self.ctpnum+\")\"\n output=self.vb.io.execute(cmd,log=\"out\",applout=\"<>\")\n print \"input checksignature: \",output\n #self.signatureM=", "def check_sig(filename):\n pipe = Popen([\"gpg\", \"--verify\", filename], stderr=PIPE)\n pipe.stderr.read()\n status = pipe.wait()\n if status != 0:\n raise BadSignature('%s is not properly signed' % filename)", "def check_args():\n schema = Schema({\n 'FOLDREC': Use(open, error='FOLDREC file should be readable'),\n 'CLUSTAL': Use(open, error='CLUSTAL file should be readable'),\n 'CCMPRED': Use(open, error='CCMPRED file should be readable'),\n '--metafold': Use(open, error='METAFOLD_FILE should be readable'),\n '--nb_pdb': And(Use(int), lambda n: 1 <= n <= 405,\n error='--nb_pdb=NUM should be integer 1 <= N <= 405'),\n '--dssp': Use(open, error='dssp/mkdssp should be readable'),\n '--dope': Use(open, error='dope file should be readable'),\n '--benchmark': Use(open, error='BENCHMARK_FILE should be readable'),\n '--cpu': And(Use(int), lambda n: 0 <= n <= cpu_count(),\n error='--cpus=NUM should be integer 1 <= N <= ' + str(cpu_count())),\n # The output PATH is created (if not exists) at the end of the program\n # so we skip the check.\n object: object})\n try:\n schema.validate(ARGUMENTS)\n except SchemaError as err:\n exit(err)", "def verify_signature(self, inputs, signature):\n pass", "def verify_signature(self, inputs, signature):\n pass", "def Mime_CheckCmds():\n status = True\n cmdcheck = [\"xdg-mime\"]\n for cmd in cmdcheck:\n if not shutil.which(cmd):\n print(\"\\nError, ensure command {0} is installed.\".format(cmd))\n status = False\n return status", "def test_command_verify():\n wozardry.parse_args([\"verify\", kValid1])\n wozardry.parse_args([\"verify\", kValid2])", "def _verify_arguments(self):\n # if self.options.action == \"create\":\n # if self.options.encrypt_payload and not self.options.payload_secret:\n # self.parser.error('A secret must be supplied with --payload-secret option when the --encrypt-payload option is in use.')\n pass", "def check_arguments(self):\n self.check_num_arguments()\n self.are_readable_files(self.args)", "def run_command_check(self):\n pass", "def check_argv():\n parser = argparse.ArgumentParser(description=__doc__.strip().split(\"\\n\")[0], add_help=False)\n parser.add_argument(\"segment_fn\", type=str, help=\"pickled segmentation file\")\n if len(sys.argv) == 1:\n parser.print_help()\n sys.exit(1)\n return parser.parse_args()", "def check_arguments(self):\n ## only four test operation is permitted, if given anything apart from this, then it should print error message\n if (self.args.snap is False and self.args.snapcheck is False and self.args.check is False and self.args.diff is False and self.args.version is False):\n self.logger.error(colorama.Fore.RED +\n \"Arguments not given correctly, Please refer help message\", extra=self.log_detail)\n self.parser.print_help()\n sys.exit(1)\n\n if(((self.args.snap is True and (self.args.pre_snapfile is None or self.args.file is None)) or\n (self.args.snapcheck is True and self.args.file is None) or\n (self.args.check is True and self.args.file is None)) and \n (self.args.testfiles is None or self.args.hostname is None)\n ):\n self.logger.error(colorama.Fore.RED +\n \"Arguments not given correctly, Please refer help message\", extra=self.log_detail)\n self.parser.print_help()\n sys.exit(1)\n if self.args.diff is True:\n if (self.args.pre_snapfile is not None and os.path.isfile(self.args.pre_snapfile)) and (\n self.args.post_snapfile is not None and os.path.isfile(self.args.post_snapfile)):\n comp = Comparator()\n comp.compare_diff(\n self.args.pre_snapfile,\n self.args.post_snapfile,\n None)\n sys.exit(1)\n else:\n if (self.args.file is None) and (\n self.args.testfiles is None or self.args.hostname is None):\n self.parser.print_help()\n sys.exit(1)", "def verify_request_signature(req_info: StatusResponse) -> None:\n if not req_info.signature_check(req_info.xmlstr):\n raise ValueError(_(\"Message signature verification failure\"))", "def check_commands(self):\n pass", "def validate_args(cmd_args):\n valid = cmd_args.bag is not None\n\n if not valid:\n print('Must specify a bag file')\n\n if valid:\n for bag_file in cmd_args.bag:\n valid = os.path.isfile(bag_file)\n if not valid:\n print('Invalid bag file: ' + bag_file)\n break\n\n if valid:\n \"\"\" 1. If info is requested, that is the only argument allowed.\n 2. Topics and output files may be specified.\n 3. Topics may be specified. Output file names will be autogenerated.\n 4. Stats may be requested.\n \"\"\"\n ops_requested = [False] * 3\n ops_requested[0] = cmd_args.info\n ops_requested[1] = (cmd_args.topic is not None)\n ops_requested[2] = cmd_args.stats\n\n valid = (sum(ops_requested) == 1)\n if not valid:\n print('Must specify either bag info, a topic and output file, or statistics')\n\n if valid and cmd_args.out_file is not None:\n valid = (len(cmd_args.out_file) == len(cmd_args.bag) * len(cmd_args.topic))\n if not valid:\n print('Number of output files must be enough for bags and topics passed in')\n\n return valid", "def verify_args(opts):\n special_opts = (opts.initialize, opts.sigtool, opts.scanner)\n list_opts = (opts.listUnable, opts.listMoved, opts.listInfected, opts.listFailed)\n if any(list_opts):\n return\n special_opts_flags = [\"-g/--sigtool\", \"-i/--initialize\", \"-s/--scan\"]\n total = 0\n for opt in special_opts:\n if opt:\n total += 1\n if total == 0:\n log.error(\n \"must pass a required argument to begin, required arguments can be found in the help menu (penneav -h)\"\n )\n sys.exit(1)\n if total != 1:\n log.error(\n \"can only pass a total of 1 of the required arguments at a time ({}). You have passed a total of {}. \"\n \"Please verify your arguments and rerun Penne.\".format(\n \", \".join(special_opts_flags), total\n )\n )\n sys.exit(1)\n if opts.sigtool and opts.filename is None:\n log.error(\"must supply a filename with sigtool to generate the signature\")\n sys.exit(1)\n if opts.threadNum > 30:\n log.warning(\"max amount of threads is 30 (you passed {}), defaulting down to 30 threads\".format(opts.threadNum))\n opts.threadNum = 30\n print(WELCOME_BANNER)", "def verify(self):\n token = \"mytoken\" # set from wx server\n ll = []\n signature = self.get_argument(\"signature\", \"<none>\")\n ll.append(self.get_argument(\"timestamp\", \"<none>\"))\n ll.append(self.get_argument(\"nonce\", \"<none>\"))\n ll.append(token)\n ll.sort()\n m = hashlib.sha1()\n m.update(\"\".join(ll).encode(\"ascii\"))\n digest = m.hexdigest()\n\n if signature != digest:\n print(\"signature not match, discard this msg!\")\n return False\n else:\n print(\"signature match, got a wechat msg!\")\n return True", "def validate_output(self):\n if self.dimension == 2:\n required = SEGMENT_GEO_SIG | self.output_signature\n for rays in [\n self.active_rays,\n self.finished_rays,\n self.stopped_rays,\n self.dead_rays\n ]:\n if bool(rays):\n sig = set(rays.keys())\n if not (sig >= required):\n raise RuntimeError(\n f\"Optical engine failed output signature check. System \" \n f\"signature is {sig}, but needed {required}.\"\n )", "def verify_signature(signed_file_path, output_file_path):\n cmd = [\"gpg\", \"-d\"]\n keyring_path = configuration.get_gpg_public_keyring_path()\n\n # if a keyring is specified in the conf, used it, else use default one\n if keyring_path != \"\":\n cmd += [GPG_NO_DEFAULT_KEYRING_OPTION, GPG_KEYRING_ARG, keyring_path]\n cmd += [\"--output\", output_file_path, signed_file_path]\n\n # temporary workaround for the omi/gpg bug causing gpg to create a .gpg folder in the wrong home dir\n # only apply the workaround for oms installation\n env = None\n if \"nxOMSAutomationWorkerResource\" in os.path.abspath(__file__):\n env = os.environ.copy()\n env[\"HOME\"] = \"/var/opt/microsoft/omsagent/run\"\n\n proc = subprocessfactory.create_subprocess(cmd=cmd, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n stdout, stderr = proc.communicate()\n\n if proc.poll() == 0:\n tracer.log_debug_trace(\"Signature is valid.\")\n return True\n\n tracer.log_sandbox_job_runbook_signature_validation_failed(stderr)\n return False", "def verify(args):\n # assume that the arguments are not valid and prove otherwise\n verified_arguments = False\n # TOP-LEVEL VERIFIED:\n # both a file and a directory were specified and a command is not given\n # pylint: disable=bad-continuation\n if is_valid_file_and_directory(args) and (\n not is_command_ancillary(args)\n and not is_valid_command(args)\n and not is_valid_commits(args)\n ):\n # track how many of the sub-arguments separately verified\n file_verified = []\n # VERIFIED: correct check for existence of a file in a directory\n if is_valid_exists(args):\n # verified_arguments = True\n file_verified.append(True)\n # VERIFIED: correct check for comments with language in a file in a directory\n if is_valid_comments(args) and is_valid_language(args):\n # verified_arguments = True\n file_verified.append(True)\n # VERIFIED: correct check for paragraphs in a file in a directory\n if is_valid_paragraphs(args):\n # verified_arguments = True\n file_verified.append(True)\n # VERIFIED: correct check for words in a file in a directory\n if is_valid_words(args):\n # verified_arguments = True\n file_verified.append(True)\n # VERIFIED: correct check for fragments in a file in a directory\n if is_valid_fragment(args):\n # verified_arguments = True\n file_verified.append(True)\n # VERIFIED: correct check for line count of a file in a directory\n if is_valid_count(args):\n # verified_arguments = True\n file_verified.append(True)\n # VERIFIED: only one of prior valid options specified\n if file_verified.count(True) == 1:\n verified_arguments = True\n # TOP-LEVEL VERIFIED:\n # no file or directory details were specified and a command given\n # pylint: disable=bad-continuation\n elif is_valid_command(args) and (\n not is_valid_file_or_directory(args)\n and not is_file_ancillary(args)\n and not is_valid_commits(args)\n ):\n # track how many of the sub-arguments separately verified\n command_verified = []\n # VERIFIED: correct check for existence of a file in a directory\n if is_valid_executes(args):\n command_verified.append(True)\n # verified_arguments = True\n # VERIFIED: correct check for fragments in a file in a directory\n if is_valid_fragment(args):\n # verified_arguments = True\n command_verified.append(True)\n # VERIFIED: correct check for line count of a file in a directory\n if is_valid_count(args):\n # verified_arguments = True\n command_verified.append(True)\n # VERIFIED: only one of prior valid options specified\n if command_verified.count(True) == 1:\n verified_arguments = True\n # TOP-LEVEL VERIFIED:\n # no file or directory details were specified or a command given\n # and the argument is a request to check the count of Git commits\n # pylint: disable=bad-continuation\n elif is_valid_commits(args) and (\n not is_valid_file_or_directory(args)\n and not is_file_ancillary(args)\n and not is_valid_command(args)\n and not is_command_ancillary(args)\n ):\n verified_arguments = True\n return verified_arguments", "def test_sign_file_unsupported_format(dummy_command, tmp_path, capsys):\n # FIXME: I'm not sure how to manufacture this in practice.\n dummy_command.tools.subprocess.run.side_effect = mock_codesign(\n \"unsupported format for signature\"\n )\n\n # Sign the file\n dummy_command.sign_file(\n tmp_path / \"base_path\" / \"random.file\",\n identity=\"Sekrit identity (DEADBEEF)\",\n )\n\n # An attempt to codesign was made\n dummy_command.tools.subprocess.run.assert_has_calls(\n [\n sign_call(\n tmp_path,\n tmp_path / \"base_path\" / \"random.file\",\n entitlements=False,\n ),\n ],\n any_order=False,\n )\n\n # The console includes a warning about not needing a signature.\n assert \"... no signature required\\n\" in capsys.readouterr().out", "def check_specific_signatures(self):\r\n\r\n test1 = re.search(r'История операций по дебетовой карте за период', self.bank_text, re.IGNORECASE)\r\n # print(f\"{test1=}\")\r\n\r\n if not test1:\r\n raise exceptions.InputFileStructureError(\"Не найдены паттерны, соответствующие выписке\")", "def verify_apk_signature(self):\n verify.verify_apk_sig(self.apk_path) # raises CryptoVerificationError\n print(' - APK signature is valid')", "def check_num_arguments(self):\n if len(self.args) != 2:\n self.cli_parser.error(\"Please provide paths to an \"\n \"interactions file and an annotations file.\")", "def show_command(args):\n for fn in args.files:\n ext = os.path.splitext(fn)[1].lower()\n if ext == '.csr':\n cmd = ['openssl', 'req', '-in', fn, '-text']\n elif ext == '.crt':\n cmd = ['openssl', 'x509', '-in', fn, '-text']\n else:\n die(\"Unsupported file: %s\", fn)\n subprocess.check_call(cmd)", "def test_verify(self):\n self.backup(u\"full\", u\"testfiles/various_file_types\", options=[])\n self.verify(u'testfiles/various_file_types/executable', file_to_verify=u'executable', options=[])", "def test_validargs(clickrunner):\n for args in maincli.valid_args:\n result = clickrunner.invoke(maincli.entrypoint, args)\n assert result.exit_code == 2\n assert \"Missing command\" in result.output", "def check_arguments(self):\n # only four test operation is permitted, if given anything apart from this,\n # then it should print error message.\n if not (\n (self.args.file is None)\n and ((self.args.testfiles is None or self.args.hostname is None))\n ):\n action = None\n if self.set_action_cmd(action) is not None:\n # the operation is checked in above function\n return None\n\n self.logger.error(\n colorama.Fore.RED\n + \"Arguments not given correctly, Please refer help message\",\n extra=self.log_detail,\n )\n self.parser.print_help()\n sys.exit(1)", "def verify(self):\n \n # Check non-optional args\n pList = ['basePath', 'dateStart', 'dateStop','sensor']\n for p in pList:\n if not hasattr(self, p):\n self.showUsage()\n raise '\\nMissing keyword arg: %s.\\n' % p\n \n if not self.isValidBasePath():\n raise '\\nbasePath (%s) does not exist.\\n' % self.basePath\n\n if not isValidPimsDateString(self.dateStart):\n raise '\\ndateStart (%s) is not valid\\n' % self.dateStart\n else:\n self.uStart = stringTimeToUnix(self.dateStart)\n\n if not isValidPimsDateString(self.dateStop):\n raise '\\ndateStop (%s) is not valid\\n' % self.dateStop\n else:\n self.uStop = stringTimeToUnix(self.dateStop)" ]
[ "0.67507535", "0.66069126", "0.6045818", "0.60454977", "0.60318244", "0.60318244", "0.5943962", "0.59437245", "0.5939048", "0.59087485", "0.5906215", "0.58670527", "0.5840456", "0.58291215", "0.58183795", "0.5771363", "0.5729034", "0.5722215", "0.5658076", "0.5641391", "0.56270534", "0.56200504", "0.5605175", "0.55895895", "0.5562344", "0.55619645", "0.5557779", "0.55375355", "0.55315465", "0.55261725" ]
0.7288576
0
Returns the default featurestore. If the user did not specify the featurestore, it defaults to the project's featurestore
def _default_featurestore(self, featurestore): if featurestore is None: featurestore = fs_utils._do_get_project_featurestore() return featurestore
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_default_datastore(self):\n try:\n return self.client.list_datastores()[0]['datastore']\n except VMwareError as e:\n raise VMwareBackendError(e)", "def get_default_store_name_for_current_request():\r\n store_name = 'default'\r\n\r\n # see what request we are currently processing - if any at all - and get hostname for the request\r\n hostname = get_current_request_hostname()\r\n\r\n # get mapping information which is defined in configurations\r\n mappings = getattr(settings, 'HOSTNAME_MODULESTORE_DEFAULT_MAPPINGS', None)\r\n\r\n # compare hostname against the regex expressions set of mappings\r\n # which will tell us which store name to use\r\n if hostname and mappings:\r\n for key in mappings.keys():\r\n if re.match(key, hostname):\r\n store_name = mappings[key]\r\n return store_name\r\n\r\n return store_name", "def get_default():\n backend, opts = parse_default()\n assert backend is not None\n return load_backend(backend, opts)", "def get_default_backend():\n return __default_backend", "def get_store(self, store_name: str) -> Any:\n pass", "def default():\n return DefaultGeothermal.default()", "def get_featurestore(\n self,\n ) -> Callable[\n [featurestore_service.GetFeaturestoreRequest],\n Awaitable[featurestore.Featurestore],\n ]:\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if \"get_featurestore\" not in self._stubs:\n self._stubs[\"get_featurestore\"] = self.grpc_channel.unary_unary(\n \"/google.cloud.aiplatform.v1beta1.FeaturestoreService/GetFeaturestore\",\n request_serializer=featurestore_service.GetFeaturestoreRequest.serialize,\n response_deserializer=featurestore.Featurestore.deserialize,\n )\n return self._stubs[\"get_featurestore\"]", "def get_store(store_name: str):\n return store_handler.get_store(store_name)", "def get_mixed_stores(mixed_setting):\n return mixed_setting[\"default\"][\"OPTIONS\"][\"stores\"]", "def get_store(datafile=None):\n global _store\n if _store is None:\n _store = LocalStore(datafile=datafile)\n return _store", "def get_first_system_store(self):\n\t\ttry:\n\t\t\treturn self.stores[1]\n\t\texcept IndexError:\n\t\t\traise SafeException(_(\"No system stores have been configured\"))", "def get_default_label_store(self, scene: SceneConfig) -> LabelStoreConfig:\n raise NotImplementedError()", "def datastore_type(self) -> Optional[pulumi.Input[Union[str, 'StorageSettingStoreTypes']]]:\n return pulumi.get(self, \"datastore_type\")", "def feature_set(self) -> Optional[pulumi.Input['OrganizationFeatureSet']]:\n return pulumi.get(self, \"feature_set\")", "def datastore(self) -> Optional[pulumi.Input[str]]:\n return pulumi.get(self, \"datastore\")", "def log_store(self) -> Optional[str]:\n return pulumi.get(self, \"log_store\")", "def _get_store(self):\n return self._store", "def data_store(self) -> pulumi.Input['DataStoreInfoBaseArgs']:\n return pulumi.get(self, \"data_store\")", "def data_store_type(self) -> Optional[pulumi.Input[Union[str, 'StorageSettingStoreTypes']]]:\n return pulumi.get(self, \"data_store_type\")", "def get_store(self, subset: str) -> AbstractStore:\n return self.get_source(subset).get_driver().store", "def data_store_type(self) -> pulumi.Input[Union[str, 'DataStoreTypes']]:\n return pulumi.get(self, \"data_store_type\")", "def data_store_type(self) -> pulumi.Input[Union[str, 'DataStoreTypes']]:\n return pulumi.get(self, \"data_store_type\")", "def data_store_type(self) -> pulumi.Input[Union[str, 'DataStoreTypes']]:\n return pulumi.get(self, \"data_store_type\")", "def get_store(hass: HomeAssistant) -> dict[str, Any] | None:\n return hass.data.get(DATA_STORE)", "def get_default_model():\n models = PluginLoader.get_available_models()\n return 'original' if 'original' in models else models[0]", "def feature_set(self) -> pulumi.Output[Optional['OrganizationFeatureSet']]:\n return pulumi.get(self, \"feature_set\")", "def default_model():\n return \"teenytweetynet\"", "def datastore_type(self) -> Optional[str]:\n return pulumi.get(self, \"datastore_type\")", "def getDefaultStorage(pfn):\n\n defaultSE = \"\"\n\n # parse\n match = re.findall('^[^:]+://([^:/]+)',pfn)\n if len(match) != 1:\n tolog(\"!!WARNING!!2990!! Could not parse default storage from %s\" % (pfn))\n else:\n defaultSE = match[0]\n\n return defaultSE", "def _get_default_path(self):\n return os.path.join(cfg.DATA_DIR, 'visual_genome')" ]
[ "0.6456016", "0.62015706", "0.6144767", "0.61073357", "0.59432316", "0.5925258", "0.588503", "0.58394617", "0.5833727", "0.5825112", "0.5804936", "0.5802867", "0.5674981", "0.5647042", "0.56290233", "0.5609647", "0.5603026", "0.5592466", "0.55848753", "0.5467452", "0.5405066", "0.5405066", "0.5405066", "0.53590554", "0.53575546", "0.53547585", "0.53355634", "0.5334653", "0.5319088", "0.52802855" ]
0.907442
0
>>> binary2bytes('00000001') b'\\x01' >>> binary2bytes('00000011') b'\\x03' >>> binary2bytes('11110000') b'\\xf0' >>> binary2bytes('1111000010000000') b'\\xf0\\x80'
def binary2bytes(inputBin): #check if length is divisible by 8 if len(inputBin) % 8 == 0: byteList = [] for i in range(0, len(inputBin), 8): #convert each 8 bits in int byteList += [int(inputBin[i:i+8], 2)] #convert the list to bytes return bytes(byteList) #recursive to send back with a length divisable by 8 else: return binary2bytes(inputBin.rjust(len(inputBin) + 8-len(inputBin) % 8, "0"))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_right_binary_to_bytes(self):\n binary_string = '00000101000110100010100011010010'\n byte_string = utils.binary_to_bytes(binary_string, little_endian=False)\n expected_byte_string = b'\\x05\\x1A\\x28\\xD2'\n self.assertEqual(byte_string, expected_byte_string)", "def bytes2binary(inputBytes):\r\n result = 0\r\n for i in inputBytes:\r\n result = result * 256 + int(i)\r\n return bin(result)[2:].rjust(len(inputBytes*8), \"0\")", "def boole_list_to_bytes(bit_message:list):\n b_number = 0\n byte_list = []\n one_cool_byte = 0\n for item in bit_message:\n one_cool_byte <<= 1\n if item:\n one_cool_byte += 1\n b_number += 1\n if b_number == 8:\n byte_list.append(one_cool_byte)\n b_number = 0\n one_cool_byte = 0\n return bytes(byte_list).rstrip(b\"\\x00\") # return byte string", "def to_binary_string(x):\n return \"{0:b}\".format(x)", "def test_from_binary_bits_style(self):\n self.assertResult('[0001 0000]', b8('[0001 0000]'))", "def _to_bytes(value, length, dummy, _unhexlify=_unhexlify):\n fmt = '%%0%dx' % (2 * length,)\n return _unhexlify(fmt % value)", "def test_from_binary_bits_style(self):\n self.assertResult('[0001]', b4('[0001]'))", "def s2b (s):\n return s.encode()", "def convert_to_binary(num):\n return '{0:b}'.format(num)", "def binary(message: str) -> bitarray:\n binary_message = bitarray()\n byte_message = bytes(message, encoding=\"ascii\")\n binary_message.frombytes(byte_message)\n return binary_message", "def utf8_to_binary() :\n dico_binary, comp_seq, file_comp = read_compressed_file()\n \n #for each items of the sequence convert it in binary string on 8 bits\n bin_str = \"\"\n for value in comp_seq:\n code = ord(value)\n bin_str += '{:08b}'.format(code)\n \n #remove the number of zeroes added \n \n added = int(dico_binary[\"add\"])\n #if the padding is equal to 0, don't cut anathing from the sequence\n if added == 0: \n bin_seq = bin_str\n else: \n bin_seq = bin_str[:-added]\n \n return bin_seq, dico_binary, comp_seq, file_comp", "def get_binary(string):\r\n # Use special logic for NULL_STRING to avoid errors\r\n if string == NULL_STRING:\r\n return \"00000000\"\r\n # Otherwise, gives the binary representation of UTF-8 characters\r\n return \"\".join(\"{:08b}\".format(d) for d in bytearray(string, \"utf-8\"))", "def s2b(s):\n return s.encode('utf-8')", "def _byte_to_bits(cls, byte):\n try:\n return '{0:08b}'.format(byte)\n except AttributeError:\n # python < 2.6, so we must do this ourselves\n return cls._bin_backport(byte)", "def test_from_binary_0b_style(self):\n self.assertResult('[0001]', b4('0b0001'))\n with self.assertRaises(OverflowError):\n b4('0b10001')", "def translate_to_binary(command):\r\n int_command = int(command)\r\n binary_command = bin(int_command)[2:]\r\n missing_bits = CMD_LEN - len(binary_command)\r\n cmd_prefix = missing_bits * str(0)\r\n binary_command = str(cmd_prefix) + str(binary_command)\r\n return binary_command + \"\\n\"", "def hexstr_to_bytes(data: str) -> bytes:\n byte_array = array('B', (int(data[index:index + 2], 16) for index in range(0, len(data), 2)))\n return byte_array.tobytes()", "def bits_to_byte(bits):\n return sum([int(bits[pos]) << (7 - pos)\n for pos in range(len(bits))])", "def bytify(binary):\n\tbytes = [0,0,0,0]\n\ti = 3\n\twhile binary:\n\n\t\tbytes[i] = binary&255\n\t\tbinary >>= 8\n\t\ti -= 1 \n\treturn bytes", "def repr_as_binary(value):\n b = bin(value)[2:]\n return b.zfill(len(b) + -len(b) % 8)", "def a2b(a):\n return binascii.unhexlify(a)", "def int_to_bytes(num):\n if not is_natural(num, include_zero=True):\n raise ValueError(\"%s is not a non-negative integer.\")\n hexed = \"%x\" % num\n # align hexadecimal string to byte boundaries\n if len(hexed) % 2 == 1:\n hexed = '0%s' % hexed\n return hexed.decode('hex')", "def rawbytes(s):\n outlist = []\n for cp in s:\n num = ord(cp)\n if num < 256:\n outlist.append(pack(\"b\", num))\n elif num < 65536:\n outlist.append(pack(\">H\", num))\n else:\n b = (num & 0xFF0000) >> 16\n H = num & 0xFFFF\n outlist.append(pack(\">bH\", b, H))\n return b\"\".join(outlist)", "def __convertToBinaryStr(self, hex_str): \n final_bi_str = ''\n for c in hex_str:\n bi_str = bin(int(c, 16))[2:]\n if len(bi_str) != 4:\n bi_str = (4 - len(bi_str)%4)*'0' + bi_str\n final_bi_str += bi_str\n \n # sanity check\n if not(len(final_bi_str)%4 == 0 and (len(hex_str)*4) == len(final_bi_str)):\n print('Problem in hex2bi conversion')\n \n return final_bi_str", "def hexstr_to_bytes(input_str: str) -> bytes:\n if input_str.startswith(\"0x\") or input_str.startswith(\"0X\"):\n return bytes.fromhex(input_str[2:])\n return bytes.fromhex(input_str)", "def TransferHexToBinary(value):\n value = RemoveWhiteSpace(value)\n return \"\".join(map(chr,[int(h+l,16) for h,l in zip(value[::2],value[1::2])]))", "def rawbytes(s):\r\n outlist = []\r\n for cp in s:\r\n num = ord(cp)\r\n if num < 255:\r\n outlist.append(struct.pack('B', num))\r\n elif num < 65535:\r\n outlist.append(struct.pack('>H', num))\r\n else:\r\n b = (num & 0xFF0000) >> 16\r\n H = num & 0xFFFF\r\n outlist.append(struct.pack('>bH', b, H))\r\n return b''.join(outlist)", "def ba(hexstr_or_int):\n try:\n t1 = hexstr_or_int.lower()\n t2 = \"\".join([c if c.isalnum() else \" \" for c in t1])\n t3 = t2.split(\" \")\n out = bytearray()\n for bstr in t3:\n if bstr[0:2] == \"0x\":\n bstr = bstr[2:]\n if bstr != \"\":\n l = len(bstr)\n if(l % 2):\n bstr = \"0\"+bstr\n l+=1\n out += bytearray.fromhex(bstr)\n\n except:\n #seems arg is not a string, assume it is a int\n try:\n out = Utils.int_to_ba(hexstr_or_int)\n except:\n # seems arg is not an int, assume it is a list\n try:\n out = bytearray(hexstr_or_int)\n except:\n raise ValueError()\n return out", "def byte(b):\n if isinstance(b, basestring):\n if len(b) == 1:\n return ord(b)\n raise ValueError()\n elif isinstance(b, int):\n if 0 <= b < 256:\n return b\n raise ValueError()\n raise TypeError()", "def int2bin(integer):\n try:\n binary = bin(integer)\n return binary[2:] # string slicing to elimininate the prefix '0b'\n\n except TypeError:\n print('An integer should be provided as input')" ]
[ "0.7444598", "0.71815115", "0.6991683", "0.6945767", "0.6843568", "0.6810538", "0.6780177", "0.67500544", "0.6743914", "0.6733812", "0.6729651", "0.6696337", "0.6691725", "0.66798335", "0.6650505", "0.6643075", "0.66386986", "0.6614789", "0.66003025", "0.6540794", "0.65194076", "0.65019035", "0.6492309", "0.6482552", "0.64677143", "0.645903", "0.64582974", "0.64314306", "0.6427829", "0.6404024" ]
0.73619443
1
>>> bin_xor('1011','0000') '1011' >>> bin_xor('1','0000') '0001' >>> bin_xor('1101','1011') '0110' >>> bin_xor('10101010','01010101') '11111111'
def bin_xor(inputBin1, inputBin2): result = "" #We set each binary input to the same length by adding zeroes on the left to the smaller one if len(inputBin1) > len(inputBin2): inputBin2 = inputBin2.rjust(len(inputBin1), "0") else: inputBin1 = inputBin1.rjust(len(inputBin2), "0") #we check if each bit is equal for id in range(len(inputBin1)): if inputBin1[id] == inputBin2[id]: result += "0" else : result += "1" return result
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def xor(a, b):", "def bitwise_xor(a, b):\n\n result = \"\"\n for i in range(0, len(a)):\n result += str(int(a[i]) ^ int(b[i]))\n return result", "def test_bit_xor(self):\n value = bytearray([1])\n ops = [bitwise_operations.bit_xor(self.test_bin_ones, 0, 8, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 1 + [1] * 4)\n assert bins[self.test_bin_ones] == expected_result", "def xor_compare(bin1, bin2):\n return '{0:0{1}b}'.format(int(bin1,2) ^ int(proper_key(bin2, len(bin1)), 2), len(bin1))", "def bitwise_xor(lhs, rhs):\n return _make.bitwise_xor(lhs, rhs)", "def xor(it):\n return 0 if it[0]==it[1] else 1", "def _XOR(integer1, integer2):\n _checkInt(integer1, minvalue=0, description='integer1')\n _checkInt(integer2, minvalue=0, description='integer2')\n\n return integer1 ^ integer2", "def logical_xor(a, b):\n return bool(a) ^ bool(b)", "def strings_xor(ints1, ints2):\n bin_xor = [a ^ b for a, b in zip(ints1, ints2)]\n return ''.join([str(chr(a)) for a in bin_xor])", "def sxor(s1, s2):\n return ''.join(chr(ord(a) ^ ord(b)) for a, b in zip(s1, s2))", "def _xor_str(self,s,t):\n \treturn \"\".join(chr(ord(a)^ord(b)) for a,b in zip(s,t))", "def xorbits(num1,num2):\n thingstoadd = []\n for i in range(31):\n bit1=setbit(num1,i)\n bit2=setbit(num2,i)\n bit1=shiftleft(bit1,31 - i)\n bit2=shiftleft(bit2,31 - i)\n bitsum=add(bit1,bit2)\n bitsum=shiftright(bitsum,31 - i)\n thingstoadd.append(bitsum)\n return sum(thingstoadd)", "def bitwise_xor(self):\n register = self.return_middle_registers(self.opcode)\n self.registers[register[0]] = (\n self.registers[register[0]] ^ self.registers[register[1]])\n logger.info(\"Bitwise XOR on V{} and V{} for {}\".format(\n register[0],\n register[1],\n self.registers[register[0]]))", "def xor_bytes(a, b):\n return bytes(i^j for i, j in zip(a, b))", "def xor_bytestring(a_b, b_b):\n return bytes(a ^ b for a, b in zip(a_b, b_b))", "def _xor_bytes(a: bytes, b: bytes) -> bytes:\n assert len(a) == len(b)\n res = bytearray()\n for i in range(len(a)):\n res.append(a[i] ^ b[i])\n return bytes(res)", "def xor(b1, b2):\n\n b = bytearray(len(b1))\n for i in range(len(b1)):\n b[i] = b1[i] ^ b2[i]\n return b", "def fixed_xor(a, b):\n if len(a) != len(b):\n raise ValueError(f\"Expected a and b to be the same length; got {len(a)} vs {len(b)}\")\n\n return bytes([a[i] ^ b[i] for i in range(len(a))])", "def xor_(l1, l2):\n return np.bitwise_xor(l1,l2)", "def test_bit_xor_multiple_bytes_value_unchanged(self):\n value = bytearray([0])\n ops = [bitwise_operations.bit_xor(self.test_bin_zeroes, 7, 8, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 5)\n assert bins[self.test_bin_zeroes] == expected_result", "def f_xor(*args):\n f = Xor(*args).factor()\n return f if f in B else f.factor()", "def string_xor(s1, s2):\n\txor_str = []\n\tfor i in range(len(s1)):\n\t\tif s1[i] == s2[i]:\n\t\t\txor_str.append('0')\n\t\telse:\n\t\t\txor_str.append('1')\n\treturn ''.join(xor_str)", "def test_bit_xor_with_policy(self):\n value = bytearray([0])\n bit_policy = {\n \"bit_write_flags\": aerospike.BIT_WRITE_UPDATE_ONLY,\n }\n ops = [bitwise_operations.bit_xor(self.test_bin_zeroes, 7, 8, 1, value, bit_policy)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 5)\n assert bins[self.test_bin_zeroes] == expected_result", "def XOR(string1, string2):\r\n return \"\".join(chr(ord(s1) ^ ord(s2)) for s1, s2 in zip(string1, string2))", "def bXor(byte_string_1,byte_string_2):\n return bytes([b1 ^ b2 for b1, b2 in zip(byte_string_1, byte_string_2)])", "def _blockXOR(a, b):\n\tif len(a) != len(b):\n\t\traise ValueError(\"expected to strings with same length\")\n\tres = []\n\tfor i in xrange(len(a)):\n\t\tres.append(chr(ord(a[i]) ^ ord(b[i])))\n\treturn \"\".join(res)", "def logical_xor(lhs, rhs):\n return _make.logical_xor(lhs, rhs)", "def single_char_xor(input_bytes, char_value):\n keystring = struct.pack(\"B\", char_value)*len(input_bytes)\n #we reuse the bXor we implemented in problem #2\n return bXor(input_bytes, keystring)", "def xor_strings(s,t):\n return \"\".join(chr(ord(a)^ord(b)) for a,b in zip(s,t))", "def encrypt_single_byte_xor(value, inputbyte):\r\n intIntputbyte = int(inputbyte)\r\n return bytes([b ^ intIntputbyte for b in bytes(value)])" ]
[ "0.8044245", "0.7827002", "0.7490464", "0.7386411", "0.7358006", "0.7249659", "0.7243797", "0.72187597", "0.7168043", "0.71600723", "0.71484417", "0.7135558", "0.70728177", "0.7046469", "0.7040437", "0.7027976", "0.70228106", "0.70034254", "0.6998678", "0.69902486", "0.6981926", "0.6969949", "0.6965154", "0.6928011", "0.6913079", "0.6874179", "0.6841787", "0.6819901", "0.68074167", "0.68031543" ]
0.787626
1
>>> create_DES_subkeys('0001001100110100010101110111100110011011101111001101111111110001') ['000110110000001011101111111111000111000001110010', '011110011010111011011001110110111100100111100101', '010101011111110010001010010000101100111110011001', '011100101010110111010110110110110011010100011101', '011111001110110000000111111010110101001110101000', '011000111010010100111110010100000111101100101111', '111011001000010010110111111101100001100010111100', '111101111000101000111010110000010011101111111011', '111000001101101111101011111011011110011110000001', '101100011111001101000111101110100100011001001111', '001000010101111111010011110111101101001110000110', '011101010111000111110101100101000110011111101001', '100101111100010111010001111110101011101001000001', '010111110100001110110111111100101110011100111010', '101111111001000110001101001111010011111100001010', '110010110011110110001011000011100001011111110101']
def create_DES_subkeys(key): # permutation with the original key fullKey = bit_permutation(key, PC1) #we split the key into right and left part lprev, rprev = fullKey[:28], fullKey[28:] nFinalBlock = [] #We now proceed through 16 iterations, for 1<=n<=16 for n in range (16): lPart, rPart = left_shift_rot(lprev, key_shifts[n]), left_shift_rot(rprev, key_shifts[n]) lprev, rprev = lPart, rPart nFinalBlock += ["".join([lPart, rPart])] #We now form the keys Kn, for 1<=n<=16, by applying the following permutation table to each of the concatenated pairs rPart, lPart nPrimeFinalBlock = [] for n in range(16): nPrimeFinalBlock += [bit_permutation(nFinalBlock[n], PC2)] return nPrimeFinalBlock
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def generate_keys(cls, des_key: str) -> List[list]:\n\n keys = []\n des_key = cls.string_to_bit_array(des_key)\n # Apply the initial Permutation on the key\n des_key = cls.permutation_expand(des_key, Tables.PC_1_TABLE)\n # Split it in to LEFT,RIGHT\n left, right = cls.n_split(des_key, 28)\n # Apply the 16 rounds\n for i in range(16):\n # Apply the shift associated with the round (not always 1)\n left, right = cls.shift(left, right, Tables.SHIFT_ARRAY[i])\n # Merge them\n tmp = left + right\n # Apply the Permutation to get the Ki\n keys.append(cls.permutation_expand(tmp, Tables.PC_2_TABLE))\n return keys", "def keyGen(key):\n def leftShift(keyBitList):\n \"\"\"Perform a circular left shift on the first and second five bits\"\"\"\n shiftedKey = [None] * KeyLength\n shiftedKey[0:9] = keyBitList[1:10]\n shiftedKey[4] = keyBitList[0]\n shiftedKey[9] = keyBitList[5]\n return shiftedKey\n\n # Converts input key (integer) into a list of binary digits\n keyList = [(key & 1 << i) >> i for i in reversed(range(KeyLength))]\n permKeyList = [None] * KeyLength\n for index, elem in enumerate(P10table):\n permKeyList[index] = keyList[elem - 1]\n shiftedOnceKey = leftShift(permKeyList)\n shiftedTwiceKey = leftShift(leftShift(shiftedOnceKey))\n subKey1 = subKey2 = 0\n for index, elem in enumerate(P8table):\n subKey1 += (128 >> index) * shiftedOnceKey[elem - 1]\n subKey2 += (128 >> index) * shiftedTwiceKey[elem - 1]\n return (subKey1, subKey2)", "def _base64_to_der_keylist(base64_keylist: List[str], keyidv2_list: List[int]) -> List[Tuple[bytes, Optional[int]]]:\n res = []\n for idx, entry in enumerate(base64_keylist):\n keyidv2 = keyidv2_list[idx] if idx < len(keyidv2_list) else None\n res.append((base64.b64decode(entry), keyidv2))\n return res", "def generate_keys(self):\n self.keys = []\n key = string_to_bit_array(self.passwd)\n key = self.permutation(key, CP_1) # Perform initial permutation on the key\n g, d = split_into_n(key, 28) # Split into g (LEFT) & d (RIGHT)\n for i in range(16): # Apply the 16 rounds\n g, d = self.shift(g, d, ROUND_KEY_SHIFT[i]) # Shift the key according to the round\n tmp = g + d # Merge them\n self.keys.append(self.permutation(tmp, CP_2)) # Perform the permutation to get the Ki", "def gen_keys():", "def _key_array(key):\n key = map(ord, key)[:16]\n initial = map(ord, \"6170383452343567\")\n while len(key) < len(initial):\n key.append(initial[len(key)])\n return key", "def GetSubkeys(self):", "def gen_decomp_keys(self, decomp_list):\n for key in decomp_list:\n if isinstance(key, tuple) or isinstance(key, list):\n yield key[0]\n else:\n yield key", "def __init__(self, key):\n\n def keys(key, num_rounds):\n \"\"\"Yields the permuted key bitstring for i = 1..num_rounds\"\"\"\n C, D = key[:28], key[28:]\n # Rounds are 1-indexed, so shift array over by one\n left_shifts = [None, 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1]\n for i in range(1, num_rounds + 1):\n # Negate each rotation to rotate left.\n C, D = rotate(C, -left_shifts[i]), rotate(D, -left_shifts[i])\n yield self.permute(C + D, self._CD_permutation)\n\n self.key = list(bits_of(key, 64))\n # Permute the key. The permutation discards the parity bits...\n self.key = self.permute(self.key, self._key_permutation)\n self.number_of_rounds = 16\n # A list of the 16 keys K1 .. K16, shifted over by one to allow 1-indexing.\n self.keys = [None] + list(keys(self.key, self.number_of_rounds))", "def getKeySchedule(key):\n temp_keys = 44 * [None]\n key_schedule = byte2array(key)\n for i in range(len(key_schedule)):\n if i%4==0:\n temp = key_schedule[i]\n for j in range(0,len(temp_keys),4):\n temp_keys[j] = temp\n \n temp = [temp[-1]] + temp[:3] \n \n if i%4==1:\n temp = key_schedule[i]\n for j in range(1,len(temp_keys),4):\n temp_keys[j] = temp\n \n temp = [temp[-1]] + temp[:3] \n\n \n if i%4==2:\n temp = key_schedule[i]\n for j in range(2,len(temp_keys),4):\n temp_keys[j] = temp\n \n temp = [temp[-1]] + temp[:3] \n\n \n if i%4==3:\n temp = key_schedule[i]\n for j in range(3,len(temp_keys),4):\n temp_keys[j] = temp\n \n temp = [temp[-1]] + temp[:3] \n\n\n key_schedule = temp_keys\n\n return key_schedule", "def _prepare_encryption_table():\n seed = 0x00100001\n crypt_table = {}\n\n for i in range(256):\n index = i\n for j in range(5):\n seed = (seed * 125 + 3) % 0x2AAAAB\n temp1 = (seed & 0xFFFF) << 0x10\n\n seed = (seed * 125 + 3) % 0x2AAAAB\n temp2 = (seed & 0xFFFF)\n\n crypt_table[index] = (temp1 | temp2)\n\n index += 0x100\n\n return crypt_table", "def rc4_ksa(key_bits: Bits):\n key = bytearray(key_bits.tobytes())\n w = 256\n r = list(range(w))\n keylength = len(key)\n\n j = 0\n for i in range(w):\n j = (j + r[i] + key[i % keylength]) % w\n r[i], r[j] = r[j], r[i]\n\n return r", "def input_to_hash(self, keys):\n basic_keys = []\n for i, key in enumerate(keys):\n s = ''\n #print(max(key), min(key))\n for val in key:\n s += \"{:04x}\".format(val)\n basic_keys.append(s)\n return basic_keys", "def __initialSigningKeys(self) -> None:\n seedStr = '0' * 31\n seedNum = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']\n seedList = []\n for i in range(15):\n seed = seedStr + seedNum[i]\n seedList.append(seed.encode('utf-8'))\n\n for seed in seedList:\n self.signingKeysList.append(SigningKey(seed))\n log.info(\"15 signing keys have been generated successfully\")", "def create_key ():", "def _make_keys(key_def):\r\n keys = []\r\n labels = []\r\n\r\n # no keys? return an empty string\r\n if len(key_def) == 0:\r\n return \"\"\r\n\r\n for i in range(1, 12 + 1):\r\n try:\r\n key, label = i, key_def[i]\r\n if label.startswith('-'):\r\n key = '0'\r\n label = label[1:]\r\n else:\r\n key = '1'\r\n except KeyError:\r\n key = '0'\r\n label = HIEW_EMPTY_KEY_LABEL\r\n\r\n t = len(label)\r\n if t > HIEW_KEY_LABEL_LEN:\r\n label = label[0:HIEW_KEY_LABEL_LEN]\r\n else:\r\n label += ' ' * (HIEW_KEY_LABEL_LEN - t)\r\n\r\n keys.append(key)\r\n labels.append(label)\r\n\r\n return ''.join(keys) + HEM_FNKEY_DELIMITER + ''.join(labels)", "def sub_key(dirname):\n return SUB_PREFIX + dirname", "def strDec(data, *keys):\n decStr = \"\"\n for s in [data[i: i+16] for i in range(0, len(data), 16)]:\n intByte = [int(x) for x in '{:064b}'.format(int(s, 16))]\n for key in keys[::-1]:\n for b in getKeyBytes(key)[::-1]:\n intByte = dec(intByte, b)\n decStr += byteToString(intByte)\n return decStr", "def generate_key( length=10, char_set='all' ):\n\n if char_set == 'digits':\n char_list = string.digits\n elif char_set == 'letters':\n char_list = string.lowercase[:26] + string.uppercase[:26]\n else:\n char_list = good_chars\n\n char_list_limit = len( char_list ) - 1\n\n key = ''\n i = 0\n while i < length:\n key = string.join( [ key , char_list[ random.randint( 0, char_list_limit ) ] ], '' )\n i = i + 1\n\n return key", "def generate_keys(self):\n\n\t\tmin_ext = 1 << self.size_ext - 1\n\t\tmax_ext = 1 << self.size_ext\n\t\t\n\t\t\t\n\t\t# step 1 : chose random primary numbers p and q\n\t\tn = generate_prime(self.min_bound,self.max_bound)\n\t\tself._p = n\n\t\tn = generate_prime(self.min_bound,self.max_bound)\n\t\twhile(n == self._p):\n\t\t\tn = generate_prime(self.min_bound,self.max_bound)\n\t\tself._q = n\n\n\t\t#step 2 : compute n = pq\n\t\tself.n = self._p * self._q\n\n\t\t#step 3 : compute phi(n)\n\t\tself._phi = (self._p - 1) * (self._q - 1)\n\n\t\t#step 4 : chose the exponent\n\t\textension = randint(min_ext,max_ext) << math.ceil(math.log2(self.D))\n\t\textension = extension + self.D\n\t\twhile (gcd(self._phi,n) != 1):\n\t\t\textension = randint(min_ext,max_ext) << math.ceil(math.log2(self.D))\n\t\tself._d = extension\n\n\t\t#step 5 : compute d (private key)\n\t\tself.e = euclide_algorithm(self._d, self._phi)[\"U\"] % self._phi\n\n\t\tprint(\"p = \", self._p)\n\t\tprint(\"q = \", self._q)\n\t\tprint(\"d = \", self._d)", "def apply_compression(pc2_table, keys_56bits):\n keys_48bits = \"\"\n for index in pc2_table:\n keys_48bits += keys_56bits[index - 1]\n return keys_48bits", "def dh_get_key():\n G = EcGroup()\n priv_dec = G.order().random()\n pub_enc = priv_dec * G.generator()\n return (G, priv_dec, pub_enc)", "def calculate_cipher(self, sub_keys, text):\n X = text\n K = sub_keys\n\n step = ['0'] * 14\n for i in range(0, ROUNDS - 1):\n step[0] = (self.mul(X[0], int(K[i][0], 2)))\n step[1] = (self.add(X[1], int(K[i][1], 2)))\n step[2] = (self.add(X[2], int(K[i][2], 2)))\n step[3] = (self.mul(X[3], int(K[i][3], 2)))\n step[4] = (self.xor(step[0], step[2]))\n step[5] = (self.xor(step[1], step[3]))\n step[6] = (self.mul(step[4], int(K[i][4], 2)))\n step[7] = (self.add(step[5], step[6]))\n step[8] = (self.mul(step[7], int(K[i][5], 2)))\n step[9] = (self.add(step[6], step[8]))\n step[10] = (self.xor(step[0], step[8]))\n step[11] = (self.xor(step[2], step[8]))\n step[12] = (self.xor(step[1], step[9]))\n step[13] = (self.xor(step[3], step[9]))\n # [print(\"Step \"+str(y)+\": \"+str(hex(int(step[y]))) + \"({0})\".format(int(step[y]))) for y in range(14)]\n\n if self.log:\n print(\"Round [\" + str(i + 1) + \"] HEX input \" + ' '.join([str(hex(int(x))) for x in X]))\n print(\"Round [\" + str(i + 1) + \"] HEX sub-key \" + ' '.join([str(hex(int(k, 2))) for k in K[i]]))\n X = [step[10], step[11], step[12], step[13]] # Swap step 12 and 13\n if self.log:\n print(\"Round [\" + str(i + 1) + \"] HEX output \" + ' '.join(\n [str(hex(int(x))) for x in X]) + \"\\n---------------\")\n\n \"\"\"X1 * K1\n X2 + K2\n X3 + K3\n X4 * K4\"\"\"\n X = [step[10], step[12], step[11], step[13]]\n result = [self.mul(X[0], int(K[ROUNDS - 1][0], 2)), self.add(X[1], int(K[ROUNDS - 1][1], 2)),\n self.add(X[2], int(K[ROUNDS - 1][2], 2)), self.mul(X[3], int(K[ROUNDS - 1][3], 2))]\n\n temp = [str(hex(int(x)))[2:] for x in result]\n temp = ['0' * (4 - len(x)) + x for x in temp]\n cipher = ''.join([x for x in temp])\n\n if self.log:\n print(\"Round [\" + str(ROUNDS - 0.5) + \"] HEX input \" + ' '.join([str(hex(int(x))) for x in X]))\n print(\"Round [\" + str(ROUNDS - 0.5) + \"] HEX sub-key \" + ' '.join(\n [str(hex(int(k, 2))) for k in K[ROUNDS - 1]]))\n print(\"Round [\" + str(ROUNDS - 0.5) + \"] HEX output \" + ' '.join([str(hex(int(x))) for x in result])\n + \"\\n---------------\")\n print(\"Final Cipher/Decipher: \" + cipher + \"\\n---------------\")\n\n return cipher # Hex string", "def _deriv_keys(self, key):\n prom2abs = self._prom2abs\n abs2prom = self._abs2prom\n\n DERIV_KEY_SEP = self._DERIV_KEY_SEP\n\n # derivative could be tuple or string, using absolute or promoted names\n if isinstance(key, tuple):\n of, wrt = key\n else:\n of, wrt = key.split(DERIV_KEY_SEP)\n\n # if promoted, will map to all connected absolute names\n abs_of = [of] if of in abs2prom else prom2abs[of]\n if wrt in prom2abs:\n abs_wrt = [prom2abs[wrt]][0]\n else:\n abs_wrt = [wrt]\n\n abs_keys = ['%s%s%s' % (o, DERIV_KEY_SEP, w) for o, w in itertools.product(abs_of, abs_wrt)]\n\n prom_of = of if of in prom2abs else abs2prom[of]\n if wrt in abs2prom:\n prom_wrt = abs2prom[wrt]\n else:\n prom_wrt = wrt\n\n prom_key = (prom_of, prom_wrt)\n\n return abs_keys, prom_key", "def prepKey(key, length):\r\n keyString = \"\"\r\n while len(keyString) < length:\r\n for char in key:\r\n if len(keyString) < length:\r\n keyString += char\r\n return keyString", "def __gen_keys__(self):\n if self.seed == b'':\n self.seed = urandom(self.seed_size)\n\n n_prev = Node(hash=hash_factory(data=bytes(self.seed)).digest())\n self.keys.insert(0, n_prev)\n\n for i in range(1, self.l + 1):\n n = Node(hash=hash_factory(data=bytes(n_prev.hash)).digest())\n self.keys.insert(0, n)\n n_prev = n\n\n # Add the decoy nodes as parents of pair nodes.\n # The pair nodes will _always_ be the right child of the decoy nodes.\n for i in range(2, self.l + 1, 2):\n n_pair = self.keys[i] # type: Node\n n_impair_prev = self.keys[i-1] # type: Node\n n_pair.parent = Node(hash=bytes(n_impair_prev.hash))\n n_pair.parent.right_child = n_pair", "def subkey_list(self):\n if self.subkey_number() == 0:\n raise RegistryStructureDoesNotExist(\"NKRecord has no subkey list at 0x%x\" % (self.offset()))\n\n subkey_list_offset = self.abs_offset_from_hbin_offset(self.unpack_dword(0x1C))\n\n d = HBINCell(self._buf, subkey_list_offset, self)\n id_ = d.data_id()\n\n if id_ == b\"lf\":\n l = LFRecord(self._buf, d.data_offset(), self)\n elif id_ == b\"lh\":\n l = LHRecord(self._buf, d.data_offset(), self)\n elif id_ == b\"ri\":\n l = RIRecord(self._buf, d.data_offset(), self)\n elif id_ == b\"li\":\n l = LIRecord(self._buf, d.data_offset(), self)\n else:\n raise ParseException(\"Subkey list with type 0x%s encountered, but not yet supported.\" %\n (binascii.hexlify(id_).decode('ascii')))\n\n return l", "def generate_key(self, size):\n key = bytearray()\n for i in range(0,size):\n random_byte = ord(os.urandom(1))\n key.append(random_byte)\n return key", "def create_keys(i):\n sk = elgamal.create_sk()\n secret_keys.append(sk)\n\n keys = [0, 0]\n\n keys[x[i]] = elgamal.gen(sk)\n keys[1 - x[i]] = elgamal.o_gen()\n\n public_keys.append(keys)", "def __generate_key_from_list_of(self, list_of_keys):\r\n list_of_keys = list(list_of_keys)\r\n list_of_keys.sort()\r\n return \",\".join(list_of_keys)" ]
[ "0.69109523", "0.6327981", "0.59114325", "0.58670264", "0.5672433", "0.5617016", "0.56074584", "0.5488417", "0.54729164", "0.5424147", "0.54045707", "0.5400378", "0.539857", "0.53741616", "0.53487986", "0.5323746", "0.53177774", "0.5278533", "0.52746445", "0.5209882", "0.51777315", "0.5099774", "0.50635874", "0.50509083", "0.5031544", "0.50272053", "0.50118166", "0.50086725", "0.5007503", "0.5002198" ]
0.79006463
0
Makes sure that for each covariate name (from model) an observable (from dataframe) exists.
def _check_covariate_dict( self, covariate_dict, covariate_names, observables): # Check that model needs covariates if len(covariate_names) == 0: return None # If no mapping is provided, construct default mapping if covariate_dict is None: # Assume trivial map covariate_dict = {cov: cov for cov in covariate_names} # Check that covariate name map is valid for cov in covariate_names: if cov not in list(covariate_dict.keys()): raise ValueError( 'The covariate <' + str(cov) + '> could not be identified ' 'in the covariate name map.') mapped_name = covariate_dict[cov] if mapped_name not in observables: raise ValueError( 'The covariate <' + str(mapped_name) + '> could not be ' 'identified in the dataframe.') return covariate_dict
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_createNewObs():\n\n # check type\n assert isinstance(newObs, pd.DataFrame)\n\n # check if there are exactly 5 songs has listen count and 3 columns in the generated df\n assert newObs.query(\"listen_count!=0\").shape == (5,3)\n\n # check if the number of songs in the song_df is the same as the generated new df\n assert len(svd.song_df.song_id.unique()) == len(newObs.song_id.unique())", "def _check_covariate_values(self, covariate_names):\n # Check that model needs covariates\n if len(covariate_names) == 0:\n return None\n\n for name in covariate_names:\n # Mask covariate values\n mask = self._data[self._obs_key] == self._covariate_dict[name]\n temp = self._data[mask]\n\n for _id in self._ids:\n # Mask values for individual\n mask = temp[self._id_key] == _id\n temp2 = temp.loc[mask, self._value_key].dropna()\n\n if len(temp2) != 1:\n covariate = self._covariate_dict[name]\n raise ValueError(\n 'There are either 0 or more than 1 value of the '\n 'covariate %s for ID %s. '\n 'Exactly one covariate value '\n 'has to be provided for each ID.' % (covariate, _id)\n )", "def check_all_objects_have_names(self):\n for entity in crest.get_all_crest_objects(self.model):\n assert entity._name is not None, f\"Object {entity} has no name\"", "def observables(self, _prediction, parameters):\n if _prediction not in self.predictions:\n raise RuntimeError('Cannot create observables for unknown set of predictions: \\'{}\\''.format(_prediction))\n\n prediction = self.predictions[_prediction]\n options = eos.Options(**prediction['global_options'])\n observables = [eos.Observable.make(\n o['name'],\n parameters,\n eos.Kinematics(**(o['kinematics'] if 'kinematics' in o else {})),\n options\n ) for o in prediction['observables']]\n\n if None in observables:\n unknown_observables = set()\n for p, o in zip(prediction['observables'], observables):\n if o is None:\n unknown_observables.add(p['name'])\n raise RuntimeError('Prediction \\'{}\\' contains unknown observable names: {}'.format(_prediction, unknown_observables))\n\n return observables", "def test_covars_datapoint_observation_int_fails(tmp_observe_class,\n covar_details_mapped_covar_mapped_names_tmp_observe_class,\n covariate_str, error_msg, monkeypatch, pythontestvers):\n\n # special case for python version 3.7 (handled via new keyword argument to pytest)\n if pythontestvers == \"3.7\" and covariate_str not in [\"1, a, 2, 3\", \"\"]:\n # removes the '' from the error message\n error_msg = error_msg[:-2]\n\n # device for torch tensor definitions\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n # covariates to sample\n init_guess = [1.1, 2.2, 200, -1.7]\n initial_guess = torch.tensor([init_guess], dtype=torch.double, device=device)\n\n # temp class to execute the test\n cls = tmp_observe_class\n\n # set proposed_X attribute (required for method to work)\n cls.initial_guess = initial_guess\n cls.proposed_X = initial_guess\n cls.train_X = initial_guess\n cls.model = {\"covars_proposed_iter\": 1,\n \"covars_sampled_iter\": 1}\n cls.covar_details = covar_details_mapped_covar_mapped_names_tmp_observe_class[0]\n cls.covar_mapped_names = covar_details_mapped_covar_mapped_names_tmp_observe_class[1]\n cls.sorted_pandas_columns = covar_details_mapped_covar_mapped_names_tmp_observe_class[2]\n cls.x_data = pd.DataFrame(columns=[\"covar0\", \"covar1\", \"covar2\", \"covar3\"])\n cls.x_data.loc[0] = init_guess\n\n # monkeypatch\n def mock_input(x): # mock function to replace 'input' for unit testing purposes\n return covariate_str\n monkeypatch.setattr(\"builtins.input\", mock_input)\n\n # covariate kwargs is set to None so input-based method is used\n kwarg_covariates = None\n\n #with pytest.raises(ValueError) as e:\n with pytest.raises(Exception) as e:\n # run the method\n cls._get_covars_datapoint(covars=kwarg_covariates)\n assert str(e.value) == error_msg", "def verify_zoos(self):\n self.check_dataset_duplicate_ids(self.zoos)", "def need_ovo(model_name):\n return (model_name == 'logistic') or (model_name == 'sgd')", "def check_observatory(self):\n assert self.observatory in ALL_OBSERVATORIES, \\\n \"Invalid observatory \" + repr(self.observatory) + \" in \" + repr(self.filename)", "def condition(self, observations):\n unknown_vars = set(observations.keys()) - set(self.vs.keys())\n if unknown_vars != set():\n raise RuntimeError(\"Unknown variable '{0}'\".format(\n unknown_vars.pop()))\n self.vobs.update(observations)\n for name, value in observations.items():\n table = {(d,): 0 for d in self.vs[name].orig_domain}\n table[(value,)] = 1\n # Check if there is an existing factor that is only connected\n # to the observed variable. If that is the case, replace its\n # table by a new table corresponding to the observed value,\n # otherwise create a new factor with that table.\n found = False\n for fnode in self.fs:\n if len(fnode.variables) == 1 and fnode.variables[0] == name:\n fnode.table = table\n if not found:\n fnode = self.add_factor((name,), table)", "def checkModel(self, model):\n # TODO", "def check_objects_have_parents_and_are_not_referenced_twice(self):\n # logger.debug(\"ports:\")\n all_objs = crest.get_all_ports(self.model)\n # for o in all_objs:\n # print(o._name, o._parent)\n for obj in all_objs:\n assert all_objs.count(obj) == 1, f\"Port {obj._name} has been used multiple times\"\n assert obj._parent is not None, f\"Port {obj._name} has no parent definition\"\n\n # logger.debug(\"states:\")\n all_objs = crest.get_all_states(self.model)\n # for o in all_objs:\n # print(o._name, o._parent)\n for obj in all_objs:\n assert all_objs.count(obj) == 1, f\"State {obj._name} has been used multiple times\"\n assert obj._parent is not None, f\"State {obj._name} has no parent definition\"\n\n # logger.debug(\"updates:\")\n all_objs = crest.get_all_updates(self.model)\n # for o in all_objs:\n # print(o._name, o._parent)\n for obj in all_objs:\n assert all_objs.count(obj) == 1, f\"Update {obj._name} has been used multiple times\"\n assert obj._parent is not None, f\"Update {obj._name} has no parent definition\"\n\n # logger.debug(\"influences\")\n all_objs = crest.get_all_influences(self.model)\n # for o in all_objs:\n # print(o._name, o._parent)\n for obj in all_objs:\n assert all_objs.count(obj) == 1, f\"Influence {obj._name} has been used multiple times\"\n assert obj._parent is not None, f\"Influence {obj._name} has no parent definition\"\n\n # logger.debug(\"transitions:\")\n all_objs = crest.get_all_transitions(self.model)\n # for o in all_objs:\n # print(o._name, o._parent)\n for obj in all_objs:\n assert all_objs.count(obj) == 1, f\"Transition '{obj._name}' has been used multiple times\"\n assert obj._parent is not None, f\"Transition '{obj._name}' has no parent definition\"", "def consistency_checker(model,universals,existentials):\n universal_set=set(universals)\n existential_set=set(existentials)\n #Additionally to the universal and existential variables the model may\n #contain additional auxiliary variables -- e.g. for setting default values.\n #We consider these variables such as the existential variables.\n auxiliary_variables_in_model={abs(l) for clause in model for l in clause \n if (not abs(l) in universal_set) and (not abs(l) in existential_set)}\n existential_set = existential_set.union(auxiliary_variables_in_model)\n result, certificate = checkModelQBF(model, universal_set, existential_set)\n return result", "def _check_if_fitted(self):\n if self.covar_module is None:\n raise RuntimeError(\n \"Model has not been fitted. You need to call \"\n \"`fit_fully_bayesian_model_nuts` to fit the model.\"\n )", "def test_object_with_observables() -> None:\n system_name = \"Water900\"\n simulation_id_1 = \"NPT-lowT-lowP\"\n simulation_id_2 = \"NPT-highT-lowP\"\n system = database.system(system_name)\n parser = FlatfileParser()\n simulation_data_1 = parser.get_simulation_data(\n units=system.units,\n ensemble=system.ensemble(simulation_id_1),\n system=system.system_data,\n kinetic_ene_file=system.observable_flat_file(\n simulation_id_1, \"kinetic_energy\"\n ),\n potential_ene_file=system.observable_flat_file(\n simulation_id_1, \"potential_energy\"\n ),\n total_ene_file=system.observable_flat_file(simulation_id_1, \"total_energy\"),\n volume_file=system.observable_flat_file(simulation_id_1, \"volume\"),\n )\n simulation_data_1_copy = parser.get_simulation_data(\n units=system.units,\n ensemble=system.ensemble(simulation_id_1),\n system=system.system_data,\n kinetic_ene_file=system.observable_flat_file(\n simulation_id_1, \"kinetic_energy\"\n ),\n potential_ene_file=system.observable_flat_file(\n simulation_id_1, \"potential_energy\"\n ),\n total_ene_file=system.observable_flat_file(simulation_id_1, \"total_energy\"),\n volume_file=system.observable_flat_file(simulation_id_1, \"volume\"),\n )\n simulation_data_2 = parser.get_simulation_data(\n units=system.units,\n ensemble=system.ensemble(simulation_id_2),\n system=system.system_data,\n kinetic_ene_file=system.observable_flat_file(\n simulation_id_2, \"kinetic_energy\"\n ),\n potential_ene_file=system.observable_flat_file(\n simulation_id_2, \"potential_energy\"\n ),\n total_ene_file=system.observable_flat_file(simulation_id_2, \"total_energy\"),\n volume_file=system.observable_flat_file(simulation_id_2, \"volume\"),\n )\n\n assert simulation_data_1 == simulation_data_1_copy\n assert simulation_data_1 != simulation_data_2", "def test_unique_together(self):\n\n for mb_model in self.mb_model_list:\n indexes = connection.introspection.get_indexes(\n self.cursor, mb_model._meta.db_table)\n if not indexes and not is_db_view(mb_model._meta.db_table):\n self.assertTrue(mb_model._meta.unique_together)", "def test_data_naming():\n with pm.Model(\"named_model\") as model:\n x = pm.ConstantData(\"x\", [1.0, 2.0, 3.0])\n y = pm.Normal(\"y\")\n assert y.name == \"named_model::y\"\n assert x.name == \"named_model::x\"", "def __contains__(self, name):\n return (self.model_dir / (str(name) + '.pkl')).exists()", "def _is_lis_output_missing(curdate, model_forcing):\n for model in [\"SURFACEMODEL\", \"ROUTING\"]:\n filename = f\"lis_fcst\"\n filename += f\"/{model_forcing}\"\n filename += f\"/{model}\"\n filename += f\"/{curdate.year:04d}{curdate.month:02d}\"\n filename += \"/LIS_HIST_\"\n filename += f\"{curdate.year:04d}{curdate.month:02d}{curdate.day:02d}\"\n filename += \"0000.d01.nc\"\n if not os.path.exists(filename):\n return True\n return False", "def test_name_already_exists(self) -> None:\n with pytest.raises(IntegrityError):\n ObservationType.add({'name': 'clear', 'units': 'mag',\n 'description': 'Un-filtered apparent magnitude.'})", "def checkIfMeasuringObjectExists(table, name, fk):\n\ttry:\n\t\tcon = sqlite3.connect('PampDb.db')\n\t\tcur = con.cursor()\n\t\tcur.execute(\"SELECT * FROM \" + table + \" WHERE name='\" + name + \"'\")\n\t\tob = cur.fetchall()\n\t\tbo = False\n\t\tif not ob:\n\t\t\tcur.execute(\"INSERT INTO '\" + table + \"' (name, organisationId) VALUES ('\" + name + \"', '\" + str(fk) + \"')\")\n\t\t\tcon.commit()\n\t\t\tcur.execute(\"SELECT * FROM \" + table + \" WHERE name='\" + name + \"'\")\n\t\t\tobj = cur.fetchall()\n\t\t\tcorObj = obj[0]\n\t\t\treturn corObj\n\t\telse:\n\t\t\tfor row in ob:\n\t\t\t\tif row[2] == fk:\n\t\t\t\t\tbo = True\n\t\t\t\t\treturn row\n\t\t\tif not bo:\n\t\t\t\tcur.execute(\"INSERT INTO '\" + table + \"' (name, organisationId) VALUES ('\" + name + \"', '\" + str(fk) + \"')\")\n\t\t\t\tcon.commit()\n\t\t\t\tcur.execute(\"SELECT * FROM \" + table + \" WHERE name='\" + name + \"' AND organisationId='\" + str(fk) + \"'\")\n\t\t\t\tobj = cur.fetchall()\n\t\t\t\tcorObj = obj[0]\n\t\t\t\treturn corObj\n\t\tcon.commit()\n\t\tcon.close()\n\texcept:\n\t\tprint('Could not run function checkIfMeasuringObjectExists from DbController')", "def test_get_and_verify_covars_input_with_dependencies_works(tmp_observe_class,\n covar_details_mapped_covar_mapped_names_tmp_observe_class,\n covariates, kwarg_covariates, monkeypatch):\n\n # device for torch tensor definitions\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n # covariates to sample\n covars_tensor = torch.tensor([covariates], dtype=torch.double, device=device)\n\n # temp class to execute the test\n cls = tmp_observe_class\n\n # define required attributes\n cls.proposed_X = covars_tensor\n cls.initial_guess = covars_tensor\n cls.covar_details = covar_details_mapped_covar_mapped_names_tmp_observe_class[0]\n cls.covar_mapped_names = covar_details_mapped_covar_mapped_names_tmp_observe_class[1]\n cls.sorted_pandas_columns = covar_details_mapped_covar_mapped_names_tmp_observe_class[2]\n\n # monkeypatch\n def mock_input(x): # mock function to replace 'input' for unit testing purposes\n return \", \".join([str(x) for x in covariates])\n monkeypatch.setattr(\"builtins.input\", mock_input)\n\n # run method\n covars_candidate_float_tensor = cls._get_and_verify_covars_input(covars=kwarg_covariates)\n\n # assert\n for i in range(covars_candidate_float_tensor.size()[1]):\n assert covars_candidate_float_tensor[0, i].item() == covariates[i]", "def validateModelCol(self):\n \n ret = False\n \n dc = self.__args['datacolumn'].upper() \n if \"MODEL\" in dc or dc == 'ALL':\n ret = True\n\n return ret", "def test_MasterEquation_exists(self):\n self.assertTrue(hasattr(HaPPPy, 'MasterEquation'))", "def __init__(self,obsinst,):\n self.__observable = obsinst.getobservable()\n self.__modelDV = obs.getmodel(modeltype)\n self.__modelBkg= obsinstances[2]", "def test_covars_datapoint_observation_int_works(tmp_observe_class,\n covar_details_mapped_covar_mapped_names_tmp_observe_class,\n train_X, x_data, covars_proposed_iter, covars_sampled_iter, covariates,\n kwarg_covariates, monkeypatch):\n\n # device for torch tensor definitions\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n # covariates to sample\n covars_tensor = torch.tensor([covariates], dtype=torch.double, device=device)\n\n # temp class to execute the test\n cls = tmp_observe_class\n\n # set proposed_X attribute (required for method to work)\n cls.initial_guess = covars_tensor\n cls.proposed_X = covars_tensor\n cls.train_X = train_X\n cls.x_data = x_data\n cls.model = {\"covars_proposed_iter\": covars_proposed_iter,\n \"covars_sampled_iter\": covars_sampled_iter}\n cls.covar_details = covar_details_mapped_covar_mapped_names_tmp_observe_class[0]\n cls.covar_mapped_names = covar_details_mapped_covar_mapped_names_tmp_observe_class[1]\n cls.sorted_pandas_columns = covar_details_mapped_covar_mapped_names_tmp_observe_class[2]\n\n # monkeypatch\n def mock_input(x): # mock function to replace 'input' for unit testing purposes\n return \", \".join([str(x) for x in covariates])\n monkeypatch.setattr(\"builtins.input\", mock_input)\n\n # run the method\n cls._get_covars_datapoint(covars=kwarg_covariates)\n\n # assert the right elements have been added\n for i in range(cls.train_X.size()[1]):\n assert cls.train_X[-1, i].item() == covariates[i]\n\n # assert that counter has been updated\n assert cls.model[\"covars_sampled_iter\"] == cls.model[\"covars_proposed_iter\"]\n\n # only if covars_proposed_iter is ahead of sampled\n if covars_proposed_iter > covars_sampled_iter:\n # assert that new row has been added\n assert cls.train_X.size()[0] == train_X.size()[0] + 1\n elif train_X is None:\n # assert that cls.train_X has been initiated\n assert cls.train_X.size()[0] == 1\n else:\n # assert that no new row has been added\n assert cls.train_X.size()[0] == train_X.size()[0]", "def __setupmodelsfromws(self,out,modeltypesIn,modelnamesIn):\n # -- Could be a list\n if type(modeltypesIn) == list or type(modelnamesIn) == list:\n if type(modelnamesIn) != list:\n raise NameError(\"Coherence requires to 'modelnames' keyword\"\\\n \" being a string, as 'modeltypes' is\")\n if type(modeltypesIn) != list:\n raise NameError(\"'Coherence requires to 'modeltypes' keyword\"\\\n \" being a string, as 'modelnames' is\")\n modeltypeslist = modeltypesIn\n modelnameslist = modelnamesIn\n # Check the same len!!! FIXME\n else:\n modeltypeslist = [modeltypesIn]\n modelnameslist = [modelnameIn] \n # Setting\n for modeltype,modelname in zip(modeltypeslist,modelnameslist):\n try:\n # Note that the regular constructor puts a ntuple\n # containing the observables, so mimicking that\n self.__models[modeltype] = (out[3][modelname],None)\n except KeyError:\n # Who is not there?\n nothere = None\n if self.__models.has_key(modeltype):\n nothere = modeltype\n else:\n # should be here\n nothere = modelname\n raise AttributeError(\"Not found the model '%s'\" % nothere)\n # Don't have this info, so\n self.__pdftypes[modeltype] = '__UNDEF__'", "def do_check_model(**kwargs):\n # pushes an XCom without a specific target, just by returning it\n mle = MLEngineHook()\n model_name = kwargs['dag_run'].conf.get('model_name')\n # return bool(mle.get_model(PROJECT, MODEL_DNN_NAME))\n project = mle.get_model(PROJECT, model_name)\n kwargs['ti'].xcom_push(key='is_project', value=bool(project))", "def create_observation(self):", "def create_observation(self):", "def _ensure_schema_has_covariates(self, x_underscore_columns):\n previous_rename = self.covariate_rename\n if set(x_underscore_columns) == set(previous_rename.values()):\n return\n # Only rewrite schema if the x_<integer> list has changed.\n # because the schema depends on the number of covariates, not\n # their names.\n covariate_columns = list(x_underscore_columns)\n # ASCII sorting isn't correct b/c x_11 is before x_2.\n covariate_columns.sort(key=lambda x: int(x[2:]))\n for create_name in [\"data\", \"avgint\"]:\n empty = self.dismod_file.empty_table(create_name)\n without = [c for c in empty.columns if not c.startswith(\"x_\")]\n # The wrapper needs these columns to have a dtype of Real.\n empty = empty[without].assign(**{cname: np.empty((0,), dtype=np.float) for cname in covariate_columns})\n self.dismod_file.update_table_columns(create_name, empty)\n if getattr(self.dismod_file, create_name).empty:\n CODELOG.debug(f\"Writing empty {create_name} table with columns {covariate_columns}\")\n setattr(self.dismod_file, create_name, empty)\n else:\n CODELOG.debug(f\"Adding to {create_name} table schema the columns {covariate_columns}\")" ]
[ "0.5495533", "0.5172023", "0.5142633", "0.5087636", "0.4961099", "0.49421537", "0.49322584", "0.49233723", "0.4906298", "0.48916122", "0.4883766", "0.48531032", "0.48529163", "0.4845847", "0.48317057", "0.48283717", "0.4815817", "0.48010272", "0.4800914", "0.47912633", "0.47505814", "0.4749273", "0.4748648", "0.47479764", "0.47202483", "0.47164178", "0.471278", "0.47112772", "0.47112772", "0.4694889" ]
0.57561946
0
Makes sure that covariates can be reshaped in to an array of shape (n, c). In other words, checks whether for each covariate_name there exists exactly one nonNaN value for each ID.
def _check_covariate_values(self, covariate_names): # Check that model needs covariates if len(covariate_names) == 0: return None for name in covariate_names: # Mask covariate values mask = self._data[self._obs_key] == self._covariate_dict[name] temp = self._data[mask] for _id in self._ids: # Mask values for individual mask = temp[self._id_key] == _id temp2 = temp.loc[mask, self._value_key].dropna() if len(temp2) != 1: covariate = self._covariate_dict[name] raise ValueError( 'There are either 0 or more than 1 value of the ' 'covariate %s for ID %s. ' 'Exactly one covariate value ' 'has to be provided for each ID.' % (covariate, _id) )
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def check_categories(a: np.ndarray):\n return list(np.unique(a[~np.isnan(a)]))", "def _extract_covariates(self, covariate_names):\n # Format covariates to array of shape (n, c)\n c = len(covariate_names)\n n = len(self._ids)\n covariates = np.empty(shape=(n, c))\n for idc, name in enumerate(covariate_names):\n mask = self._data[self._obs_key] == self._covariate_dict[name]\n temp = self._data[mask]\n for idn, _id in enumerate(self._ids):\n mask = temp[self._id_key] == _id\n covariates[idn, idc] = \\\n temp.loc[mask, self._value_key].dropna().values\n\n return covariates", "def test_single(self):\n df = self.df.head(1).copy()\n n = df.index.size\n arr = df.values\n out = np_cross_ratios(arr)\n self.assertTrue(np.isfinite(out).any())\n self.assertTrue((out[np.isfinite(out)] > 0).all())\n self.assertTrue(out.shape == (n, self.d, self.d))", "def _is_1d_varray(arr):\r\n return len(arr.shape) < 2 or arr.shape[1] == 1", "def _validate_cardinality(self, columns):\n cards = [len(c.data) for c in columns]\n c = np.unique(cards)\n assert len(c) == 1, c\n return c[0]", "def is1d(a):\n return np.sum(asarray(asarray(a).shape) > 1) <= 1", "def test_multiple(self):\n df = self.df.copy()\n n = df.index.size\n arr = df.values\n out = np_cross_ratios(arr)\n self.assertTrue(np.isfinite(out).any())\n self.assertTrue((out[np.isfinite(out)] > 0).all())\n self.assertTrue(out.shape == (n, self.d, self.d))", "def test_single(self):\n df = self.df.head(1).copy()\n n = df.index.size\n out = cross_ratios(df)\n self.assertTrue(np.isfinite(out).any())\n self.assertTrue((out[np.isfinite(out)] > 0).all())\n self.assertTrue(out.shape == (n, self.d, self.d))", "def check_consistent_length(arrays: Sequence[npt.ArrayLike]) -> None:\n lengths = [_num_samples(X) for X in arrays if X is not None]\n uniques = np.unique(lengths)\n if len(uniques) > 1:\n raise ValueError(\n \"Found input variables with inconsistent numbers of\" \" samples: %r\" % [int(length) for length in lengths]\n )", "def test_multiple(self):\n df = self.df.copy()\n n = df.index.size\n out = cross_ratios(df)\n self.assertTrue(np.isfinite(out).any())\n self.assertTrue((out[np.isfinite(out)] > 0).all())\n self.assertTrue(out.shape == (n, self.d, self.d))", "def validate_unique_cof_ids():\n ids = list(FRAMEWORKS_DF['CURATED-COFs ID'].str.lower()) + list(FRAMEWORKS_DISCARDED_DF['CURATED-COFs ID'].str.lower())\n\n duplicates = [item for item, count in collections.Counter(list(ids)).items() if count > 1]\n\n if duplicates:\n print('Error: Duplicate CURATED-COF IDs detected: {}'.format(duplicates))\n sys.exit(1)\n\n print('No duplicate CURATED-COF IDs found.')", "def check_missing_data(df): \n df_lng = pd.melt(df) #Convert to long data\n null_variables = df_lng.value.isnull()\n \n return pd.crosstab(df_lng.variable, null_variables)", "def victory_checker() -> bool:\r\n conflict_check()\r\n for x in range(shape):\r\n for y in range(shape):\r\n if conflict_space[x, y] != 0:\r\n return False\r\n if separation_crawler(False):\r\n return False\r\n return True", "def cnan(x):\n if np.isnan(x).sum()>0:\n import pdb\n pdb.set_trace()", "def nanvarc(array_data, axis=0):\n\n mdatreal = np.ma.masked_array(array_data.real, np.isnan(array_data.real));\n varreal = np.var(mdatreal, axis=axis);\n mdatimag = np.ma.masked_array(array_data.imag, np.isnan(array_data.imag));\n varimag = np.var(mdatimag, axis=axis);\n retval = np.array( (varreal + 1j*varimag) );\n \n return retval;", "def verify_transformed(self, data):\n data_dim = data.shape[-1]\n if data_dim != self.dimension:\n error(\n \"{} result dimension {} does not match the prescribed input dimension {}\"\n .format(self.name, data_dim, self.dimension))\n nans, _ = np.where(np.isnan(data))\n if np.size(nans) != 0:\n error(\"{} result contains nan elements in :{}\".format(\n self.name, nans))", "def test_remove_autos():\n test_array = np.ones((3, 3, 11, 21))\n out_array = utils.remove_auto_correlations(test_array, axes=(0, 1))\n assert (6, 11, 21) == out_array.shape", "def really1d(arr):\n if np.ndim(arr) != 1:\n return False\n # Empty list or array\n if len(arr) == 0:\n return True\n if np.any(np.vectorize(np.ndim)(arr)):\n return False\n return True", "def _test_obsdup(t):\n return t.shape[0] != len(set(t.ids(axis='observation')))", "def _check_onehot_data(self, data):\n if data.ndim > 1 and np.equal(data ** 2, data).all():\n shp = (data.shape[0],) + data.shape[2:]\n if np.equal(np.ones(shp), data.sum(axis=1)).all():\n return True\n return False", "def _fix_uniq_col(self):\n # subgradient; for two boolean arrays, multiplication seems to be the best way \n # (equivalent to logical_and)\n n_covered_col = self.a_csr.dot(np.ones(self.ncols)) \n ifix = np.zeros(self.ncols, dtype=bool)\n if (np.count_nonzero(n_covered_col) != self.mrows):\n raise ValueError(\"There are uncovered rows! Please check your input!\")\n if (np.any(n_covered_col==1)):\n inonzero = self.a_csr[n_covered_col==1,:].nonzero()\n ifix[inonzero[1]] = True\n\n return ifix", "def healthy_test(obj: np.ndarray) -> bool:\n nb_rows, nb_cols = obj.shape\n return nb_rows == nb_cols > 1 and np.array_equal(obj, colony(nb_rows))", "def test_cprod_ignore_nans():\n source = [np.ones((16,), dtype=float) for _ in range(10)]\n source.append(np.full_like(source[0], np.nan))\n product = cprod(source, ignore_nan=True)\n assert np.allclose(product, np.ones_like(product))", "def test_contrasting(self):\n df = self.df.copy()\n n = df.index.size\n # Create some nans to imitate contrasting analysis sets\n df.iloc[\n np.random.randint(1, self.n, size=2), np.random.randint(1, self.d, size=2)\n ] = np.nan\n arr = df.values\n out = np_cross_ratios(arr)\n self.assertTrue(np.isfinite(out).any())\n self.assertTrue((out[np.isfinite(out)] > 0).all())\n self.assertTrue(out.shape == (n, self.d, self.d))", "def compute_correlation_matrix_with_incomplete_data(df, correlation_type):\n X = copy.deepcopy(pd.DataFrame(df)) # make sure we are using a dataframe to do computations. \n assert correlation_type in ['spearman', 'pearson', 'covariance']\n X = X.astype(np.float64) # if we do not do this for some reason it ignores some columns in computing the correlation matrix. \n # which ends up being the wrong shape. \n if correlation_type == 'covariance':\n C = X.cov() * (len(df) - 1) / len(df) # need correction factor so it's consistent with ddof = 0. Makes little difference. \n else:\n C = X.corr(correlation_type)\n C = np.array(C)\n assert C.shape[0] == C.shape[1]\n assert C.shape[0] == len(df.columns)\n\n \n for i in range(len(C)):\n for j in range(len(C)):\n if np.isnan(C[i][j]):\n print(\"Warning: entry of covariance matrix is nan; setting to 0.\")\n C[i][j] = 0\n non_missing_data_counts = (~pd.isnull(X)).sum(axis = 0)\n return C, non_missing_data_counts", "def coarsen(raw, err = 0.01):\n # Set up a blank database equal in size to the input data\n data = np.zeros(raw.shape)\n \n # Record the first data point\n data[0,:] = raw[0,:]\n \n # Loop through the remaining data and only record a data point if err will \n # otherwise be exceeded for any column of dependent-variable data.\n j = 0\n i_0 = 0\n for i in range(1, raw.shape[0]-1):\n # Loop through each row of data\n rec = False\n for k in range(1, raw.shape[1]):\n # Check each column for an exceedance of the err criteria\n if raw[i,k] != 0.:\n ea = np.abs((raw[i,k] - raw[i_0,k]) / raw[i,k])\n else:\n ea = 0.\n if ea > err:\n # Error exceeded for this column; record this row of data\n rec = True\n if rec:\n # Need to record this row\n j += 1\n data[j,:] = raw[i,:]\n # Reset the baseline row for the error calculation\n i_0 = i\n \n # Record the last data point\n j += 1\n data[j,:] = raw[-1,:]\n \n # Remove all blank rows from database\n data = data[0:j+1,:]\n \n # Return the reduced dataset\n return data", "def check_color(c):\n\n c = asarray(c)\n if c.ndim == 1:\n c = c.flatten()\n c = c[newaxis, :]\n if c.shape[1] != 3:\n raise Exception(\"Color must have three values per point\")\n elif c.ndim == 2:\n if c.shape[1] != 3:\n raise Exception(\"Color array must have three values per point\")\n return c", "def _is_1d_harray(arr):\r\n return len(arr.shape) < 2 or arr.shape[0] == 1", "def is_data_unique(data: np.array) -> bool:\n\n data_shape = data.shape\n unique_data_shape = np.unique(data, axis=0).shape\n\n if data_shape == unique_data_shape:\n return True\n\n return False", "def isscalar(x):\n arrayed_x = asarray(x)\n return asarray(x).ndim == 0 and arrayed_x.dtype != 'object'" ]
[ "0.5669321", "0.547841", "0.5444621", "0.54324275", "0.5407865", "0.54041755", "0.53234154", "0.5320249", "0.5316274", "0.5283278", "0.52639496", "0.5132837", "0.5126093", "0.5118132", "0.51035595", "0.5090211", "0.5082021", "0.50425917", "0.5038308", "0.5019751", "0.4994034", "0.4962509", "0.49620336", "0.4960717", "0.49429446", "0.49224508", "0.49138647", "0.4907427", "0.49058405", "0.48988461" ]
0.6623855
0
Makes sure that the data is formated properly. 1. ids are strings 2. time are numerics or NaN 3. observables are strings 4. values are numerics or NaN 5. observable types are 'Modelled' or 'Covariate' 6. dose are numerics or NaN 7. duration are numerics or NaN
def _clean_data(self, dose_key, dose_duration_key): # Create container for data columns = [ self._id_key, self._time_key, self._obs_key, self._value_key] if dose_key is not None: columns += [dose_key] if dose_duration_key is not None: columns += [dose_duration_key] data = pd.DataFrame(columns=columns) # Convert IDs to strings data[self._id_key] = self._data[self._id_key].astype( "string") # Convert times to numerics data[self._time_key] = pd.to_numeric(self._data[self._time_key]) # Convert observables to strings data[self._obs_key] = self._data[self._obs_key].astype( "string") # Convert values to numerics data[self._value_key] = pd.to_numeric(self._data[self._value_key]) # Convert dose to numerics if dose_key is not None: data[dose_key] = pd.to_numeric( self._data[dose_key]) # Convert duration to numerics if dose_duration_key is not None: data[dose_duration_key] = pd.to_numeric( self._data[dose_duration_key]) self._data = data
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def parse_missing_fields(data):\n def _get_nan_synonims(k):\n if k == \"extra_security_descriptors\":\n return [pd.NaT, np.nan]\n else:\n return [pd.NaT, '', np.nan]\n\n data = {id_no: {k: (v if v not in _get_nan_synonims(k) and not pd.isna(v) \n else None) for k,v in datapoint.items()} for id_no, datapoint in data.items()}\n return data", "def _maybe_dt_data(self, data, feature_names, feature_types,\n meta=None, meta_type=None):\n if meta and data.shape[1] > 1:\n raise ValueError(\n 'DataTable for label or weight cannot have multiple columns')\n if meta:\n # below requires new dt version\n # extract first column\n data = data.to_numpy()[:, 0].astype(meta_type)\n return data, None, None\n\n data_types_names = tuple(lt.name for lt in data.ltypes)\n bad_fields = [data.names[i]\n for i, type_name in enumerate(data_types_names)\n if type_name not in self.dt_type_mapper]\n if bad_fields:\n msg = \"\"\"DataFrame.types for data must be int, float or bool.\n Did not expect the data types in fields \"\"\"\n raise ValueError(msg + ', '.join(bad_fields))\n\n if feature_names is None and meta is None:\n feature_names = data.names\n\n # always return stypes for dt ingestion\n if feature_types is not None:\n raise ValueError(\n 'DataTable has own feature types, cannot pass them in.')\n feature_types = np.vectorize(self.dt_type_mapper2.get)(\n data_types_names)\n\n return data, feature_names, feature_types", "def _pre_process_record(self, data):\n result = []\n symbolic_split = \",\"\n if isinstance(data, dict):\n if self.measure is None:\n logging.error(\"Missing the name of keys pointing to values\")\n raise UnSADException.data_format_exception()\n if self.timestamp is not None:\n if self.timestamp in data:\n try:\n result.append(float(data[self.timestamp]))\n [result.append(data[measure])\n for measure in self.measure]\n except RuntimeError:\n logging.error(\"Invalid input data type, should be a numerical type\")\n logging.error(\"Input data should contain all the fields \"\n \"that are specified when initialize the detector: \" + str(self.measure))\n raise UnSADException.data_type_exception()\n else:\n logging.error(\"Input data should contain a timestamp field:\" + str(self.timestamp))\n raise UnSADException.data_format_exception()\n else:\n try:\n [result.append(data[measure]) for measure in self.measure]\n except RuntimeError:\n logging.error(\"Input data should contain all the fields \"\n \"that are specified when initialize the detector: \" + str(self.measure))\n raise UnSADException.data_format_exception()\n elif isinstance(data, Iterable) and not isinstance(data, str):\n if self.timestamp is not None:\n if len(data) == len(self.measure) + 1:\n try:\n result = list(data)\n result[0] = float(result[0])\n except RuntimeError as e:\n logging.error(\"Invalid input data type, timestamp should be a numerical type\")\n raise UnSADException.data_type_exception()\n else:\n logging.error(\"The number of input parameters:\" + str(\n len(data)) + \" does not match with this detectors:\" + str(len(self.measure) + 1))\n raise UnSADException.input_number_exception()\n else:\n if self.measure is None or len(data) == len(self.measure):\n result = data\n else:\n logging.error(\"The number of input parameters:\" + str(\n len(data)) + \" does not match with this detectors:\" + str(len(self.measure)))\n raise UnSADException.input_number_exception()\n else:\n if (self.measure is None or len(self.measure) == 1) and self.timestamp is None:\n if self.symbolic:\n return str(data)\n else:\n try:\n return float(data)\n except RuntimeError as e:\n logging.error(\"Invalid input data type, should be a numerical type\")\n raise UnSADException.data_type_exception()\n else:\n logging.error(\"This detector is not initialized properly\")\n raise UnSADException.not_proper_initialize_exception()\n\n if not self.symbolic:\n try:\n processed_result = [float(result[i])\n for i in range(len(result))]\n except RuntimeError as e:\n logging.error(\"Invalid input data type, should be a numerical type\")\n raise UnSADException.data_type_exception()\n\n return processed_result[0] if len(processed_result) == 1 else processed_result\n\n else:\n if self.timestamp is not None:\n return [result[0], symbolic_split.join([str(s) for s in result[1:]])]\n else:\n return symbolic_split.join([str(s) for s in result])", "def cleanData(data):\r\n \r\n indexes = data.index[pd.isnull(data[\"release date\"])]\r\n # data = data.drop(data.index[[2172, 3781, 7245, 12475, 14756, 15292, 49295, 93523, 99723]],axis=0,inplace=False)\r\n data = data.drop(indexes,axis=0,inplace=False)\r\n data = data.drop([\"video release date\", 'IMDb URL'],axis=1)\r\n \r\n \r\n data.gender = data.gender.astype(\"category\")\r\n data.occupation = data.occupation.astype(\"category\")\r\n \r\n categorical_variables = [\"gender\", \"occupation\"]\r\n for variable in categorical_variables:\r\n dummies = pd.get_dummies(data[variable], prefix=variable)\r\n data = pd.concat([data, dummies], axis=1)\r\n data.drop([variable], axis=1, inplace=True)\r\n data['movieID'] = data['movieID'].astype('int')\r\n data['userID'] = data['userID'].astype('int')\r\n \r\n\t#data = dateTime(data)\r\n \r\n return data", "def normalize_data(data):\n\n # 'alphanumeric' and 'description' use the empty string instead of None\n if 'alphanumeric' in data and data['alphanumeric'] is None:\n data['alphanumeric'] = \"\"\n if 'description' in data and data['description'] is None:\n data['description'] = \"\"\n\n # Values may be None to clear them or leave them blank.\n\n # Type is the one exception; it is required and may not be None.\n if 'type' in data:\n try:\n data['type'] = OdlcType.lookup(data['type'])\n except KeyError:\n raise ValueError('Unknown odlc type \"%s\"; known types %r' %\n (data['type'], OdlcType.names()))\n\n if 'latitude' in data and data['latitude'] is not None:\n try:\n data['latitude'] = float(data['latitude'])\n if data['latitude'] < -90 or data['latitude'] > 90:\n raise ValueError\n except ValueError:\n # Unable to convert to float or out-of-range\n raise ValueError('Invalid latitude \"%s\", must be -90 <= lat <= 90'\n % data['latitude'])\n\n if 'longitude' in data and data['longitude'] is not None:\n try:\n data['longitude'] = float(data['longitude'])\n if data['longitude'] < -180 or data['longitude'] > 180:\n raise ValueError\n except ValueError:\n # Unable to convert to float or out-of-range\n raise ValueError(\n 'Invalid longitude \"%s\", must be -180 <= lat <= 180' %\n (data['longitude']))\n\n if 'orientation' in data and data['orientation'] is not None:\n try:\n data['orientation'] = Orientation.lookup(data['orientation'])\n except KeyError:\n raise ValueError(\n 'Unknown orientation \"%s\"; known orientations %r' %\n (data['orientation'], Orientation.names()))\n\n if 'shape' in data and data['shape'] is not None:\n try:\n data['shape'] = Shape.lookup(data['shape'])\n except KeyError:\n raise ValueError('Unknown shape \"%s\"; known shapes %r' %\n (data['shape'], Shape.names()))\n\n if 'background_color' in data and data['background_color'] is not None:\n try:\n data['background_color'] = Color.lookup(data['background_color'])\n except KeyError:\n raise ValueError('Unknown color \"%s\"; known colors %r' %\n (data['background_color'], Color.names()))\n\n if 'alphanumeric_color' in data and data['alphanumeric_color'] is not None:\n try:\n data['alphanumeric_color'] = \\\n Color.lookup(data['alphanumeric_color'])\n except KeyError:\n raise ValueError('Unknown color \"%s\"; known colors %r' %\n (data['alphanumeric_color'], Color.names()))\n\n if 'autonomous' in data:\n if data['autonomous'] is not True and data['autonomous'] is not False:\n raise ValueError('\"autonmous\" must be true or false')\n\n if 'actionable_override' in data:\n if (data['actionable_override'] is not True and\n data['actionable_override'] is not False): # yapf: disable\n raise ValueError('\"actionable_override\" must be true or false')\n\n return data", "def prepare_data(self, data):\n for i, v in data.items():\n field_type = self.get_field_type(i)\n #log.info('i = %s, type = %s', i, field_type)\n if field_type == 'datetime' and isinstance(v, (str, unicode)):\n data[i] = datetime_from_string(v)\n return data", "def validate_example_data(t, units=True):\n input_data_columns = [f\"C{num}\" for num in range(1, 4)]\n assert list(t.data.columns) == input_data_columns\n if units:\n input_data_units = [\"m/s\", \"mol/L\", \"(m^3)/kg\"]\n assert t.units_dict == {\n input_data_columns[i]: input_data_units[i]\n for i in range(len(input_data_columns))\n }\n assert t.units_list == [\n input_data_units[i] for i in range(len(input_data_columns))\n ]\n else:\n assert t.units_dict == {\n input_data_columns[i]: \"\" for i in range(len(input_data_columns))\n }\n assert t.units_list == [\"\"] * len(input_data_columns)", "def clean_meteo_data(self, df):\n for col in df.columns:\n df[col] = df[col].str.replace(',', '.').astype(\"float\")\n# df_nan = df[df.isna().any(axis=1)]\n# print(\"Check Nans:\",df_nan.shape[0])\n df=df.fillna(method='ffill')\n# df_nan = df[df.isna().any(axis=1)]\n# print(\"Check Nans:\",df_nan.shape[0])\n# print(\"shape selected sensor data:\",df.shape)\n df=df.dropna()\n df=df.resample(\"10T\").mean()\n df=df.reset_index()\n df['dag']=df['datetime'].dt.day\n return df", "def test_time_dicts():\n dmd = DMD()\n dmd.fit(X=sample_data_1, Y=sample_data_2)\n expected_dict = {\"dt\": 1, \"t0\": 0, \"tend\": 13}\n np.testing.assert_equal(dmd.original_time, expected_dict)\n np.testing.assert_equal(dmd.dmd_time, expected_dict)", "def _check_types(self):\n if isinstance(self.unique_id, (int, str)): # should unique_id be a float?\n self.unique_id = str(self.unique_id)\n else:\n raise TypeError(f'unique_id incorrect type: {type(self.unique_id)}')\n try:\n self.ra = float(self.ra)\n except TypeError:\n print(f'ra incorrect type: {type(self.ra)}')\n try:\n self.dec = float(self.dec)\n except TypeError:\n print(f'dec incorrect type: {type(self.dec)}')\n try:\n self.z = float(self.z)\n except TypeError:\n print(f'z incorrect type: {type(self.z)}')\n if not isinstance(self.galcat, GCData):\n raise TypeError(f'galcat incorrect type: {type(self.galcat)}')\n if not -360. <= self.ra <= 360.:\n raise ValueError(f'ra={self.ra} not in valid bounds: [-360, 360]')\n if not -90. <= self.dec <= 90.:\n raise ValueError(f'dec={self.dec} not in valid bounds: [-90, 90]')\n if self.z < 0.:\n raise ValueError(f'z={self.z} must be greater than 0')", "def _parse_dtypes(data, table_meta):\n for name, field in table_meta['fields'].items():\n field_type = field['type']\n if field_type == 'datetime':\n datetime_format = field.get('format')\n data[name] = pd.to_datetime(data[name], format=datetime_format, exact=False)\n elif field_type == 'numerical' and field.get('subtype') == 'integer':\n data[name] = data[name].dropna().astype(np.int64)\n elif field_type == 'id' and field.get('subtype', 'integer') == 'integer':\n data[name] = data[name].dropna().astype(np.int64)\n\n return data", "def test_datatype(self):\n with Pandas() as pd:\n if pd is None:\n return\n with Numpy() as np: # noqa\n if numpy is None:\n return\n sys.stderr.write(\"\\n\")\n\n df, hist1, hist2, hist3 = get_test_histograms1()\n\n assert hist1.datatype == str\n np.testing.assert_array_equal(hist2.datatype, [numpy.number, str])\n np.testing.assert_array_equal(hist3.datatype, [numpy.datetime64, numpy.number, str])", "def test_str_time_1(self):\n xknx = XKNX()\n sensor = Sensor(\n xknx, \"TestSensor\", group_address_state=\"1/2/3\", value_type=\"time_1\"\n )\n sensor.sensor_value.payload = DPTArray(\n (\n 0x5E,\n 0x1E,\n )\n )\n\n self.assertEqual(sensor.resolve_state(), 32071.68)\n self.assertEqual(sensor.unit_of_measurement(), \"s\")\n self.assertEqual(sensor.ha_device_class(), None)", "def unpack(id: int):\n id = int(id)\n time_list = [i['ts'] for i in data if int(i['id']) == id]\n val_list = [i['floatvalue'] for i in data if int(i['id']) == id]\n # SMIP always returns one entry before the start time for each ID, we don't need this\n if len(time_list) < 2 or len(val_list) < 2:\n return dash.no_update\n time_list.pop(0)\n val_list.pop(0)\n # Measure sampling rate\n rate = nan\n if len(time_list) > 1:\n rate = (strptime_fix(time_list[1])\n - strptime_fix(time_list[0])).total_seconds()\n return {'time_list': time_list, 'val_list': val_list, 'rate': rate}", "def _load_time(self):\n\n time_variables = ('time', 'Times', 'Itime', 'Itime2')\n got_time, missing_time = [], []\n for time in time_variables:\n # Since not all of the time_variables specified above are required, only try to load the data if they\n # exist. We'll raise an error if we don't find any of them though.\n if time in self.ds.variables:\n setattr(self.time, time, self.ds.variables[time][:])\n got_time.append(time)\n attributes = type('attributes', (object,), {})()\n for attribute in self.ds.variables[time].ncattrs():\n setattr(attributes, attribute, getattr(self.ds.variables[time], attribute))\n setattr(self.atts, time, attributes)\n else:\n missing_time.append(time)\n\n if len(missing_time) == len(time_variables):\n warn('No time variables found in the netCDF.')\n else:\n if 'Times' in got_time:\n # Overwrite the existing Times array with a more sensibly shaped one.\n self.time.Times = np.asarray([''.join(t.astype(str)).strip() for t in self.time.Times])\n\n # Make whatever we got into datetime objects and use those to make everything else. Note: the `time' variable\n # is often the one with the lowest precision, so use the others preferentially over that.\n if 'Times' not in got_time:\n if 'time' in got_time:\n _dates = num2date(self.time.time, units=getattr(self.ds.variables['time'], 'units'))\n elif 'Itime' in got_time and 'Itime2' in got_time:\n _dates = num2date(self.time.Itime + self.time.Itime2 / 1000.0 / 60 / 60, units=getattr(self.ds.variables['Itime'], 'units'))\n try:\n self.time.Times = np.array([datetime.strftime(d, '%Y-%m-%dT%H:%M:%S.%f') for d in _dates])\n except ValueError:\n self.time.Times = np.array([datetime.strftime(d, '%Y/%m/%d %H:%M:%S.%f') for d in _dates])\n # Add the relevant attribute for the Times variable.\n attributes = type('attributes', (object,), {})()\n setattr(attributes, 'time_zone', 'UTC')\n setattr(self.atts, 'Times', attributes)\n\n if 'time' not in got_time:\n if 'Times' in got_time:\n try:\n _dates = np.array([datetime.strptime(''.join(t.astype(str)).strip(), '%Y-%m-%dT%H:%M:%S.%f') for t in self.time.Times])\n except ValueError:\n _dates = np.array([datetime.strptime(''.join(t.astype(str)).strip(), '%Y/%m/%d %H:%M:%S.%f') for t in self.time.Times])\n elif 'Itime' in got_time and 'Itime2' in got_time:\n _dates = num2date(self.time.Itime + self.time.Itime2 / 1000.0 / 60 / 60, units=getattr(self.ds.variables['Itime'], 'units'))\n # We're making Modified Julian Days here to replicate FVCOM's 'time' variable.\n self.time.time = date2num(_dates, units='days since 1858-11-17 00:00:00')\n # Add the relevant attributes for the time variable.\n attributes = type('attributes', (object,), {})()\n setattr(attributes, 'units', 'days since 1858-11-17 00:00:00')\n setattr(attributes, 'long_name', 'time')\n setattr(attributes, 'format', 'modified julian day (MJD)')\n setattr(attributes, 'time_zone', 'UTC')\n setattr(self.atts, 'time', attributes)\n\n if 'Itime' not in got_time and 'Itime2' not in got_time:\n if 'Times' in got_time:\n try:\n _dates = np.array([datetime.strptime(''.join(t.astype(str)).strip(), '%Y-%m-%dT%H:%M:%S.%f') for t in self.time.Times])\n except ValueError:\n _dates = np.array([datetime.strptime(''.join(t.astype(str)).strip(), '%Y/%m/%d %H:%M:%S.%f') for t in self.time.Times])\n elif 'time' in got_time:\n _dates = num2date(self.time.time, units=getattr(self.ds.variables['time'], 'units'))\n # We're making Modified Julian Days here to replicate FVCOM's 'time' variable.\n _datenum = date2num(_dates, units='days since 1858-11-17 00:00:00')\n self.time.Itime = np.floor(_datenum)\n self.time.Itime2 = (_datenum - np.floor(_datenum)) * 1000 * 60 * 60 # microseconds since midnight\n attributes = type('attributes', (object,), {})()\n setattr(attributes, 'units', 'days since 1858-11-17 00:00:00')\n setattr(attributes, 'format', 'modified julian day (MJD)')\n setattr(attributes, 'time_zone', 'UTC')\n setattr(self.atts, 'Itime', attributes)\n attributes = type('attributes', (object,), {})()\n setattr(attributes, 'units', 'msec since 00:00:00')\n setattr(attributes, 'time_zone', 'UTC')\n setattr(self.atts, 'Itime2', attributes)\n\n # Additional nice-to-have time representations.\n if 'Times' in got_time:\n try:\n self.time.datetime = np.array([datetime.strptime(d, '%Y-%m-%dT%H:%M:%S.%f') for d in self.time.Times])\n except ValueError:\n self.time.datetime = np.array([datetime.strptime(d, '%Y/%m/%d %H:%M:%S.%f') for d in self.time.Times])\n attributes = type('attributes', (object,), {})()\n setattr(attributes, 'long_name', 'Python datetime.datetime')\n setattr(self.atts, 'datetime', attributes)\n else:\n self.time.datetime = _dates\n self.time.matlabtime = self.time.time + 678942.0 # convert to MATLAB-indexed times from Modified Julian Date.\n attributes = type('attributes', (object,), {})()\n setattr(attributes, 'long_name', 'MATLAB datenum')\n setattr(self.atts, 'matlabtime', attributes)\n\n # Clip everything to the time indices if we've been given them. Update the time dimension too.\n if 'time' in self._dims:\n if all([isinstance(i, (datetime, str)) for i in self._dims['time']]):\n # Convert datetime dimensions to indices in the currently loaded data.\n self._dims['time'][0] = self.time_to_index(self._dims['time'][0])\n self._dims['time'][1] = self.time_to_index(self._dims['time'][1]) + 1 # make the indexing inclusive\n for time in self.obj_iter(self.time):\n setattr(self.time, time, getattr(self.time, time)[self._dims['time'][0]:self._dims['time'][1]])\n self.dims.time = len(self.time.time)", "def data_preprocessing(dataset):\r\n df = pd.read_csv(dataset)\r\n df.head()\r\n df.describe()\r\n df.isnull().sum()\r\n df= df.drop(['instant'], axis=1)\r\n df['dteday'] = pd.to_datetime(df['dteday'].apply(str) + ' ' + df['hr'].apply(str) + ':00:00')\r\n return df", "def emit_metric(ts, data):\n clean = [cleaner(d) for d in data]\n # print clean\n # check that clean[0] do not start with a number\n (n0,v0) = clean[0]\n if n0 is not None:\n # print 'error: do not understand metric' \n return\n\n if len(clean) == 2:\n (n1,v1) = clean[1]\n return '{0}.{1} {2} {3}'.format(v0, v1, ts, n1)\n elif len(clean) == 3:\n (n1,v1) = clean[1]\n (n2,v2) = clean[2]\n return '{0}.{1}.{2} {3} {4}'.format(v0, v1, v2, ts, n2)", "def set_data(\n self, data, output_observable_dict=None, covariate_dict=None,\n id_key='ID', time_key='Time', obs_key='Observable',\n value_key='Value', dose_key='Dose', dose_duration_key='Duration'):\n # Check input format\n if not isinstance(data, pd.DataFrame):\n raise TypeError(\n 'Data has to be a pandas.DataFrame.')\n\n # If model does not support dose administration, set dose keys to None\n if not self._mechanistic_model.supports_dosing():\n dose_key = None\n dose_duration_key = None\n\n keys = [id_key, time_key, obs_key, value_key]\n if dose_key is not None:\n keys += [dose_key]\n if dose_duration_key is not None:\n keys += [dose_duration_key]\n\n for key in keys:\n if key not in data.keys():\n raise ValueError(\n 'Data does not have the key <' + str(key) + '>.')\n\n # Check output observable map\n outputs = self._mechanistic_model.outputs()\n observables = data[obs_key].dropna().unique()\n output_observable_dict = self._check_output_observable_dict(\n output_observable_dict, outputs, observables)\n\n # Check covariate name map\n covariate_names = self.get_covariate_names()\n covariate_dict = self._check_covariate_dict(\n covariate_dict, covariate_names, observables)\n\n self._id_key, self._time_key, self._obs_key, self._value_key = [\n id_key, time_key, obs_key, value_key]\n self._data = data[keys]\n self._output_observable_dict = output_observable_dict\n self._covariate_dict = covariate_dict\n\n # Make sure data is formatted correctly\n self._clean_data(dose_key, dose_duration_key)\n self._ids = self._data[self._id_key].unique()\n\n # Extract dosing regimens\n self._dosing_regimens = None\n if dose_key is not None:\n self._dosing_regimens = self._extract_dosing_regimens(\n dose_key, dose_duration_key)\n\n # Set number of modelled individuals of population model\n if isinstance(self._population_model, chi.ReducedPopulationModel):\n # Unfix model parameters\n self._population_model = \\\n self._population_model.get_population_model()\n if self._population_model is not None:\n self._population_model.set_n_ids(len(self._ids))\n\n # Check that covariates can be reshaped into (n, c)\n self._check_covariate_values(covariate_names)", "def dataIdentify(self, in_nc):\r\n data_nc = NET.Dataset(in_nc)\r\n time = data_nc.variables['time'][:]\r\n diff = NUM.unique(NUM.diff(time))\r\n data_nc.close()\r\n #time_interval_highres = NUM.array([1.0,3.0,6.0],dtype=float)\r\n #time_interval_lowres_full = NUM.array([3.0, 6.0],dtype=float)\r\n #time_interval_lowres = NUM.array([6.0],dtype=float)\r\n #time_interval_lowres_3Hr = NUM.array([3.0],dtype=float)\r\n\t\t\r\n time_interval_HRES1 = NUM.array([1.0],dtype=float) # Line Added/Modified CJB 20190108\r\n time_interval_HRES13 = NUM.array([1.0,3.0],dtype=float) # Line Added/Modified CJB 20190108\r\n time_interval_HRES136 = NUM.array([1.0,3.0,6.0],dtype=float) # Line Added/Modified CJB 20190108\r\n time_interval_ENS3 = NUM.array([3.0],dtype=float) # Line Added/Modified CJB 20190108\r\n time_interval_ENS36 = NUM.array([3.0,6.0],dtype=float) # Line Added/Modified CJB 20190108\r\n time_interval_ENS6 = NUM.array([6.0],dtype=float) # Line Added/Modified CJB 20190108\r\n\r\n\r\n #print \"SDR - diff:\", diff, time_interval_highres, time_interval_lowres_full, time_interval_lowres\r\n #if NUM.array_equal(diff, time_interval_highres):\r\n # return \"HighRes\"\r\n #elif NUM.array_equal(diff, time_interval_lowres_full):\r\n # return \"LowResFull\"\r\n #elif NUM.array_equal(diff, time_interval_lowres):\r\n # return \"LowRes\"\r\n #elif NUM.array_equal(diff, time_interval_lowres_3Hr):\r\n # return \"Low3HrRes\"\r\n #else:\r\n # return None\r\n\t\t\t\r\n if NUM.array_equal(diff, time_interval_HRES1): # Line Added/Modified CJB 20190108\r\n return \"HRES1\" # Line Added/Modified CJB 20190108\r\n elif NUM.array_equal(diff, time_interval_HRES13): # Line Added/Modified CJB 20190108\r\n return \"HRES13\" # Line Added/Modified CJB 20190108\r\n elif NUM.array_equal(diff, time_interval_HRES136): # Line Added/Modified CJB 20190108\r\n return \"HRES136\" # Line Added/Modified CJB 20190108\r\n elif NUM.array_equal(diff, time_interval_ENS3): # Line Added/Modified CJB 20190108\r\n return \"ENS3\" # Line Added/Modified CJB 20190108\r\n elif NUM.array_equal(diff, time_interval_ENS36): # Line Added/Modified CJB 20190108\r\n return \"ENS36\" # Line Added/Modified CJB 20190108\r\n elif NUM.array_equal(diff, time_interval_ENS6): # Line Added/Modified MJS, CJB 20190108\r\n return \"ENS6\" # Line Added/Modified CJB 20190108\r\n else: # Line Added/Modified CJB 20190108\r\n return None # Line Added/Modified CJB 20190108\r", "def __init__(self, data_id, course_fields, speed_fields, heading_fields,\n wind_dir_fields, wind_speed_fields,\n update_on_fields=None,\n zero_line_reference=0,\n convert_wind_factor=1,\n convert_speed_factor=1,\n output_nmea=False):\n super().__init__(input_format=formats.Python_Record,\n output_format=formats.Text)\n self.data_id = data_id\n self.course_fields = course_fields.split(',')\n self.speed_fields = speed_fields.split(',')\n self.heading_fields = heading_fields.split(',')\n self.wind_dir_fields = wind_dir_fields.split(',')\n self.wind_speed_fields = wind_speed_fields.split(',')\n\n if update_on_fields:\n self.update_on_fields = update_on_fields.split(',')\n else:\n self.update_on_fields = self.wind_dir_fields\n self.zero_line_reference = zero_line_reference\n\n self.convert_wind_factor = convert_wind_factor\n self.convert_speed_factor = convert_speed_factor\n self.output_nmea = output_nmea\n \n self.course_val = None\n self.speed_val = None\n self.heading_val = None\n self.wind_dir_val = None\n self.wind_speed_val = None\n\n self.last_timestamp = 0", "def null_value_handler(datatype, value, null_format):\n if DataType.Name(datatype) == \"STRING\":\n if NullValues.STRING == value:\n return null_format\n return value\n elif DataType.Name(datatype) == \"DOUBLE\":\n if math.isnan(value):\n return null_format\n return value\n elif DataType.Name(datatype) == \"FLOAT\":\n if math.isnan(value):\n return null_format\n return value\n elif DataType.Name(datatype) == \"INT32\":\n if NullValues.INT32 == value:\n return null_format\n return value\n elif DataType.Name(datatype) == \"INT64\":\n if NullValues.INT64 == value:\n return null_format\n return value\n elif DataType.Name(datatype) == \"DURATION\":\n if NullValues.DURATION.equals(value):\n return null_format\n return value\n elif DataType.Name(datatype) == \"TIMESTAMP\":\n if NullValues.TIMESTAMP.equals(value):\n return null_format\n return value\n else:\n return value", "def null_value_handler(datatype, value, null_format):\n if DataType.Name(datatype) == \"STRING\":\n if NullValues.STRING == value:\n return null_format\n return value\n elif DataType.Name(datatype) == \"DOUBLE\":\n if math.isnan(value):\n return null_format\n return value\n elif DataType.Name(datatype) == \"FLOAT\":\n if math.isnan(value):\n return null_format\n return value\n elif DataType.Name(datatype) == \"INT32\":\n if NullValues.INT32 == value:\n return null_format\n return value\n elif DataType.Name(datatype) == \"INT64\":\n if NullValues.INT64 == value:\n return null_format\n return value\n elif DataType.Name(datatype) == \"DURATION\":\n if NullValues.DURATION.equals(value):\n return null_format\n return value\n elif DataType.Name(datatype) == \"TIMESTAMP\":\n if NullValues.TIMESTAMP.equals(value):\n return null_format\n return value\n else:\n return value", "def __init__(self, data, t0=None, sampling_interval=None,\r\n sampling_rate=None, duration=None, time=None, time_unit='s',\r\n metadata=None):\r\n\r\n #If a UniformTime object was provided as input:\r\n if isinstance(time, UniformTime):\r\n c_fac = time._conversion_factor\r\n #If the user did not provide an alternative t0, get that from the\r\n #input:\r\n if t0 is None:\r\n t0 = time.t0\r\n #If the user did not provide an alternative sampling interval/rate:\r\n if sampling_interval is None and sampling_rate is None:\r\n sampling_interval = time.sampling_interval\r\n sampling_rate = time.sampling_rate\r\n #The duration can be read either from the length of the data, or\r\n #from the duration specified by the time-series:\r\n if duration is None:\r\n duration = time.duration\r\n length = time.shape[-1]\r\n #If changing the duration requires a change to the\r\n #sampling_rate, make sure that this was explicitely required by\r\n #the user - if the user did not explicitely set the\r\n #sampling_rate, or it is inconsistent, throw an error:\r\n data_len = np.array(data).shape[-1]\r\n\r\n if (length != data_len and\r\n sampling_rate != float(data_len * c_fac) / time.duration):\r\n e_s = \"Length of the data (%s) \" % str(len(data))\r\n e_s += \"specified sampling_rate (%s) \" % str(sampling_rate)\r\n e_s += \"do not match.\"\r\n raise ValueError(e_s)\r\n #If user does not provide a\r\n if time_unit is None:\r\n time_unit = time.time_unit\r\n\r\n else:\r\n ##If the input was not a UniformTime, we need to check that there\r\n ##is enough information in the input to generate the UniformTime\r\n ##array.\r\n\r\n #There are different valid combinations of inputs\r\n tspec = tuple(x is not None for x in\r\n [sampling_interval, sampling_rate, duration])\r\n\r\n tspec_arg_names = [\"sampling_interval\",\r\n \"sampling_rate\",\r\n \"duration\"]\r\n\r\n #The valid configurations\r\n valid_tspecs = [\r\n #interval, length:\r\n (True, False, False),\r\n #interval, duration:\r\n (True, False, True),\r\n #rate, length:\r\n (False, True, False),\r\n #rate, duration:\r\n (False, True, True),\r\n #length, duration:\r\n (False, False, True)\r\n ]\r\n\r\n if tspec not in valid_tspecs:\r\n raise ValueError(\"Invalid time specification. \\n\"\r\n \"You provided: %s\\n %s see docstring for more info.\" % (\r\n str_tspec(tspec, tspec_arg_names),\r\n str_valid_tspecs(valid_tspecs, tspec_arg_names)))\r\n\r\n # Make sure to grab the time unit from the inputs, if it is provided:\r\n if time_unit is None:\r\n # If you gave us a duration with time_unit attached\r\n if isinstance(duration, TimeInterface):\r\n time_unit = duration.time_unit\r\n # Otherwise, you might have given us a sampling_interval with a\r\n # time_unit attached:\r\n elif isinstance(sampling_interval, TimeInterface):\r\n time_unit = sampling_interval.time_unit\r\n\r\n # Calculate the sampling_interval or sampling_rate from each other and\r\n # assign t0, if it is not already assigned:\r\n if sampling_interval is None:\r\n if isinstance(sampling_rate, Frequency):\r\n c_f = time_unit_conversion[time_unit]\r\n sampling_interval = sampling_rate.to_period() / float(c_f)\r\n elif sampling_rate is None:\r\n data_len = np.asarray(data).shape[-1]\r\n sampling_interval = float(duration) / data_len\r\n sampling_rate = Frequency(1.0 / sampling_interval,\r\n time_unit=time_unit)\r\n else:\r\n c_f = time_unit_conversion[time_unit]\r\n sampling_rate = Frequency(sampling_rate, time_unit='s')\r\n sampling_interval = sampling_rate.to_period() / float(c_f)\r\n else:\r\n if sampling_rate is None: # Only if you didn't already 'inherit'\r\n # this property from another time object\r\n # above:\r\n if isinstance(sampling_interval, TimeInterface):\r\n c_f = time_unit_conversion[sampling_interval.time_unit]\r\n sampling_rate = Frequency(1.0 / (float(sampling_interval) /\r\n c_f),\r\n time_unit=sampling_interval.time_unit)\r\n else:\r\n sampling_rate = Frequency(1.0 / sampling_interval,\r\n time_unit=time_unit)\r\n\r\n #Calculate the duration, if that is not defined:\r\n if duration is None:\r\n duration = np.asarray(data).shape[-1] * sampling_interval\r\n\r\n if t0 is None:\r\n t0 = 0\r\n\r\n # Make sure to grab the time unit from the inputs, if it is provided:\r\n if time_unit is None:\r\n #If you gave us a duration with time_unit attached\r\n if isinstance(duration, TimeInterface):\r\n time_unit = duration.time_unit\r\n #Otherwise, you might have given us a sampling_interval with a\r\n #time_unit attached:\r\n elif isinstance(sampling_interval, TimeInterface):\r\n time_unit = sampling_interval.time_unit\r\n\r\n #Otherwise, you can still call the common constructor to get the real\r\n #object initialized, with time_unit set to None and that will generate\r\n #the object with time_unit set to 's':\r\n TimeSeriesBase.__init__(self, data, time_unit, metadata=metadata)\r\n\r\n self.time_unit = time_unit\r\n self.sampling_interval = TimeArray(sampling_interval,\r\n time_unit=self.time_unit)\r\n self.t0 = TimeArray(t0, time_unit=self.time_unit)\r\n self.sampling_rate = sampling_rate\r\n self.duration = TimeArray(duration, time_unit=self.time_unit)", "def test_datatype(self):\n dates = pd.date_range(start=\"2007-01-01\", end=\"2007-02-01\")\n\n ts = pd.DataFrame(\n {\n \"var1\": np.arange(len(dates), dtype=np.int8),\n \"var2\": np.arange(len(dates), dtype=np.int16),\n \"var3\": np.arange(len(dates), dtype=np.int32),\n \"var4\": np.arange(len(dates), dtype=np.int64)\n },\n index=dates)\n\n dataset_w = GriddedNcContiguousRaggedTs(self.testdatapath,\n self.grid,\n mode=\"w\")\n\n for gpi in self.gpis:\n dataset_w.write(gpi, ts)\n\n dataset_r = GriddedNcContiguousRaggedTs(self.testdatapath,\n self.grid,\n mode=\"r\")\n\n for gpi in self.gpis:\n arr = dataset_r.read(gpi)\n assert (arr[\"var1\"].dtype == np.int8)\n assert (arr[\"var2\"].dtype == np.int16)\n assert (arr[\"var3\"].dtype == np.int32)\n assert (arr[\"var4\"].dtype == np.int64)", "def validate_emission_input_data(self, emission):\n if emission:\n data = {}\n if emission.has_key('vehicleId'):\n data['vehicle_id'] = self.get_valid_emission_vehicle_id(emission['vehicleId'])\n else:\n raise InvalidUsage('vehicleId is an obligatory field.')\n \n if emission.has_key('vehicleType'):\n data['vehicle_type'] = self.get_valid_emission_vehicle_type(emission['vehicleType'])\n else:\n raise InvalidUsage('vehicleType is an obligatory field.')\n \n if emission.has_key('latitude'):\n data['latitude'] = self.get_valid_emission_latitude(emission['latitude'])\n else:\n raise InvalidUsage('latitude is an obligatory field.')\n \n if emission.has_key('longitude'):\n data['longitude'] = self.get_valid_emission_longitude(emission['longitude'])\n else:\n raise InvalidUsage('longitude is an obligatory field.')\n \n if emission.has_key('timestamp'):\n data['timestamp'] = self.get_valid_emission_timestamp(emission['timestamp'])\n else:\n data['timestamp'] = self.get_valid_emission_timestamp(None)\n \n if emission.has_key('heading'):\n data['heading'] = self.get_valid_emission_heading(emission['heading'])\n else:\n raise InvalidUsage('heading is an obligatory field.')\n \n return data\n \n else:\n raise InvalidUsage('emission can not be a empty body.')", "def format_data(self, raw_data):\n opz = raw_data.copy()\n opz['datetime'] = pd.to_datetime(opz['Datum-tijd'], format='%Y-%m-%dT%H:%M:%SZ')\n opz.drop(['Datum-tijd'],axis=1, inplace=True)\n opz['dag']=opz['datetime'].dt.day\n opz['tijd'] = opz['datetime'].dt.time\n #voeg open/dicht data toe en bepaal momenten waarop dit wisselt\n opz['Opzetstuk Noord (°)'] = opz['Opzetstuk Noord (°)'].str.replace(',', '.').astype(float)\n opz['Opzetstuk Zuid (°)'] = opz['Opzetstuk Zuid (°)'].str.replace(',', '.').astype(float)\n opz['Opzetstuk Noord (°)'].fillna(opz['Opzetstuk Zuid (°)'], inplace=True)\n opz['Opzetstuk Zuid (°)'].fillna(opz['Opzetstuk Noord (°)'], inplace=True)\n return opz", "def validate_metadata(self):\n\n # check sampling rate\n if self.has_data():\n # check start time\n if self.start != self.run_metadata.time_period.start:\n if (\n self.run_metadata.time_period.start\n != \"1980-01-01T00:00:00+00:00\"\n ):\n msg = (\n f\"start time of dataset {self.start} does not \"\n f\"match metadata start {self.run_metadata.time_period.start} \"\n f\"updating metatdata value to {self.start}\"\n )\n self.logger.warning(msg)\n self.run_metadata.time_period.start = self.start.iso_str\n\n # check end time\n if self.end != self.run_metadata.time_period.end:\n if (\n self.run_metadata.time_period.end\n != \"1980-01-01T00:00:00+00:00\"\n ):\n msg = (\n f\"end time of dataset {self.end} does not \"\n f\"match metadata end {self.run_metadata.time_period.end} \"\n f\"updating metatdata value to {self.end}\"\n )\n self.logger.warning(msg)\n self.run_metadata.time_period.end = self.end.iso_str\n if self.sample_rate != self.run_metadata.sample_rate:\n if self.run_metadata.sample_rate == 0.0:\n pass\n elif self.run_metadata.sample_rate is not None:\n msg = (\n f\"sample rate of dataset {self.sample_rate} does not \"\n f\"match metadata sample rate {self.run_metadata.sample_rate} \"\n f\"updating metatdata value to {self.sample_rate}\"\n )\n self.logger.warning(msg)\n self.run_metadata.sample_rate = self.sample_rate\n\n if self.run_metadata.id not in self.station_metadata.runs.keys():\n self.station_metadata.runs[0].update(self.run_metadata)\n\n self.station_metadata.update_time_period()\n self.survey_metadata.update_time_period()", "def test_cast_observation_date_sad_path(self):\n # a record without date value should throw an exception\n descriptor = self.descriptor\n schema = ObservationSchema(descriptor)\n record = {\n 'Latitude': \"-32\", 'Longitude': \"115.3\"\n }\n self.assertIsNone(schema.cast_record_observation_date(record))\n\n record = {\n 'Latitude': \"-32\", 'Observation Date': '', 'Longitude': \"115.3\"\n }\n self.assertIsNone(schema.cast_record_observation_date(record))\n\n record = {\n 'Latitude': \"-32\", 'Observation Date': 'bullshit', 'Longitude': \"115.3\"\n }\n with self.assertRaises(InvalidDateType):\n schema.cast_record_observation_date(record)\n\n record = {\n 'Latitude': \"-32\", 'Observation Date': 1200, 'Longitude': \"115.3\"\n }\n with self.assertRaises(InvalidDateType):\n schema.cast_record_observation_date(record)", "def ProcessData(self, data):\r\n ### ########################\r\n try:\r\n self.month = int(float(data['month']));\r\n except Exception as e:\r\n return False, \"A month must be provided.\";\r\n\r\n try:\r\n self.mosque_id = int(float(data['mosqueid']));\r\n except Exception as e:\r\n return False, \"A mosque ID must be provided.\";\r\n\r\n return True, None;", "def test_plt_mag_time():\n\n ta = WATA()\n wata_data = define_testdata()\n ta.source = ColumnDataSource(data=wata_data)\n ta.add_time_column()\n ta.setup_date_range()\n\n # create the arrays per filter and readout pattern\n nrsrapid_f140x, nrsrapid_f110w, nrsrapid_clear = [], [], []\n nrsrapidd6_f140x, nrsrapidd6_f110w, nrsrapidd6_clear = [], [], []\n filter_used, readout = ta.source.data['tafilter'], ta.source.data['readout']\n max_val_box, time_arr = ta.source.data['max_val_box'], ta.source.data['time_arr']\n for i, val in enumerate(max_val_box):\n if '140' in filter_used[i]:\n if readout[i].lower() == 'nrsrapid':\n nrsrapid_f140x.append(val)\n nrsrapid_f110w.append(np.NaN)\n nrsrapid_clear.append(np.NaN)\n nrsrapidd6_f140x.append(np.NaN)\n nrsrapidd6_f110w.append(np.NaN)\n nrsrapidd6_clear.append(np.NaN)\n elif readout[i].lower() == 'nrsrapidd6':\n nrsrapid_f140x.append(np.NaN)\n nrsrapid_f110w.append(np.NaN)\n nrsrapid_clear.append(np.NaN)\n nrsrapidd6_f140x.append(val)\n nrsrapidd6_f110w.append(np.NaN)\n nrsrapidd6_clear.append(np.NaN)\n elif '110' in filter_used[i]:\n if readout[i].lower() == 'nrsrapid':\n nrsrapid_f140x.append(np.NaN)\n nrsrapid_f110w.append(val)\n nrsrapid_clear.append(np.NaN)\n nrsrapidd6_f140x.append(np.NaN)\n nrsrapidd6_f110w.append(np.NaN)\n nrsrapidd6_clear.append(np.NaN)\n elif readout[i].lower() == 'nrsrapidd6':\n nrsrapid_f140x.append(np.NaN)\n nrsrapid_f110w.append(np.NaN)\n nrsrapid_clear.append(np.NaN)\n nrsrapidd6_f140x.append(np.NaN)\n nrsrapidd6_f110w.append(val)\n nrsrapidd6_clear.append(np.NaN)\n else:\n if readout[i].lower() == 'nrsrapid':\n nrsrapid_f140x.append(np.NaN)\n nrsrapid_f110w.append(np.NaN)\n nrsrapid_clear.append(val)\n nrsrapidd6_f140x.append(np.NaN)\n nrsrapidd6_f110w.append(np.NaN)\n nrsrapidd6_clear.append(np.NaN)\n elif readout[i].lower() == 'nrsrapidd6':\n nrsrapid_f140x.append(np.NaN)\n nrsrapid_f110w.append(np.NaN)\n nrsrapid_clear.append(np.NaN)\n nrsrapidd6_f140x.append(np.NaN)\n nrsrapidd6_f110w.append(np.NaN)\n nrsrapidd6_clear.append(val)\n # add to the bokeh data structure\n ta.source.data[\"nrsrapid_f140x\"] = nrsrapid_f140x\n ta.source.data[\"nrsrapid_f110w\"] = nrsrapid_f110w\n ta.source.data[\"nrsrapid_clear\"] = nrsrapid_clear\n ta.source.data[\"nrsrapidd6_f140x\"] = nrsrapidd6_f140x\n ta.source.data[\"nrsrapidd6_f110w\"] = nrsrapidd6_f110w\n ta.source.data[\"nrsrapidd6_clear\"] = nrsrapidd6_clear\n result = ta.plt_mag_time()\n\n assert bokeh_plot_type == type(result)" ]
[ "0.55926216", "0.54661906", "0.5444112", "0.53816944", "0.5362483", "0.5326546", "0.5323102", "0.52938086", "0.52288264", "0.522744", "0.5212353", "0.52054536", "0.51796585", "0.5146705", "0.5109984", "0.50910634", "0.5082423", "0.5068899", "0.5065601", "0.50507253", "0.5046317", "0.5046317", "0.5039348", "0.503811", "0.5037432", "0.5005337", "0.4995677", "0.49889842", "0.4988221", "0.49545613" ]
0.558016
1
Returns an instance of a chi.HierarchicalLoglikelihood based on the provided list of loglikelihoods and the population models.
def _create_hierarchical_log_likelihood(self, log_likelihoods): # Get covariates from the dataset if any are needed covariate_names = self.get_covariate_names() covariates = None if len(covariate_names) > 0: covariates = self._extract_covariates(covariate_names) log_likelihood = chi.HierarchicalLogLikelihood( log_likelihoods, self._population_model, covariates) return log_likelihood
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _create_log_likelihoods(self, ids):\n # Create a likelihood for each individual\n log_likelihoods = []\n for individual in ids:\n # Set dosing regimen\n if self._dosing_regimens:\n self._mechanistic_model.set_dosing_regimen(\n self._dosing_regimens[individual])\n\n log_likelihood = self._create_log_likelihood(individual)\n if log_likelihood is not None:\n # If data exists for this individual, append to log-likelihoods\n log_likelihoods.append(log_likelihood)\n\n if len(ids) == 1:\n return log_likelihoods[0]\n\n return log_likelihoods", "def figure_of_merit_from(self, parameter_list):\r\n return self.log_likelihood_from(parameter_list=parameter_list)", "def __init__(self, likelihoods):\n\t\tsuper(GroupedLikelihood, self).__init__()\n\t\tself.likelihoods = torch.nn.ModuleList(likelihoods)", "def objective_llh(self, params):\n\n try:\n obj = self.log_likelihood(params[0], params[1], params[2:])\n except (LinAlgError, ZeroDivisionError, ValueError):\n obj = -np.inf\n return obj", "def from_lists(\n cls,\n model: AbstractPriorModel,\n parameter_lists: List[List[float]],\n log_likelihood_list: List[float],\n log_prior_list: List[float],\n weight_list: List[float],\n ) -> List[\"Sample\"]:\n samples = list()\n\n paths = model.unique_prior_paths\n\n for params, log_likelihood, log_prior, weight in zip(\n parameter_lists, log_likelihood_list, log_prior_list, weight_list\n ):\n arg_dict = {t: param for t, param in zip(paths, params)}\n\n samples.append(\n cls(\n log_likelihood=log_likelihood,\n log_prior=log_prior,\n weight=weight,\n kwargs=arg_dict,\n )\n )\n return samples", "def __init__(self, likelihood_list, **kwargs):\n super().__init__(**kwargs)\n for l in likelihood_list:\n assert isinstance(l, Likelihood)\n self.likelihoods = likelihood_list", "def _create_log_likelihood(self, individual):\n # Get individuals data\n times = []\n observations = []\n mask = self._data[self._id_key] == individual\n data = self._data[mask][\n [self._time_key, self._obs_key, self._value_key]]\n for output in self._mechanistic_model.outputs():\n # Mask data for observable\n observable = self._output_observable_dict[output]\n mask = data[self._obs_key] == observable\n temp_df = data[mask]\n\n # Filter times and observations for non-NaN entries\n mask = temp_df[self._value_key].notnull()\n temp_df = temp_df[[self._time_key, self._value_key]][mask]\n mask = temp_df[self._time_key].notnull()\n temp_df = temp_df[mask]\n\n # Collect data for output\n times.append(temp_df[self._time_key].to_numpy())\n observations.append(temp_df[self._value_key].to_numpy())\n\n # # Count outputs that were measured\n # # TODO: copy mechanistic model and update model outputs.\n # # (Useful for e.g. control group and dose group training)\n # n_measured_outputs = 0\n # for output_measurements in observations:\n # if len(output_measurements) > 0:\n # n_measured_outputs += 1\n\n # Create log-likelihood and set ID to individual\n log_likelihood = chi.LogLikelihood(\n self._mechanistic_model, self._error_models, observations, times)\n log_likelihood.set_id(individual)\n\n return log_likelihood", "def LLwrapper(params):\n NLL = LogLikelihood(gauss, s)\n return NLL(params[0], params[1])", "def make_mlp_likelihood(model=None, model_config=None, wiener_params=None, **kwargs):\n\n def random(\n self,\n keep_negative_responses=True,\n add_model=False,\n add_model_parameters=False,\n add_outliers=False,\n keep_subj_idx=False,\n ):\n \"\"\"\n Generate random samples from a given model (the dataset matches the size of the respective observated dataset supplied as an attribute of self).\n \"\"\"\n\n # This can be simplified so that we pass parameters directly to the simulator ...\n theta = np.array(model_config[\"params_default\"], dtype=np.float32)\n keys_tmp = self.parents.value.keys()\n cnt = 0\n\n for param in model_config[\"params\"]:\n if param in keys_tmp:\n theta[cnt] = np.array(self.parents.value[param]).astype(np.float32)\n cnt += 1\n\n sim_out = simulator(theta=theta, model=model, n_samples=self.shape[0], max_t=20)\n\n # Add outliers:\n if add_outliers:\n if self.parents.value[\"p_outlier\"] > 0.0:\n sim_out = hddm_dataset_generators._add_outliers(\n sim_out=sim_out,\n p_outlier=self.parents.value[\"p_outlier\"],\n max_rt_outlier=1 / wiener_params[\"w_outlier\"],\n )\n\n sim_out_proc = hddm_preprocess(\n sim_out,\n keep_negative_responses=keep_negative_responses,\n keep_subj_idx=keep_subj_idx,\n add_model_parameters=add_model_parameters,\n )\n\n if add_model:\n sim_out_proc[\"model\"] = model\n\n return sim_out_proc\n\n def pdf(self, x):\n # Check if model supplied has only two choice options\n # If yes --> check if two-dimensional input (rt, response) or one-dimensional input (rt) --> processing depends on it\n # If not --> input x has to be two dimensional (rt, response) becasuse we can't deduce response from rt\n x = np.array(x, dtype=np.float32)\n\n if len(x.shape) == 1 or x.shape[1] == 1:\n rt = x\n response = rt / np.abs(rt)\n rt = np.abs(rt)\n elif x.shape[1] == 2:\n rt = x[:, 0]\n response = x[:, 1]\n\n params = np.array(\n [self.parents[param] for param in model_config[\"params\"]]\n ).astype(np.float32)\n\n return hddm.wfpt.wiener_like_nn_mlp_pdf(\n rt,\n response,\n params,\n p_outlier=self.parents.value[\"p_outlier\"],\n w_outlier=wiener_params[\"w_outlier\"],\n network=kwargs[\"network\"],\n )\n\n def cdf(self, x):\n # TODO: Implement the CDF method for neural networks\n return \"Not yet implemented\"\n\n def make_likelihood():\n likelihood_str = make_likelihood_str_mlp(\n config=model_config, wiener_params=wiener_params\n )\n exec(likelihood_str)\n my_fun = locals()[\"custom_likelihood\"]\n return my_fun\n\n # TODO: Allow for rt's of -999 in LAN likelihoods\n def make_likelihood_missing_data():\n return\n\n likelihood_ = make_likelihood()\n\n wfpt_nn = stochastic_from_dist(\"Wienernn_\" + model, partial(likelihood_, **kwargs))\n\n wfpt_nn.pdf = pdf\n wfpt_nn.cdf_vec = None # AF TODO: Implement this for neural nets (not a big deal actually but not yet sure where this is ever used finally)\n wfpt_nn.cdf = cdf\n wfpt_nn.random = random\n return wfpt_nn", "def log_likelihood_function(self, instance):\r\n\r\n xvalues = np.arange(self.data.shape[0])\r\n model_data = instance.profile_from_xvalues(xvalues=xvalues)\r\n residual_map = self.data - model_data\r\n chi_squared_map = (residual_map / self.noise_map) ** 2.0\r\n log_likelihood = -0.5 * sum(chi_squared_map)\r\n\r\n return log_likelihood", "def log_likelihood(self, y_list):\n if self.lambda_mat is None:\n raise ValueError(\"Can't compute model likelihood before fitting!\")\n\n # precision prior distribution given precision hyper-parameters\n prec_distr = stats.gamma(a=self.prec_distr[0],\n scale=self.prec_distr[1] ** -1.0)\n\n # likelihood of projection matrix precision priors given\n # precision hyper-parameters\n lambda_logl = np.sum(\n prec_distr.logpdf(self.lambda_mat['alpha']\n / self.lambda_mat['beta'])\n )\n\n # likelihood of projection matrix values given their precision priors\n a_logl = np.sum(\n stats.norm(loc=0, scale=(self.lambda_mat['beta']\n / self.lambda_mat['alpha']))\n .logpdf(self.A_mat['mu'])\n )\n\n # likelihood of latent feature matrix given kernel matrix,\n # projection matrix, and standard deviation hyper-parameter\n h_logl = np.sum(\n stats.norm(loc=self.A_mat['mu'].transpose() @ self.kernel_mat,\n scale=self.sigma_h)\n .logpdf(self.H_mat['mu'])\n )\n\n # likelihood of bias parameter precision priors given\n # precision hyper-parameters\n weight_prior_logl = np.sum(\n prec_distr.logpdf(np.array(self.weight_priors['alpha'])\n / np.array(self.weight_priors['beta']))\n )\n\n # likelihood of bias parameters given their precision priors\n weight_logl = np.sum(\n stats.norm(loc=0, scale=(np.array(self.weight_priors['beta'])\n / np.array(self.weight_priors['alpha'])))\n .logpdf(self.weight_mat['mu'])\n )\n\n # likelihood of predicted outputs given latent features, bias\n # parameters, and latent feature weight parameters\n f_logl = np.sum(\n stats.norm(\n loc=(self.weight_mat['mu'][1:, :].transpose()\n @ self.H_mat['mu']\n + np.vstack(self.weight_mat['mu'][0, :])),\n scale=1).logpdf(self.output_mat['mu'])\n )\n\n # likelihood of actual output labels given class separation margin\n # and predicted output labels\n y_logl = np.sum(self.get_y_logl(y_list))\n\n return (lambda_logl + a_logl + h_logl\n + weight_prior_logl + weight_logl + f_logl + y_logl)", "def GSM_log_likelihood(X, model):\n D, M = X.shape\n k = model.mix.shape[0]\n log_likelihood = 0\n for i in range(M):\n logpdf_X = 0\n for j in range(k):\n mvn = multivariate_normal(cov=model.cov[j, :])\n logpdf_X = mvn.logpdf(x=X[:, i]) * model.mix[j]\n log_likelihood += logpdf_X\n return log_likelihood", "def ICA_log_likelihood(X, model):\n\n # TODO: YOUR CODE HERE", "def __init__(self, model):\n TreeLikelihoodBase.__init__(self, model)", "def _compute_log_likelihood(self, parameters):\n raise NotImplementedError('')", "def compute_log_likelihood(self, indicators, weights, l2):\n scores, _ = self.predict_probability(self.train_feature_x, weights)\n probs = self.predict_probability(self.train_feature_x, weights)\n lp = np.sum((indicators-1)*scores + np.log(probs)) - l2* np.sum(weights[1:]**2)\n return lp", "def loglikelihood(self):\n raise NotImplementedError(\"To be implemented\")", "def log_likelihood(self, data, reward_model, bias_params):", "def build_model(inputs, num_classes, is_training, hparams):\n scopes = setup_arg_scopes(is_training)\n with contextlib.nested(*scopes):\n if hparams.model_name == 'pyramid_net':\n logits = build_shake_drop_model(\n inputs, num_classes, is_training)\n elif hparams.model_name == 'wrn':\n logits = build_wrn_model(\n inputs, num_classes, hparams.wrn_size)\n elif hparams.model_name == 'shake_shake':\n logits = build_shake_shake_model(\n inputs, num_classes, hparams, is_training)\n return logits", "def get_likelihoods(self, alleles):\n\n l = len(alleles)\n if l==2:\n result = self.likelihoods2(alleles)\n elif l==3:\n result = self.likelihoods3(alleles)\n elif l==4:\n result = self.likelihoods4(alleles)\n elif l==5:\n result = self.likelihoods5(alleles)\n else:\n result = self.likelihoods(alleles)\n return result", "def max_log_likelihood_gen_from(self) -> Generator:\r\n\r\n def func_gen(fit: af.Fit) -> Generator:\r\n galaxies = fit.instance.galaxies\r\n if hasattr(fit.instance, \"clumps\"):\r\n galaxies = galaxies + fit.instance.clumps\r\n\r\n return self.object_via_gen_from(fit=fit, galaxies=galaxies)\r\n\r\n return self.aggregator.map(func=func_gen)", "def log_likelihood(self, params):\n # extract the parameters\n m1 = params['m1']\n m2 = params['m2']\n DL = params['DL']\n Tc = params['Tc']\n iota = params['iota']\n phic = params['phic']\n psi = params['psi']\n thetaS = params['thetaS']\n phiS = params['phiS']\n\n # calculate the model\n model = self._model(time, m1, m2, DL, Tc, iota, phic, psi, thetaS, phiS)\n\n# # normalisation\n# norm = -0.5*self._ndata*LN2PI - self._ndata*self._logsigma\n\n# # chi-squared\n# chisq = np.sum(((self._data - model)/(self._sigma))**2)\n\n return -np.vdot(self._data - model,self._data - model)", "def compute_dollo_ml_tree(snv_log_likelihoods, leaf_name_groups=None):\n trees = dollo.tasks.create_trees(\n snv_log_likelihoods,\n sample_col='cluster_id',\n leaf_name_groups=leaf_name_groups,\n )\n\n results_table = dollo.tasks.compute_tree_log_likelihoods_mp(\n snv_log_likelihoods, trees,\n sample_col='cluster_id', variant_col='variant_id')\n\n ml_tree_id = results_table.set_index('tree_id')['log_likelihood'].idxmax()\n tree = trees[ml_tree_id]\n loss_prob = results_table.set_index('tree_id').loc[ml_tree_id, 'loss_prob']\n\n tree_annotations = dollo.run.annotate_posteriors(\n snv_log_likelihoods, tree, loss_prob=loss_prob,\n sample_col='cluster_id', variant_col='variant_id')\n\n return tree, tree_annotations", "def maximize_loglik(model_params: Union[CupidParams, CupidParamsCSHeteroxy, CupidParamsFcmnl],\n x_init: np.ndarray,\n lower: Optional[np.ndarray] = None,\n upper: Optional[np.ndarray] = None,\n checkgrad: Optional[bool] = False,\n verbose: Optional[bool] = False,\n fixed_vars: Optional[List[int]] = None,\n fixed_vals: Optional[List[float]] = None,\n options: Optional[Dict] = {'iprint': 1}) -> Tuple[float, np.ndarray, int]:\n n_params = x_init.size\n try:\n kc = KN_new()\n except:\n bs_error_abort(\"Failed to find a valid Knitro license.\")\n\n KN_add_vars(kc, n_params)\n\n # bounds, if any\n if lower is None:\n # not necessary since infinite\n KN_set_var_lobnds(kc, xLoBnds=np.full(n_params, -KN_INFINITY))\n else:\n KN_set_var_lobnds(kc, xLoBnds=lower)\n if upper is None:\n KN_set_var_upbnds(kc, xUpBnds=np.full(n_params, KN_INFINITY))\n else:\n KN_set_var_upbnds(kc, xUpBnds=upper)\n\n # Define an initial point. If not set, Knitro will generate one.\n KN_set_var_primal_init_values(kc, xInitVals=x_init)\n\n if fixed_vars is not None:\n assert fixed_vals is not None\n KN_set_var_fxbnds(kc, fixed_vars, fixed_vals)\n\n cb = KN_add_eval_callback(kc, evalObj=True, funcCallback=log_likelihood)\n\n KN_set_cb_user_params(kc, cb, model_params)\n\n KN_set_cb_grad(kc, cb, objGradIndexVars=KN_DENSE,\n gradCallback=grad_log_likelihood)\n\n KN_set_int_param(kc, KN_PARAM_OUTLEV, KN_OUTLEV_ALL)\n\n if checkgrad:\n # Perform a derivative check.\n KN_set_int_param(kc, KN_PARAM_DERIVCHECK, KN_DERIVCHECK_ALL)\n\n # Solve the problem.\n nStatus = KN_solve(kc)\n\n loglik_val, estimates = print_optimization_results(kc)\n\n print_stars()\n print(f\" Value of log-likelihood: {loglik_val: > 8.3f}\\n\")\n print()\n\n return loglik_val, np.array(estimates), nStatus", "def add_likelihood(self, likelihood):\n for n, f in enumerate(self.features):\n fname = \"%s:%s\" % (self.name, f)\n attribs = {\"id\":\"featureLikelihood:%s\" % fname,\"spec\":\"TreeLikelihood\",\"useAmbiguities\":\"true\"}\n if self.pruned:\n distribution = ET.SubElement(likelihood, \"distribution\",attribs)\n # Create pruned tree\n tree_id = \"Tree.t:prunedBeastlingTree.%s\" % fname\n tree = ET.SubElement(distribution, \"tree\", {\"id\":tree_id, \"spec\":\"beast.evolution.tree.PrunedTree\",\"quickshortcut\":\"true\",\"assert\":\"false\"})\n ET.SubElement(tree, \"tree\", {\"idref\":\"Tree.t:beastlingTree\"})\n ET.SubElement(tree, \"alignment\", {\"idref\":\"pruned_data_%s\"%fname})\n # Create pruned branchrate\n self.clock.add_pruned_branchrate_model(distribution, fname, tree_id)\n else:\n attribs[\"branchRateModel\"] = \"@%s\" % self.clock.branchrate_model_id\n attribs[\"tree\"] = \"@Tree.t:beastlingTree\"\n distribution = ET.SubElement(likelihood, \"distribution\",attribs)\n\n # Sitemodel\n self.add_sitemodel(distribution, f, fname)\n\n # Data\n self.add_feature_data(distribution, n, f, fname)", "def __calc_likelihood(self, *args):\n params = {}\n for i, p in enumerate(self._par_names):\n if self._par_islog[p]:\n params[p] = np.power(10., args[i])\n else:\n params[p] = args[i]\n return self.return_likelihood(params)", "def make_mlp_likelihood_reg(\n model=None, model_config=None, wiener_params=None, **kwargs\n):\n\n # Need to rewrite these random parts !\n def random(\n self,\n keep_negative_responses=True,\n add_model=False,\n add_model_parameters=False,\n add_outliers=False,\n keep_subj_idx=False,\n ):\n \"\"\"\n Function to sample from a regressor based likelihood. Conditions on the covariates.\n \"\"\"\n param_dict = deepcopy(self.parents.value)\n del param_dict[\"reg_outcomes\"]\n\n param_data = np.zeros(\n (self.value.shape[0], len(model_config[\"params\"])), dtype=np.float32\n )\n\n cnt = 0\n for tmp_str in model_config[\"params\"]:\n if tmp_str in self.parents[\"reg_outcomes\"]:\n # param_data[:, cnt] = param_dict[tmp_str].values\n param_data[:, cnt] = param_dict[tmp_str].loc[self.value.index].values\n\n for linked_indirect_regressor in param_links[tmp_str]:\n # param_data[:, cnt] = (\n # param_data[:, cnt]\n # + param_dict[linked_indirect_regressor].values\n # )\n\n param_data[:, cnt] = (\n param_data[:, cnt]\n + param_dict[linked_indirect_regressor]\n .loc[self.value.index]\n .values\n )\n\n for linked_indirect_beta in param_links_betas[tmp_str]:\n param_data[:, cnt] = (\n param_data[:, cnt]\n + param_dict[linked_indirect_beta[0]]\n * self.value[linked_indirect_beta[1]]\n )\n else:\n param_data[:, cnt] = param_dict[tmp_str]\n cnt += 1\n\n sim_out = simulator(\n theta=param_data, model=model, n_samples=1, max_t=20 # n_trials = size,\n )\n\n # Add outliers:\n if add_outliers:\n if self.parents.value[\"p_outlier\"] > 0.0:\n sim_out = hddm_dataset_generators._add_outliers(\n sim_out=sim_out,\n p_outlier=self.parents.value[\"p_outlier\"],\n max_rt_outlier=1 / wiener_params[\"w_outlier\"],\n )\n\n sim_out_proc = hddm_preprocess(\n sim_out,\n keep_negative_responses=keep_negative_responses,\n add_model_parameters=add_model_parameters,\n keep_subj_idx=keep_subj_idx,\n )\n\n if add_model:\n sim_out_proc[\"model\"] = model\n\n return sim_out_proc\n\n def pdf(self, x):\n return \"Not yet implemented\"\n\n def cdf(self, x):\n # TODO: Implement the CDF method for neural networks\n return \"Not yet implemented\"\n\n def make_likelihood():\n if indirect_betas_present or indirect_regressors_present:\n likelihood_str = make_reg_likelihood_str_mlp(\n config=model_config,\n wiener_params=wiener_params,\n param_links=param_links,\n param_links_betas=param_links_betas,\n )\n else:\n likelihood_str = make_reg_likelihood_str_mlp_basic(\n config=model_config,\n wiener_params=wiener_params,\n )\n\n exec(likelihood_str)\n my_fun = locals()[\"custom_likelihood_reg\"]\n return my_fun\n\n # TODO: Allow for missing data in LAN likelihoods\n def make_likelihood_missing_data():\n return\n\n param_links, indirect_regressors_present = __prepare_indirect_regressors(\n model_config=model_config\n )\n param_links_betas, indirect_betas_present = __prepare_indirect_betas(\n model_config=model_config\n )\n\n likelihood_ = make_likelihood()\n stoch = stochastic_from_dist(\"wfpt_reg\", partial(likelihood_, **kwargs))\n stoch.pdf = pdf\n stoch.cdf = cdf\n stoch.random = random\n return stoch", "def get_log_likelihood(response_probability, response):\n pass", "def log_likelihood_plot(samples,log_likelihoods, ncols, cmap = 'jet', samples_dir = None, record_list = None):\r\n\r\n num_elements = samples.shape[0]\r\n num_samples = samples.shape[1]\r\n height = samples.shape[2]\r\n width = samples.shape[3]\r\n num_channels = samples.shape[4]\r\n\r\n if not os.path.exists(samples_dir):\r\n os.makedirs(samples_dir)\r\n\r\n nrows = num_samples // ncols \r\n assert num_samples == nrows*ncols, \"Number of samples not equal to nrows*ncols\"\r\n\r\n for i in range(num_elements):\r\n elm_samples = samples[i]\r\n elm_likelihoods = log_likelihoods[i,:]\r\n # Sorted by negative log likelihood\r\n sorted_indices = np.argsort(-elm_likelihoods)\r\n sorted_likelihoods = elm_likelihoods[sorted_indices]\r\n sorted_samples = elm_samples[sorted_indices]\r\n # Normalize log likelihoods to be in 0-1 range\r\n min_ll, max_ll = sorted_likelihoods[-1], sorted_likelihoods[0]\r\n normalized_likelihoods = (sorted_likelihoods - min_ll)/(max_ll - min_ll)\r\n\r\n # For each sample, draw an image with a box proportional in size and color to the log-likelihood value\r\n ll_images = np.ones((num_samples,height,width,3))\r\n # Specify box sizes \r\n lower_width = width//2 - width//5\r\n upper_width = width//2 + width//5 \r\n max_box_height = height\r\n min_box_height = 1\r\n # Generate colors for the boxes\r\n convert_to_cmap = get_cmap(cmap)\r\n # Remove alpha channel from colormap\r\n colors = convert_to_cmap(normalized_likelihoods)[:,:-1]\r\n\r\n # Fill out images with boxes\r\n for sample_no in range(num_samples):\r\n norm_ll = normalized_likelihoods[sample_no]\r\n box_height = int(min_box_height + (max_box_height - min_box_height)*norm_ll)\r\n box_color = colors[sample_no]\r\n for j in range(3):\r\n ll_images[sample_no,height- box_height:height, lower_width:upper_width, j] = box_color[j]\r\n\r\n # Save images and boxes in decreasing order of log_likelihood \r\n img = np.zeros((2*num_samples,height,width,3))\r\n if num_channels == 1:\r\n img[0::2] = np.squeeze(np.stack((sorted_samples,)*3, axis=3))\r\n else:\r\n img[0::2] = sorted_samples\r\n img[1::2] = ll_images*255 \r\n img = np.reshape(img,(num_samples,2*height,width,3))\r\n\r\n final_img = (img.reshape(nrows,ncols,2*height,width,3)\r\n .swapaxes(1,2)\r\n .reshape(2*height*nrows,width*ncols,3)).astype('uint8')\r\n\r\n name = record_list[i]\r\n start_idx = name.rindex('/')\r\n end_idx = name.rindex('.')\r\n name = name[start_idx+1:end_idx]\r\n final_img_path = samples_dir + '/' + name + '_' + 'generated_likelihood.jpg'\r\n\r\n imsave(final_img_path, final_img)", "def log_likelihood(X, Z, variable_types):\n\tk = Z['pi_unconstrained'].shape[1]+1 # the number of mixture components\n\t## We gather the log probabilities of each indiv in batch for each mixture component into\n\t## a matrix of size (B x k), where B is the batch size.\n\tlogps = torch.zeros([len(X), k])\n\t## First insert the mixture weight contribution to the array\n\tlogps += logsoftmax(Z['pi_unconstrained'], dim=-1)\n\t## Next loop over the features and sum the contributions to logps\n\tfor i, (key, z) in enumerate(Z.items()):\n\t\tif key not in ['pi_unconstrained']:\n\t\t\tdata = torch.Tensor(X[key].values).unsqueeze(-1)\n\t\t\tdist = variable_types[key]\n\t\t\tif dist == 'Categorical':\n\t\t\t\talpha = softmax(z, dim=-1, additional=-50.)\n\t\t\t\tlogps += Categorical(probs = alpha).log_prob(data)\n\t\t\telif dist == 'Bernoulli':\n\t\t\t\ttheta = z\n\t\t\t\tlogps += Bernoulli(logits = theta).log_prob(data)\n\t\t\telif dist == 'Beta':\n\t\t\t\talpha, beta = torch.exp(z).transpose(0,1)\n\t\t\t\tlogps += Beta(alpha, beta).log_prob(data)\n\t## Compute logsumexp over the mixture components and return the sum over data elements.\n\tlogp = torch.logsumexp(logps, dim=-1)\n\treturn logp.sum()" ]
[ "0.57376385", "0.5609973", "0.5427306", "0.537937", "0.5340062", "0.5271139", "0.52402085", "0.5212378", "0.5142101", "0.5134181", "0.5104734", "0.5094124", "0.509232", "0.5073549", "0.50627905", "0.5023009", "0.5007841", "0.49988776", "0.4992658", "0.4934784", "0.49270967", "0.4868239", "0.48662978", "0.48417732", "0.4829989", "0.48205093", "0.47830316", "0.47747278", "0.47506368", "0.47477776" ]
0.73569417
0
Gets the relevant data for the individual and returns the resulting chi.LogLikelihood.
def _create_log_likelihood(self, individual): # Get individuals data times = [] observations = [] mask = self._data[self._id_key] == individual data = self._data[mask][ [self._time_key, self._obs_key, self._value_key]] for output in self._mechanistic_model.outputs(): # Mask data for observable observable = self._output_observable_dict[output] mask = data[self._obs_key] == observable temp_df = data[mask] # Filter times and observations for non-NaN entries mask = temp_df[self._value_key].notnull() temp_df = temp_df[[self._time_key, self._value_key]][mask] mask = temp_df[self._time_key].notnull() temp_df = temp_df[mask] # Collect data for output times.append(temp_df[self._time_key].to_numpy()) observations.append(temp_df[self._value_key].to_numpy()) # # Count outputs that were measured # # TODO: copy mechanistic model and update model outputs. # # (Useful for e.g. control group and dose group training) # n_measured_outputs = 0 # for output_measurements in observations: # if len(output_measurements) > 0: # n_measured_outputs += 1 # Create log-likelihood and set ID to individual log_likelihood = chi.LogLikelihood( self._mechanistic_model, self._error_models, observations, times) log_likelihood.set_id(individual) return log_likelihood
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def log_likelihood_function(self, instance):\r\n\r\n xvalues = np.arange(self.data.shape[0])\r\n model_data = instance.profile_from_xvalues(xvalues=xvalues)\r\n residual_map = self.data - model_data\r\n chi_squared_map = (residual_map / self.noise_map) ** 2.0\r\n log_likelihood = -0.5 * sum(chi_squared_map)\r\n\r\n return log_likelihood", "def log_likelihood(self, x):\n # set nuisance parameters to their central values!\n predictions = self.get_predictions(self.shortarray_to_array(x), nuisance=False)\n m_obj = flavio.Measurement['Pseudo-measurement for FastFit instance: ' + self.name]\n m_obs = m_obj.all_parameters\n prob_dict = m_obj.get_logprobability_all(predictions)\n ll = sum(prob_dict.values())\n return ll", "def _create_log_likelihoods(self, ids):\n # Create a likelihood for each individual\n log_likelihoods = []\n for individual in ids:\n # Set dosing regimen\n if self._dosing_regimens:\n self._mechanistic_model.set_dosing_regimen(\n self._dosing_regimens[individual])\n\n log_likelihood = self._create_log_likelihood(individual)\n if log_likelihood is not None:\n # If data exists for this individual, append to log-likelihoods\n log_likelihoods.append(log_likelihood)\n\n if len(ids) == 1:\n return log_likelihoods[0]\n\n return log_likelihoods", "def get_log_likelihood(response_probability, response):\n pass", "def bayesian_info_criterion(log_likelihood, n_params, n_samples):\n return n_params * np.log(n_samples) - 2.0 * log_likelihood", "def get_log_prob(self, latent, obs):\n return self.get_log_prob_from_latent_dist(self.get_latent_dist(obs), latent)", "def get_log_likelihood(response_probability, observed_response):\n \n return np.log(response_probability[observed_response])", "def log_likelihood(self, params):\n # extract the parameters\n m1 = params['m1']\n m2 = params['m2']\n DL = params['DL']\n Tc = params['Tc']\n iota = params['iota']\n phic = params['phic']\n psi = params['psi']\n thetaS = params['thetaS']\n phiS = params['phiS']\n\n # calculate the model\n model = self._model(time, m1, m2, DL, Tc, iota, phic, psi, thetaS, phiS)\n\n# # normalisation\n# norm = -0.5*self._ndata*LN2PI - self._ndata*self._logsigma\n\n# # chi-squared\n# chisq = np.sum(((self._data - model)/(self._sigma))**2)\n\n return -np.vdot(self._data - model,self._data - model)", "def get_log_prob(self, latent, obs, obs_id, get_accuracy=False):\n if self.use_alphabet:\n obs, alphabet = obs\n else:\n alphabet = None\n num_particles, batch_size, num_arcs, _ = latent.shape\n _, num_rows, num_cols = obs.shape\n latent_log_prob = self.get_latent_dist(alphabet).log_prob(latent)\n\n obs_dist = self.get_obs_dist(latent.view(num_particles * batch_size, num_arcs, 2))\n if hasattr(obs_dist, \"log_prob_with_id\"):\n obs_log_prob, accuracy = obs_dist.log_prob_with_id(\n obs[None]\n .expand(num_particles, batch_size, num_rows, num_cols)\n .reshape(num_particles * batch_size, num_rows, num_cols),\n obs_id[None].expand(num_particles, batch_size).reshape(num_particles * batch_size),\n get_accuracy=True,\n )\n obs_log_prob = obs_log_prob.view(num_particles, batch_size)\n else:\n obs_log_prob = obs_dist.log_prob(\n obs[None]\n .expand(num_particles, batch_size, num_rows, num_cols)\n .reshape(num_particles * batch_size, num_rows, num_cols)\n ).view(num_particles, batch_size)\n accuracy = None\n\n if hasattr(self, \"likelihood_weight\"):\n obs_log_prob = obs_log_prob * self.likelihood_weight\n\n if get_accuracy:\n return latent_log_prob + obs_log_prob, accuracy\n else:\n return latent_log_prob + obs_log_prob", "def log_likelihood(self):\n\n if self._log_likelihood is None:\n self._log_likelihood = logpdf(x=self.y, cov=self.S)\n return self._log_likelihood", "def get_log_probss(self, latent, obs, obs_id):\n\n if self.use_alphabet:\n obs, alphabet = obs\n else:\n alphabet = None\n\n num_particles, batch_size, num_arcs, _ = latent.shape\n _, num_rows, num_cols = obs.shape\n latent_log_prob = self.get_latent_dist(alphabet).log_prob(latent)\n obs_dist = self.get_obs_dist(latent.view(num_particles * batch_size, num_arcs, 2))\n if hasattr(obs_dist, \"log_prob_with_id\"):\n obs_log_prob = obs_dist.log_prob_with_id(\n obs[None]\n .expand(num_particles, batch_size, num_rows, num_cols)\n .reshape(num_particles * batch_size, num_rows, num_cols),\n obs_id[None].expand(num_particles, batch_size).reshape(num_particles * batch_size),\n ).view(num_particles, batch_size)\n else:\n obs_log_prob = obs_dist.log_prob(\n obs[None]\n .expand(num_particles, batch_size, num_rows, num_cols)\n .reshape(num_particles * batch_size, num_rows, num_cols)\n ).view(num_particles, batch_size)\n\n if hasattr(self, \"likelihood_weight\"):\n obs_log_prob = obs_log_prob * self.likelihood_weight\n\n return latent_log_prob, obs_log_prob", "def loglikelihood(model, data, q):\n\tph, pvh = model\n\tnPeople, nQuestions = data.shape\n\tlogL = 0\n\tfor i in range(nPeople):\n\t\tanswers = data[i,:]\n\t\tfor k in range(nQuestions):\n\t\t\tlogL += np.log(sum(pvh[:, k, int(answers[k] - 1)] * q[i,:].T))\n\treturn logL", "def log_likelihood(self, data, reward_model, bias_params):", "def log_likelihood(self):\r\n assert not self.likelihood.is_heteroscedastic\r\n A = -0.5*self.batchsize*self.output_dim*(np.log(2.*np.pi) - np.log(self.likelihood.precision))\r\n B = -0.5*self.likelihood.precision*self.output_dim*self.trace_K\r\n Kmm_logdet = 2.*np.sum(np.log(np.diag(self.Lm)))\r\n C = -0.5*self.output_dim*self.data_prop*(Kmm_logdet-self.q_u_logdet - self.num_inducing)\r\n C += -0.5*np.sum(self.LQL * self.B)\r\n D = -0.5*self.likelihood.precision*self.likelihood.trYYT\r\n E = np.sum(self.V*self.projected_mean)\r\n return (A+B+C+D+E)/self.data_prop", "def ICA_log_likelihood(X, model):\n\n # TODO: YOUR CODE HERE", "def log_likelihood(self):\r\n return (-0.5 * self.num_data * self.output_dim * np.log(2.*np.pi) -\r\n 0.5 * self.output_dim * self.K_logdet + self._model_fit_term() + self.likelihood.Z)", "def logistic(weights, data, targets, hyperparameters):\n\n # TODO: Finish this function\n\n return f, df, y", "def log_likelihood(self, x):\n return self.log_likelihood_exp(x) + self.log_prior_nuisance_parameters(x)", "def my_loglike(theta, x, data, sigma):\n\n model = my_model(theta, x)\n\n return -0.5*len(x)*np.log(2*math.pi*sigma**2) - (0.5/sigma**2) * np.sum((data-model)**2)", "def get_log_marginal_likelihood(self, mode='BIC'):\n if mode == 'BIC':\n if not self.isOptimized:\n print('Parameters have not been optimized; training now')\n self.train()\n if self.BICscore is None:\n BIC = 0\n for i, model in enumerate(self.models):\n n = model.n \n k = model.m.num_params\n L = model.m.log_likelihood()\n BIC += L - k/2*np.log(n)\n self.BICscore = BIC\n return self.BICscore\n elif mode in ['laplace', 'Laplace']:\n raise NotImplementedError('Laplace approximation is not yet implemented')\n elif mode == 'AIS':\n raise NotImplementedError('Annealed importance sampling is not yet implemented')\n else:\n raise NotImplementedError('Unrecognized marginal likelihood approximation {:s}'.format(mode))", "def get_log_marginal_likelihood(self, mode='BIC'):\n if mode == 'BIC':\n if not self.isOptimized:\n print('Parameters have not been optimized; training now')\n self.train()\n \n if self.BICscore is None:\n k = self.m.num_params\n L = self.m.log_likelihood()\n BIC = L - k/2*np.log(self.n)\n self.BICscore = BIC\n return self.BICscore\n elif mode in ['laplace', 'Laplace']:\n raise NotImplementedError('Laplace approximation is not yet implemented')\n elif mode == 'AIS':\n raise NotImplementedError('Annealed importance sampling is not yet implemented')\n else:\n raise NotImplementedError('Unrecognized marginal likelihood approximation {:s}'.format(mode))", "def _get_logit(self, input, target_idx, noise_idx):\n\n target_logit, noise_logit = self.get_score(input, target_idx, noise_idx)\n\n target_logit = target_logit.sub(self.norm_term)\n noise_logit = noise_logit.sub(self.norm_term)\n return target_logit, noise_logit", "def Likelihood(self, data, hypo):\n p_correct = hypo\n score = data\n\n k = self.exam.Reverse(score)\n n = self.exam.max_score\n like = thinkbayes2.EvalBinomialPmf(k, n, p_correct)\n return like", "def loglikelihood(self):\n raise NotImplementedError(\"To be implemented\")", "def log_likelihood_function(self, instance: af.ModelInstance) -> float:\r\n model_data = self.model_data_from_instance(instance=instance)\r\n fit = self.fit_from_model_data(model_data=model_data)\r\n return fit.log_likelihood", "def log_likelihood(self):\n return -0.5*self.D*self.K_logdet + self._model_fit_term() + self.likelihood.Z", "def log_likelihood(self):\r\n if self.likelihood.is_heteroscedastic:\r\n A = -0.5 * self.num_data * self.output_dim * np.log(2.*np.pi) + 0.5 * np.sum(np.log(self.likelihood.precision)) - 0.5 * np.sum(self.likelihood.V * self.likelihood.Y)\r\n B = -0.5 * self.output_dim * (np.sum(self.likelihood.precision.flatten() * self.psi0) - np.trace(self._A))\r\n else:\r\n A = -0.5 * self.num_data * self.output_dim * (np.log(2.*np.pi) - np.log(self.likelihood.precision)) - 0.5 * self.likelihood.precision * self.likelihood.trYYT\r\n B = -0.5 * self.output_dim * (np.sum(self.likelihood.precision * self.psi0) - np.trace(self._A))\r\n C = -self.output_dim * (np.sum(np.log(np.diag(self.LB)))) # + 0.5 * self.num_inducing * np.log(sf2))\r\n D = 0.5 * self.data_fit\r\n self._A_part, self._B_part, self._C_part, self._D_part = A, B, C, D\r\n return A + B + C + D + self.likelihood.Z", "def _compute_log_likelihood(self, X, S):\n log_likelihood = 0\n for n in range(self.n_col):\n likelihood = 1\n for k in range(self.n_components):\n likelihood *= self.weights[k] \\\n * multivariate_normal(self.means[k], self.covs[k]).pdf(X[n]) \\\n * poisson(self.rates[k]).pmf(S[n])\n log_likelihood += np.log(likelihood)\n\n return log_likelihood", "def getLikelihood(self, caliStep):\n\n # state vector y_t = H(x_t)+Sigma_t\n stateVec = self.yadeData[caliStep, :, :].dot(self.__obsMatrix)\n obsVec = self.obsData[caliStep, :]\n\n # row-wise subtraction obsVec[numObs]-stateVec[numSamples,numObs]\n vecDiff = obsVec - stateVec\n Sigma = self.getCovMatrix(caliStep, self.obsWeights)\n invSigma = np.linalg.inv(Sigma)\n likelihood = np.zeros(self.numSamples)\n\n # compute likelihood = exp(-0.5*(y_t-H(x_t))*Sigma_t^{-1}*(y_t-H(x_t)))\n for i in range(self.numSamples):\n power = (vecDiff[i, :]).dot(invSigma.dot(vecDiff[i, :].T))\n likelihood[i] = np.exp(-0.5 * power)\n\n # regularize likelihood\n likelihood /= np.sum(likelihood)\n return likelihood", "def log_likelihood_function(self, instance) -> float:\n return self.prior.factor(instance[0])" ]
[ "0.593657", "0.5863257", "0.57026047", "0.56884336", "0.5661554", "0.56269956", "0.55965257", "0.5575074", "0.5520455", "0.5502658", "0.5476224", "0.54435015", "0.5408902", "0.540859", "0.53706634", "0.53657186", "0.5365584", "0.5350838", "0.5345029", "0.5338034", "0.5330534", "0.531789", "0.5287897", "0.5282496", "0.5278607", "0.52624726", "0.52624655", "0.52504915", "0.52432084", "0.5239725" ]
0.7430913
0
Extracts covariates from the pandas.DataFrame and formats them as a np.ndarray of shape (n, c).
def _extract_covariates(self, covariate_names): # Format covariates to array of shape (n, c) c = len(covariate_names) n = len(self._ids) covariates = np.empty(shape=(n, c)) for idc, name in enumerate(covariate_names): mask = self._data[self._obs_key] == self._covariate_dict[name] temp = self._data[mask] for idn, _id in enumerate(self._ids): mask = temp[self._id_key] == _id covariates[idn, idc] = \ temp.loc[mask, self._value_key].dropna().values return covariates
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def X(self) -> np.ndarray:\n cols = [col for col in self._obj.names.covariates if col in self._obj.columns]\n if not cols:\n raise KeyError(\"No known covariates in CausalFrame\")\n return self._obj[cols].to_numpy()", "def get_codon_arr(chromosome: Chromosome) -> np.ndarray:\n\n seq_len = len(chromosome.sequence)\n arr = np.zeros((seq_len - 2,), dtype=np.int)\n\n for f in chromosome.features:\n\n if f.type != 'CDS':\n continue\n if f.strand == '-':\n continue\n\n protein_len = (f.end - f.start) // 3\n for aa in range(protein_len):\n pos = f.start + (aa * 3) - 1 # -1 to 0-based\n arr[pos] = 1\n\n return arr", "def get_covariates_df(dataset_name: str) -> pd.DataFrame:\n path = Path(dataset_name) / COVARIATES_FILE\n return get_dataframe(path)", "def get_pca_vectors(dataframe):\n vectors = list()\n # Use the \"components\" to define the direction of the vectors,\n # and the \"explained variance\" to define the squared-length of the vectors.\n for idx, row in dataframe.iterrows():\n v = row[['x', 'y']].values * np.sqrt(row['var_expl']) * 3 # Scale up for better visibility.\n mean = row[['meanx', 'meany']].values\n mean_offset = (mean, mean + v)\n vectors.append(mean_offset)\n \n return vectors", "def cov(self) -> 'DataFrame':\n if self._is_string():\n raise TypeError('DataFrame consists only of strings. Must have int, float, '\n 'or bool columns')\n\n x: ndarray = self._values_number()\n if x.dtype.kind == 'i':\n x0: ndarray = x[0]\n x_diff: ndarray = x - x0\n Exy: ndarray = (x_diff.T @ x_diff)\n Ex: ndarray = x_diff.sum(0)[np.newaxis, :]\n ExEy: ndarray = Ex.T @ Ex\n counts: Union[int, ndarray] = len(x)\n else:\n x0 = _math.get_first_non_nan(x)\n x_diff = x - x0\n x_not_nan: ndarray = (~np.isnan(x)).astype(int)\n\n x_diff_0: ndarray = np.nan_to_num(x_diff)\n counts = (x_not_nan.T @ x_not_nan)\n Exy = (x_diff_0.T @ x_diff_0)\n Ex = (x_diff_0.T @ x_not_nan)\n ExEy = Ex * Ex.T\n\n with np.errstate(invalid='ignore'):\n cov: ndarray = (Exy - ExEy / counts) / (counts - 1)\n\n new_data: Dict[str, ndarray] = {'f': np.asfortranarray(cov)}\n new_column_info: ColInfoT = {'Column Name': utils.Column('S', 0, 0)}\n new_columns: ndarray = np.empty(x.shape[1] + 1, dtype='O')\n new_columns[0] = 'Column Name'\n\n i: int = 0\n for col, dtype, loc in self._col_info_iter(): # type: str, str, int\n if dtype not in 'ifb':\n continue\n new_column_info[col] = utils.Column('f', i, i + 1)\n new_columns[i + 1] = col\n i += 1\n new_data['S'] = np.asfortranarray(new_columns[1:])[:, np.newaxis]\n return self._construct_from_new(new_data, new_column_info,\n np.asarray(new_columns, dtype='O'))", "def contours_to_arrays(gdf, col): \n\n coords_zvals = []\n\n for i in range(0, len(gdf)):\n\n val = gdf.iloc[i][col]\n\n try:\n coords = np.concatenate([np.vstack(x.coords.xy).T \n for x in gdf.iloc[i].geometry])\n except:\n coords = np.vstack(gdf.iloc[i].geometry.coords.xy).T\n\n coords_zvals.append(np.column_stack((coords, \n np.full(np.shape(coords)[0], \n fill_value=val))))\n\n return np.concatenate(coords_zvals)", "def _make_2D_array(df, data_col='Sample DNA Concentration',\n well_col='Well', rows=8, cols=12):\n # initialize empty Cp array\n cp_array = np.empty((rows, cols), dtype=object)\n\n # fill Cp array with the post-cleaned values from the right half of the\n # plate\n for record in df.iterrows():\n row = ord(str.upper(record[1][well_col][0])) - ord('A')\n col = int(record[1][well_col][1:]) - 1\n cp_array[row, col] = record[1][data_col]\n\n return cp_array", "def dataframe_to_array(df: pd.DataFrame) -> np.ndarray:\n\n if isinstance(df, pd.Series):\n x_array = df\n elif isinstance(df, pd.DataFrame):\n nb_vars = df.shape[1]\n varlist = df.columns\n x_array = df[varlist[0]]\n if nb_vars > 1:\n for k in range(1, nb_vars):\n x_array = x_array.astype(str) + \"_&_\" + df[varlist[k]].astype(str)\n else:\n raise AssertionError(\"The input data is not a pandas dataframe\")\n\n return np.asarray(x_array.to_numpy())", "def coeff_variation(df):\r\n\r\n\tdf_coeff_dict = dict()\r\n\r\n\tfor i, col in enumerate(df.columns):\r\n\t\tdf_coeff_dict[col] = [df[col].std() / df[col].mean()]\r\n\r\n\tdf_coeff = pd.DataFrame(df_coeff_dict, index=['Coeefficient of Variation'])\r\n\tpd.set_option('precision', 2) # set output display precision in 2 decimal places\r\n\r\n\treturn df_coeff", "def ca_to_coils_second_df(agent_df):", "def cc_cov(r, **kwargs):\r\n sample_corr = r.corr()\r\n n_assets = len(r.columns)\r\n avg_distinct_rho = (sample_corr.values.sum() - n_assets) / (\r\n n_assets * (n_assets - 1)) # Taking avg of off diagonal corr matrix on one side\r\n const_corr = np.full_like(sample_corr, avg_distinct_rho)\r\n np.fill_diagonal(const_corr, 1.)\r\n sd = r.std()\r\n # Convert to cov using statsmodel\r\n const_cov_sm = mh.corr2cov(const_corr, sd)\r\n # Convert to cov using formula and outer product - alternate way is to use sd @ sd.T instead of np.outer(sd, sd) -> yields matrix(mxm)\r\n const_cov = const_corr * np.outer(sd, sd)\r\n return pd.DataFrame(const_cov, columns=r.columns, index=r.columns)", "def get_corr(self):\r\n cov = self.data.values\r\n with np.errstate(divide='ignore', invalid='ignore'):\r\n coeff = np.true_divide(1, self.get_std().values)\r\n coeff[~ np.isfinite(coeff)] = 0 # -inf inf NaN\r\n corr = np.multiply(np.multiply(cov, coeff).T, coeff)\r\n df = pd.DataFrame(\r\n corr,\r\n index=self.data.index,\r\n columns=self.data.columns,\r\n )\r\n return self.__class__(df)", "def cov_to_corr(cy):\n \n N = len(cy)\n \n corr = np.zeros((N,N))\n \n sd = np.sqrt(np.diag(cy))\n \n sdinv = np.diag(1/sd)\n \n corr = np.dot(np.dot(sdinv,cy),sdinv)\n \n #print(np.shape(corr))\n return corr", "def covariates(self):\n return None", "def make_numpy_matrix(df,variables):\n observations = []\n for col in variables:\n observations.append(np.array(df[col]))\n observations = np.mat(observations).transpose().A #annoying numpy magic, and Tim loves it\n print observations.shape\n return observations", "def get_covariate_pairs(self):\n if self.covariate_field not in self.matrix.obs.columns:\n raise ValueError(\"Covariate value not available in dataset\")\n from itertools import product\n covariate = set(self.matrix.obs[self.covariate_field])\n return product(covariate, covariate)", "def build_cov_dataset(self):\n return self.ini_eeg_f[:, :, self.mask_tri].copy()", "def get_process_covariance_matrix(dt):\n # a = np.array([\n # [0.25 * dt ** 4, 0.5 * dt ** 3, 0.5 * dt ** 2],\n # [0.5 * dt ** 3, dt ** 2, dt],\n # [0.5 * dt ** 2, dt, 1]\n # ])\n\n a = np.array([\n [dt ** 6 / 36., dt ** 5 / 24., dt ** 4 / 6.],\n [dt ** 5 / 24., 0.25 * dt ** 4, 0.5 * dt ** 3],\n [dt ** 4 / 6., 0.5 * dt ** 3, dt ** 2]\n ])\n return a", "def test_roundtrip_from_dataframe2(self):\n import pandas as pd\n df = pd.DataFrame(data={\n 'a': np.arange(3),\n 'b': np.arange(3)[::-1]\n })\n ca = carray(df, dtype=np.dtype(np.float))\n assert_array_equal(df, ca)\n self.assertEqual(ca.dtype, np.dtype(np.float),\n msg='carray has been created with invalid dtype')", "def get_correlation(df):\n frame_correlation = df.corr()\n return frame_correlation", "def vnC(self):\n return np.array(\n [x for x in [self.nCx, self.nCy, self.nCz] if x is not None],\n dtype=int\n )", "def get_data_matrix(df):\n return df[[\"Open\", \"High\", 'Low', \"Close\"]].to_numpy()", "def get_pca_data(dataframe):\n # We don't reduce dimensionality, but overlay the 2 principal components in 2D.\n pca = PCA(n_components=2)\n \n x = dataframe[['df1', 'df2']].values\n try:\n # df1 and df2 have the same scale. No need to standardize. Standardizing might actually distort PCA here.\n pca.fit(x)\n except ValueError:\n # Return empty.\n df = pd.DataFrame(columns=['var_expl', 'var_expl_ratio', 'x', 'y', 'meanx', 'meany'])\n else:\n df = pd.DataFrame({'var_expl': pca.explained_variance_.T,\n 'var_expl_ratio': pca.explained_variance_ratio_.T * 100, # In percent\n 'x': pca.components_[:, 0],\n 'y': pca.components_[:, 1],\n 'meanx': pca.mean_[0],\n 'meany': pca.mean_[1],\n },\n index=[1, 2] # For designating principal components.\n )\n df.index.rename('PC', inplace=True)\n return df", "def calcCovarianceMatrix(data):\n # Create covariance matrix and array to store the mean values for x_mean, y_mean, z_mean\n C = np.zeros((data.shape[1], data.shape[1]))\n mean_xyz = []\n # Calculate all mean values\n for i in range(0, data.shape[1]):\n mean_xyz.append(data[:,i].mean())\n mean_xyz = np.array(mean_xyz)\n # Check whether dimensions agree \n if data[:,0].size != data[:,1].size or data[:,0].size != data[:,2].size:\n print \"X, Y and Z must be of same dimensions.\"\n else:\n # For each row in covariance matrix C\n for i in range(0, C.shape[0]):\n # For each column in covariance matrix C\n for j in range(0, C.shape[1]):\n C[i,j] = 0\n # For each point in the dataset, access x, y, z-values\n for point in data:\n # For each point, access x,y and z in all combinations (xx, xy, xz, yx, yy, yz etc)\n C[i][j] = C[i][j] + (point[i]-mean_xyz[i])*(point[j]-mean_xyz[j])\n # Divide by the total number of points \n C = (1.0/data.shape[0]) * C\n return C", "def format_and_annualise(self, raw_cov_array):\n assets = self.X.columns\n return (\n pd.DataFrame(raw_cov_array, index=assets, columns=assets) * self.frequency\n )", "def reshape_df(df, x_list, y_list, x, y, c):\n c_vals = []\n for yn in y_list:\n row = []\n dfy = df[df[y] == yn]\n for xn in x_list:\n dfyx = dfy[dfy[x] == xn]\n if len(dfyx) == 1:\n row.append(dfyx[c].values[0])\n else:\n row.append(np.NaN)\n c_vals.append(row)\n return c_vals", "def _as_numpy(_1d_h2o_frame):\n f = _check_is_1d_frame(_1d_h2o_frame)\n \n nm = str(f.columns[0])\n return f[nm].as_data_frame(use_pandas=True)[nm].values", "def generate(data: pd.DataFrame) -> np.ndarray:\n # TODO tests\n return data.apply(pd.to_numeric, errors='coerce')", "def make_xyz(df: pd.DataFrame,\n response_var: list,\n fixed_var: list = ['Sex']) -> np.ndarray:\n x = pd.get_dummies(df[fixed_var]).to_numpy()\n x = np.fliplr(x)\n n_animals = df.shape[0] # to fix z the the same shape\n z = np.identity(n_animals)[1]\n y = df[[response_var]].to_numpy()\n\n return x, z, y", "def prepare_covariates(self, nodes):\n size = len(nodes)\n X = np.zeros((size, 2))\n print(\"Indiv shape: \", X.shape)\n return np.array(X)" ]
[ "0.6590012", "0.617049", "0.61693865", "0.60362846", "0.5884417", "0.5769841", "0.5732126", "0.570601", "0.5662892", "0.5627514", "0.55737424", "0.55586195", "0.5551977", "0.5550387", "0.551459", "0.54919827", "0.54874426", "0.54502755", "0.5422454", "0.54132974", "0.5411954", "0.54087126", "0.5408162", "0.53901577", "0.5368243", "0.5361488", "0.53551924", "0.5348061", "0.5339839", "0.53332007" ]
0.64851564
1
Converts the dosing regimens defined by the pandas.DataFrame into myokit.Protocols, and returns them as a dictionary with individual IDs as keys, and regimens as values. For each dose entry in the dataframe a dose event is added to the myokit.Protocol. If the duration of the dose is not provided a bolus dose of duration 0.01 time units is assumed.
def _extract_dosing_regimens(self, dose_key, duration_key): # Create duration column if it doesn't exist and set it to default # bolus duration of 0.01 if duration_key is None: duration_key = 'Duration in base time unit' self._data[duration_key] = 0.01 # Extract regimen from dataset regimens = dict() for label in self._ids: # Filter times and dose events for non-NaN entries mask = self._data[self._id_key] == label data = self._data[ [self._time_key, dose_key, duration_key]][mask] mask = data[dose_key].notnull() data = data[mask] mask = data[self._time_key].notnull() data = data[mask] # Add dose events to dosing regimen regimen = myokit.Protocol() for _, row in data.iterrows(): # Set duration duration = row[duration_key] if np.isnan(duration): # If duration is not provided, we assume a bolus dose # which we approximate by 0.01 time_units. duration = 0.01 # Compute dose rate and set regimen dose_rate = row[dose_key] / duration time = row[self._time_key] regimen.add(myokit.ProtocolEvent(dose_rate, time, duration)) regimens[label] = regimen return regimens
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _df_to_cellchat_format(self, df_to_convert) -> dict:\n interactions_dataframes = {}\n\n for _, row in df_to_convert.iterrows():\n df = pd.DataFrame(index=self.cell_types, columns=self.cell_types)\n\n for cell_type_i in self.cell_types:\n for cell_type_j in self.cell_types:\n interaction_name = f\"{cell_type_i}|{cell_type_j}\"\n df.loc[cell_type_i, cell_type_j] = row[interaction_name]\n\n interactions_dataframes[row.interacting_pair] = df\n\n return interactions_dataframes", "def create_network_dict(df, years):\n\n networks = {}\n for year in years:\n print('Creating network for %d...' % year)\n networks[year] = create_dot_network(df, str(year))\n\n return networks", "def url_to_df(url, station_name, dictionary):\n \n path_to_data = os.path.join(et.data.get_data(url=url))\n \n dataframe = pd.read_csv(path_to_data)\n \n dataframe['Station ID'] = station_name\n \n output_dataframe = dataframe[['Station ID', 'year', 'month', 'day', 'doy',\n 'sm_5cm', 'sm_10cm', 'sm_20cm', 'sm_50cm', 'sm_100cm']]\n \n output_dataframe['month'].replace({1: \"Jan\", 2: \"Feb\", 3: \"Mar\", \n 4: \"Apr\", 5: \"May\", 6: \"Jun\", \n 7: \"Jul\", 8: \"Aug\", 9: \"Sep\", \n 10: \"Oct\", 11: \"Nov\", 12: \"Dec\"}, \n inplace=True)\n \n cut_labels = ['decad0', 'decad1', 'decad2']\n cut_bins = [0, 10, 20, 31]\n output_dataframe['decad'] = pd.cut(output_dataframe['day'], bins=cut_bins, labels=cut_labels)\n \n cut_labels = ['pentad0', 'pentad1', 'pentad2', 'pentad3', 'pentad4', 'pentad5']\n cut_bins = [0, 5, 10, 15, 20, 25, 31]\n output_dataframe['pentad'] = pd.cut(output_dataframe['day'], bins=cut_bins, labels=cut_labels)\n \n dictionary.update({station_name: output_dataframe})", "def create_cris_data_dict(df, filename, outdir):\n json_dict = {}\n for key in df.keys():\n if key != 'participant_id':\n json_dict[key] = {'Units': key.split()[-1]}\n else:\n json_dict[key] = {'Description': 'OpenNeuro ID of the subject.'}\n with open(outdir.joinpath(filename + '.json'), \"w\") as f:\n json.dump(json_dict, f, indent=4)", "def read_delsys_csv(filename: str) -> Dict[str, Dict[str, TimeSeries]]:\n # Check the number of rows to skip\n n_rows = 0\n with open(filename, 'r') as fid:\n while True:\n s = fid.readline()\n if s.startswith('X[s]'):\n break\n else:\n n_rows += 1\n\n # Open the CSV\n df = pd.read_csv(filename, skiprows=n_rows)\n\n # Create a TimeSeries for each signal since they all have different time\n # vectors\n n_signals = int(len(df.columns) / 2)\n\n emg = {}\n acc = {}\n gyro = {}\n mag = {}\n\n for i_signal in range(n_signals):\n time = df.iloc[:, i_signal * 2].to_numpy()\n name = df.columns[i_signal * 2 + 1]\n data = df.iloc[:, i_signal * 2 + 1].to_numpy()\n\n if ': Acc' in name:\n short_name = name\n ts = TimeSeries(time=time, data={short_name: data})\n acc[short_name] = ts\n elif ': Mag' in name:\n short_name = name\n ts = TimeSeries(time=time, data={short_name: data})\n mag[short_name] = ts\n elif ': Gyro' in name:\n short_name = name\n ts = TimeSeries(time=time, data={short_name: data})\n gyro[short_name] = ts\n elif ': EMG' in name:\n short_name = name.split(':')[0]\n ts = TimeSeries(time=time, data={short_name: data})\n emg[short_name] = ts\n\n return {'emg': emg, 'acc': acc, 'gyro': gyro, 'mag': mag}", "def convert_id(df, id_in, id_out, chunklength, timer, load_loc, save_loc=None, load_pmid=True,\n mail_ad='placeholder', tool='id_converter'):\n\n import time\n import requests\n import pandas as pd\n import numpy as np\n\n pubmedURL = 'https://www.ncbi.nlm.nih.gov/pmc/utils/idconv/v1.0/?tool=' + tool + '&email=' + mail_ad + '&ids='\n\n # Format changes\n try:\n df[id_in] = df[id_in].fillna(value=np.nan) # If there are any None objects\n except:\n pass\n\n try:\n df[id_out] = df[id_out].fillna(value=np.nan)\n df[id_out] = df[id_out].fillna(0.0).astype(int).astype(str)\n except:\n pass\n\n # If there is a location for a csv dataframe with doi -> pmid mappings\n if load_pmid:\n df_mappings = pd.read_csv(load_loc)\n df_final = pd.merge(df, df_mappings, on=id_in, how='inner') # or \"left\"?\n print(\"Number of final dataframe entries: \" + str(len(df_final)))\n\n else:\n print(\"Could not find .csv with doi -> pmid mappings, retrieving mappings from Pubmed\")\n # need to remove NaNs because the pubmed API does not accept these requests\n df_nonna = df[~df[str(id_in)].isnull()].reset_index()\n dois_to_convert = df_nonna[str(id_in)].values\n # Split into evenly sized chunks\n doi_chunked = [dois_to_convert[i:i+chunklength] for i in range(0, len(dois_to_convert), chunklength)]\n\n original_list = []\n response_list = []\n\n for i in range(0, len(doi_chunked)):\n cur_request = pubmedURL + str(\",\".join(doi_chunked[i])) + '&format=json'\n response = requests.get(cur_request)\n json_data = response.json()\n\n for j in range(0, len(doi_chunked[i])):\n try:\n original_list.append(json_data['records'][j][str(id_in)])\n except:\n original_list.append(np.nan)\n print(\"Problem in input ID\")\n try:\n response_list.append(json_data['records'][j][str(id_out)])\n except:\n response_list.append(np.nan)\n try:\n print(\"Problem in conversion - input ID was \" + str(json_data['records'][j][str(id_in)]))\n except:\n print(\"Problem in conversion - no input ID?\")\n\n print('Waiting ' + str(timer) + ' seconds, about ' + str((len(doi_chunked)-i) * timer) + ' seconds left.')\n time.sleep(timer)\n\n # Make dataframe\n df_responselist = pd.DataFrame({str(id_in) : original_list, str(id_out) : response_list})\n\n # Save this dataframe for reproducibility\n if save_loc:\n df_responselist.to_csv(save_loc, index=False)\n\n # Recombine with original input df\n df_final = pd.merge(df, df_responselist, on=str(id_in), how='outer')\n\n return df_final", "def add_observations(instrument_id, obstable):\n\n if Session.registry.has():\n session = Session()\n else:\n session = Session(bind=DBSession.session_factory.kw[\"bind\"])\n\n # if the fields do not yet exist, we need to add them\n if ('RA' in obstable) and ('Dec' in obstable) and not ('field_id' in obstable):\n instrument = session.query(Instrument).get(instrument_id)\n regions = Regions.parse(instrument.region, format='ds9')\n field_data = obstable[['RA', 'Dec']]\n field_ids = add_tiles(\n instrument.id, instrument.name, regions, field_data, session=session\n )\n obstable['field_id'] = field_ids\n\n try:\n observations = []\n for index, row in obstable.iterrows():\n field_id = int(row[\"field_id\"])\n field = (\n session.query(InstrumentField)\n .filter(\n InstrumentField.instrument_id == instrument_id,\n InstrumentField.field_id == field_id,\n )\n .first()\n )\n if field is None:\n return log(\n f\"Unable to add observations for instrument {instrument_id}: Missing field {field_id}\"\n )\n\n observation = (\n session.query(ExecutedObservation)\n .filter_by(\n instrument_id=instrument_id, observation_id=row[\"observation_id\"]\n )\n .first()\n )\n if observation is not None:\n log(\n f\"Observation {row['observation_id']} for instrument {instrument_id} already exists... continuing.\"\n )\n continue\n\n # enable multiple obstime formats\n try:\n # can catch iso and isot this way\n obstime = Time(row[\"obstime\"])\n except ValueError:\n # otherwise catch jd as the numerical example\n obstime = Time(row[\"obstime\"], format='jd')\n\n observations.append(\n ExecutedObservation(\n instrument_id=instrument_id,\n observation_id=row[\"observation_id\"],\n instrument_field_id=field.id,\n obstime=obstime.datetime,\n seeing=row.get(\"seeing\", None),\n limmag=row[\"limmag\"],\n exposure_time=row[\"exposure_time\"],\n filt=row[\"filter\"],\n processed_fraction=row[\"processed_fraction\"],\n target_name=row[\"target_name\"],\n )\n )\n session.add_all(observations)\n session.commit()\n\n flow = Flow()\n flow.push('*', \"skyportal/REFRESH_OBSERVATIONS\")\n\n return log(f\"Successfully added observations for instrument {instrument_id}\")\n except Exception as e:\n return log(f\"Unable to add observations for instrument {instrument_id}: {e}\")\n finally:\n session.close()\n Session.remove()", "def _get_rekey_ddi_data(ddi_data):\n for enum, item in enumerate(ddi_data):\n ddi_data[enum] = dict((d['network'],\n dict(d, index=index))\n for (index, d) in enumerate(item))\n return ddi_data", "def parse_pathways(pathway_dataframe):\n return {\n kegg_id: name\n for line, (kegg_id, name) in pathway_dataframe.iterrows()\n }", "def generate_for_day(df: pd.DataFrame, dt=None, tickers=None, rounds=None) -> ListOfDicts:\n\n if dt:\n logging.info(f\"Training {rounds} rounds with {len(df)} stocks in dataset for {dt}...\")\n else:\n logging.info(f\"Training {rounds} rounds with {len(df)} stocks in dataset...\")\n\n if len(df) < MIN_TRAINING_SIZE:\n logging.warning(f\"Skipping because the number of stocks < {MIN_TRAINING_SIZE}...\")\n return []\n\n dt_str = dt and dt.strftime(\"%Y-%m-%d\")\n df = df[(df.date == dt_str)]\n\n calculate_overall_r2(df, rounds)\n\n raw_estimate_by_ticker = {}\n\n if tickers:\n unavailable_tickers = set(tickers) - set(list(df['ticker']))\n for ticker in unavailable_tickers:\n logging.warning(f\"Ticker '{ticker}' not found in dataset. Continuing...\")\n tickers.remove(ticker)\n else:\n tickers = set(list(df['ticker']))\n logging.info(f\"Building models for {len(tickers)} stocks.\")\n\n def _gfds(ticker):\n return ticker, generate_ffe_for_ticker(ticker, df=df, rounds=rounds)\n\n for ticker, estimate in fastmap.fastmap(_gfds, list(tickers)):\n market_cap = float(df[(df.ticker == ticker)]['marketCap'])\n logging.info(\"FFER for %r: %.4f\", ticker, market_cap / estimate)\n raw_estimate_by_ticker[ticker] = estimate\n\n estimates = []\n for ticker, pred in raw_estimate_by_ticker.items():\n df_row = df[(df.ticker == ticker)].to_dict(orient='records')[0]\n row = {}\n if dt_str:\n row[\"date\"] = dt_str\n row[\"ticker\"] = ticker\n row[\"num_shares\"] = df_row[\"shares\"]\n row[\"actual_market_cap\"] = df_row['marketCap']\n row[\"estimate_market_cap\"] = pred\n row[\"actual_price\"] = df_row[\"price\"]\n row[\"estimate_price\"] = row[\"estimate_market_cap\"] / row[\"num_shares\"]\n row[\"ffer\"] = row[\"actual_price\"] / row[\"estimate_price\"]\n for col in X_DIMENSIONS:\n row[col] = df_row[col]\n estimates.append(row)\n\n return sorted(estimates, key=lambda p: p[\"ffer\"])", "def convert_data(df):\n print(\"Converting history...\")\n return [ dict(row) for i, row in df.iterrows() ]", "def fetch_game_info(df: pd.DataFrame) -> pd.DataFrame:\n data_dict = defaultdict(list)\n len = df.shape[0]\n\n with alive_bar(len) as bar:\n for _, row in df.iterrows():\n gid = row['id']\n\n html = fetch_url(TWITCH_TRCK_URL + 'games/' + gid, hint='game')\n divs = html.find_all('div', {'class': 'g-x-s-block'})\n for div in divs:\n # Give a initial value as None\n # so that the program won't raise exception for length\n val, label = (None, None)\n val = div.find('div', {'class': 'g-x-s-value'}).text.strip()\n label = div.find('div', {'class': 'g-x-s-label'}).text.strip()\n if ('@' in label):\n (label, date) = label.split('@')\n label = label.strip()\n val += date\n data_dict[label].append(val)\n\n bar()\n\n df = df.assign(**data_dict)\n return df", "def get_player_dict(self) -> dict:\n return self.df.to_dict('index')", "def to_dict_records(df):\r\n return df.to_dict('records')", "def treatments_dict():\n treats = 2\n data = pd.DataFrame(\n data={\"id\": np.arange(100), \"block\": [0] * 40 + [1] * 30 + [2] * 30}\n )\n idx_col = \"id\"\n size = 90\n\n treatments = stochatreat(\n data=data,\n block_cols=[\"block\"],\n treats=treats,\n idx_col=idx_col,\n size=size,\n random_state=42,\n )\n\n treatments_dict = {\n \"data\": data,\n \"idx_col\": idx_col,\n \"size\": size,\n \"treatments\": treatments,\n }\n\n return treatments_dict", "def to_dcase_format(sed_labels, doa_labels):\n batch_size, T, num_tracks, num_classes= sed_labels.shape\n\n sed_labels = sed_labels.reshape(batch_size*T, num_tracks, num_classes)\n doa_labels = doa_labels.reshape(batch_size*T, num_tracks, 2)\n \n output_dict = {}\n for n_idx in range(batch_size*T):\n for n_track in range(num_tracks):\n class_index = list(np.where(sed_labels[n_idx, n_track, :])[0])\n assert len(class_index) <= 1, 'class_index should be smaller or equal to 1!!\\n'\n if class_index:\n event_doa = [class_index[0], int(np.around(doa_labels[n_idx, n_track, 0] * 180 / np.pi)), \\\n int(np.around(doa_labels[n_idx, n_track, 1] * 180 / np.pi))] # NOTE: this is in degree\n if n_idx not in output_dict:\n output_dict[n_idx] = []\n output_dict[n_idx].append(event_doa)\n return output_dict", "def events(self, game_id: int) -> DataFrame[Any]:", "def _ensemble_map(df, nxg, columns=[]):\n assert isinstance(df, pd.DataFrame)\n assert isinstance(nxg, nx.DiGraph)\n ret = {}\n\n module_group_df = df.groupby([\"module\"])\n module_name_group_df = df.groupby([\"module\", \"name\"])\n\n module_callsite_map = module_group_df[\"name\"].unique().to_dict()\n\n module_time_inc_map = module_group_df[\"time (inc)\"].max().to_dict()\n module_time_exc_map = module_group_df[\"time\"].max().to_dict()\n\n name_time_inc_map = module_name_group_df[\"time (inc)\"].max().to_dict()\n name_time_exc_map = module_name_group_df[\"time\"].max().to_dict()\n\n # loop through the nodes\n for node in nxg.nodes(data=True):\n node_name = node[0]\n node_dict = node[1][\"attr_dict\"]\n\n if node_dict[\"type\"] == \"component-node\":\n module = node_name.split(\"=\")[0]\n callsite = node_name.split(\"=\")[1]\n actual_time = SankeyLayout.callsite_time(\n group_df=module_name_group_df, module=module, callsite=callsite\n )\n time_inc = name_time_inc_map[(module, callsite)]\n time_exc = name_time_exc_map[(module, callsite)]\n\n elif node_dict[\"type\"] == \"super-node\":\n module = node_name\n callsite = module_callsite_map[module].tolist()\n actual_time = SankeyLayout.module_time(\n group_df=module_name_group_df,\n module_callsite_map=module_callsite_map,\n module=module,\n )\n\n time_inc = module_time_inc_map[module]\n time_exc = module_time_exc_map[module]\n\n for column in columns:\n if column not in ret:\n ret[column] = {}\n\n if column == \"time (inc)\":\n ret[column][node_name] = time_inc\n\n elif column == \"time\":\n ret[column][node_name] = time_exc\n\n elif column == \"actual_time\":\n ret[column][node_name] = actual_time\n\n elif column == \"module\":\n ret[column][node_name] = module\n\n elif column == \"name\":\n ret[column][node_name] = callsite\n\n elif column == \"type\":\n ret[column][node_name] = node_dict[\"type\"]\n\n return ret", "def fetch_propagation_data(observer_stats):\n columns = [\n Observer.TABLE.c.start_time,\n Observer.TABLE.c.duration,\n Observer.TABLE.c.type,\n Observer.TABLE.c.status,\n Observer.TABLE.c.nameserver,\n ]\n query = select(columns).where(\n and_(Observer.TABLE.c.start_time >= observer_stats.start,\n Observer.TABLE.c.start_time <= observer_stats.end)\n )\n result = get_engine().execute(query)\n\n data = {\n 'by_type': {},\n 'by_nameserver': {},\n }\n for row in result:\n start_time, duration, type, status, nameserver = row\n if type not in data['by_type']:\n data['by_type'][type] = {\n 'error': [],\n 'success': [],\n }\n if nameserver not in data['by_nameserver']:\n data['by_nameserver'][nameserver] = {\n 'error': [],\n 'success': [],\n }\n datapoint = (start_time, duration)\n if status == Observer.STATUSES.COMPLETE:\n data['by_type'][type]['success'].append(datapoint)\n data['by_nameserver'][nameserver]['success'].append(datapoint)\n else:\n data['by_type'][type]['error'].append(datapoint)\n data['by_nameserver'][nameserver]['error'].append(datapoint)\n return data", "def convert_to_json(dataframe):\n dataframe = dataframe.set_index('YYYYMMDD').to_json('schiphol_windstoten.json', orient = 'index')", "def gen_dict(self):\n stimuli_dict = dict()\n for i, stim in enumerate(STIMULI):\n stimuli_dict[stim.name] = dict(stimulus_path=stim.value)\n rel_df = self.df.iloc[:, i * 2 : i * 2 + 2]\n stimuli_dict[stim.name][\"responses\"] = rel_df\n return stimuli_dict", "def to_dict(df):\n\t# Extract the names\n\tnames = list(df.columns.values)\n\t# Create sequence\n\tdf_list = []\n\t#Iterate over rows of data frame\n\tfor index, row in df.iterrows():\n\t\t# Create temporary object\n\t\ttemp_dict = {}\n\t\t#Iterate over key names and add values\n\t\tfor name in names:\n\t\t\ttemp_dict[name] = row[name]\n\t\t# Append object to dictionary\n\t\tdf_list.append(temp_dict.copy())\n\t\n\treturn df_list", "def initialize_connected_data(frame_data):\n connected_data = {}\n for i in range(0, len(frame_data)):\n this_spot_data = add_time_nuc(frame_data[i], 0, nucmask)\n connected_data[i+1] = np.array([this_spot_data])\n return connected_data", "def convert_to_dict(data_frame: pd.DataFrame) -> List[Dict[str, Any]]:\n type_conversion = {\"date\": str} if \"date\" in data_frame.columns else {}\n return data_frame.replace({np.nan: None}).astype(type_conversion).to_dict(\"records\")", "def so_attributes(self):\n try:\n self.channels\n except AttributeError:\n # create if doesn't exist\n self.channels = [x[0] for x in self.data.columns]\n \n dfs = ['sofiltEEG', 'spsofiltEEG']\n [setattr(self, df, pd.DataFrame(index=self.data.index)) for df in dfs]\n self.so_events = {}\n self.so_rejects = {}", "def data_parser(df):\n\n chunks = []\n for row in df.itertuples():\n piece = {}\n piece['datetime'] = row[1]\n piece[row[3]] = row[4]\n chunks.append(piece)\n\n # Join dicts on shared 'datetime' keys.\n combine = defaultdict(dict)\n for elem in chunks:\n combine[elem['datetime']].update(elem)\n\n ordered = sorted(combine.values(), key=itemgetter(\"datetime\"))\n\n mapped_generation = []\n for item in ordered:\n mapped_types = [(mapping.get(k, k), v) for k, v in item.items()]\n\n # Need to avoid multiple 'unknown' keys overwriting.\n complete_production = defaultdict(lambda: 0.0)\n for key, val in mapped_types:\n try:\n complete_production[key] += val\n except TypeError:\n # Datetime is a string at this point!\n complete_production[key] = val\n\n dt = complete_production.pop('datetime')\n final = (dt, dict(complete_production))\n mapped_generation.append(final)\n\n return mapped_generation", "def station_id_lookup(df):\n station_dict = defaultdict()\n values = df.values\n for row in values:\n stationid = row[0]\n data = row[1:]\n station_dict[stationid] = data\n return station_dict", "def df_to_dict(df):\n return df.to_dict('index')", "def add_extra_syn_to_dict(df, pos):\n\tsyn_dict = get_syn_dict(pos)\n\tfor index, row in df.iterrows():\n\t\tsource = row['source']\n\t\ttarget = row['target']\n\t\tif row['pos'] == pos and target not in syn_dict[source]:\n\t\t\tsyn_dict[source].append(target)\n\treturn syn_dict", "def _dataframe_preprocess(self):\n # 1. add baisc feature like date, time in day, ....\n if self.data_type != 'porto':\n self.df['TIMESTAMP'] = self.df.apply(lambda df: df['TIMESTAMPS'][0], axis=1)\n self.df['TIME'] = pd.to_datetime(self.df['TIMESTAMP'], unit='s', utc=True)\n \n self.df.TIME = self.df.TIME.dt.tz_convert(self.timezone)\n # 2. group df for specific driver analysis\n self.grouped_df = self.df.groupby('LABEL')\n if self.count_od_info:\n if 'SD' not in self.df.columns:\n self._add_OD_info()\n self.grouped_od = self.df.groupby('SD')" ]
[ "0.5042048", "0.4814868", "0.47347727", "0.4657895", "0.46245697", "0.4503713", "0.4491382", "0.4467344", "0.44467682", "0.44412938", "0.44312024", "0.44292995", "0.44158575", "0.4410534", "0.4407224", "0.43975756", "0.43851158", "0.43694475", "0.43649432", "0.43511978", "0.43446887", "0.4340217", "0.43241158", "0.42884073", "0.42852736", "0.42700034", "0.42646876", "0.42521992", "0.42505872", "0.42259207" ]
0.65537184
0
Resets the error model parameter names and prepends the output name if more than one output exists.
def _set_error_model_parameter_names(self): # Reset error model parameter names to defaults for error_model in self._error_models: error_model.set_parameter_names(None) # Rename error model parameters, if more than one output n_outputs = self._mechanistic_model.n_outputs() if n_outputs > 1: # Get output names outputs = self._mechanistic_model.outputs() for output_id, error_model in enumerate(self._error_models): # Get original parameter names names = error_model.get_parameter_names() # Prepend output name output = outputs[output_id] names = [output + ' ' + name for name in names] # Set new parameter names error_model.set_parameter_names(names)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def fixupProcess(self):\n # Make sure that for each output module the following parameters exist\n # in the PSet returned from the framework:\n # fileName\n # logicalFileName\n # dataset.dataTier\n # dataset.filterName\n if hasattr(self.process, \"outputModules\"):\n outputModuleNames = self.process.outputModules.keys()\n else:\n outputModuleNames = self.process.outputModules_()\n for outMod in outputModuleNames:\n outModRef = getattr(self.process, outMod)\n if not hasattr(outModRef, \"dataset\"):\n outModRef.dataset = cms.untracked.PSet()\n if not hasattr(outModRef.dataset, \"dataTier\"):\n outModRef.dataset.dataTier = cms.untracked.string(\"\")\n if not hasattr(outModRef.dataset, \"filterName\"):\n outModRef.dataset.filterName = cms.untracked.string(\"\")\n if not hasattr(outModRef, \"fileName\"):\n outModRef.fileName = cms.untracked.string(\"\")\n if not hasattr(outModRef, \"logicalFileName\"):\n outModRef.logicalFileName = cms.untracked.string(\"\")\n return", "def output_name(self, auxiliary_output=None):\n\n raise Exception(\"Child classes must override output_name()\")", "def setName(self, *args):\n return _libsbml.Output_setName(self, *args)", "def reset_error(self):\n\t\t\n\t\tself.error = None", "def __set_outputs__(self):\n self.__set_in_out_var__(None, 1)", "def prepare_output_name(output_name: str, output: Output, prefix: str) -> str:\n if prefix:\n output_name = add_output_prefix(output_name, output=output)\n return output_name", "def _fix_outputs(self, op, outputs):\n if op == 'Dropout':\n assert len(outputs) == 2, \"ONNX have two outputs for dropout layer.\"\n outputs = outputs[:-1]\n return outputs", "def _get_output(self, output, error):\n return IDLVMinimalModels(output, error)", "def cleanup(self):\n self.__log('Resetting value for output_filename, making way for another go.')\n self.output_filename = None", "def output_names(self):\n msg = \"output_names() is not implemented by op {}\"\n raise NotImplementedError(msg.format(self.op_type))", "def reset_error_state(self):\n self.error_state = Error.none\n self.error_info = ''", "def make_invalid_output(self):\r\n self.task_output = 'HI MY NAME IS INVALID JSON'\r\n # This should be given the value of 'unknown' if the task output\r\n # can't be properly parsed\r\n self.duration_sec = 'unknown'", "def rename(self):\n\n # Remove any zero-padding from single-digit parameter names\n # This reverses any change applied by one of the CUDA writers\n for i in range(self.parser.comp-1, len(self.parser.parsedModel.parameterId)):\n old_name = self.parser.parsedModel.parameterId[i]\n num = old_name[len('parameter'):]\n if len(num) > 1 and num[0] == '0':\n new_name = 'parameter' + str(num[1:])\n self.parser.parsedModel.parameterId[i] = new_name\n self.parser.rename_everywhere(old_name, new_name)\n\n # Remove any zero-padding from single-digit species names\n # This reverses any change applied by one of the CUDA writers\n for i in range(len(self.parser.parsedModel.speciesId)):\n old_name = self.parser.parsedModel.speciesId[i]\n num = old_name[len('species'):]\n if len(num) > 1 and num[0] == '0':\n new_name = 'species' + str(num[1:])\n self.parser.parsedModel.speciesId[i] = new_name\n self.parser.rename_everywhere(old_name, new_name)", "def fixupProcess(self):\n # Make sure that for each output module the following parameters exist\n # in the PSet returned from the framework:\n # fileName\n # logicalFileName\n # dataset.dataTier\n # dataset.filterName\n if hasattr(self.process, \"outputModules\"):\n outputModuleNames = list(self.process.outputModules) \n elif hasattr(self.process, \"outputModules_\"):\n outputModuleNames = self.process.outputModules_()\n elif hasattr(self.process, \"_Process__outputmodules\"):\n outputModuleNames = list(self.process._Process__outputmodules)\n else:\n msg = \"Error loading output modules from process\"\n raise AttributeError(msg)\n\n for outMod in outputModuleNames:\n tweak = PSetTweak()\n self.logger.info(\"DEBUG output module = %s\", outMod)\n tweak.addParameter(\"process.options\", \"customTypeCms.untracked.PSet()\")\n tweak.addParameter(\"process.%s.dataset\" % outMod, \"customTypeCms.untracked.PSet(dataTier=cms.untracked.string(''), filterName=cms.untracked.string(''))\")\n self.applyPsetTweak(tweak, skipIfSet=True, cleanupTweak=True)\n #tweak.addParameter(\"process.%s.dataset.dataTier\" % outMod, \"customTypeCms.untracked.string('')\")\n #tweak.addParameter(\"process.%s.dataset.filterName\" % outMod, \"customTypeCms.untracked.string('')\")\n tweak.addParameter(\"process.%s.fileName\" % outMod, \"customTypeCms.untracked.string('')\")\n tweak.addParameter(\"process.%s.logicalFileName\" % outMod, \"customTypeCms.untracked.string('')\")\n self.applyPsetTweak(tweak, skipIfSet=True)\n\n return", "def adjust_model_params(self, args):\n if self.model == \"linear\":\n self.with_sent = False\n if args.with_sent:\n sys.stderr.write(\"Setting with_sent param to False \")\n sys.stderr.write(\"for linear model (by definition).\\n\")\n elif self.model == \"joint\":\n self.hidden_sent = True\n self.sent_links = True\n if not args.hidden_sent or not args.sent_links:\n sys.stderr.write(\"Setting hidden_sent and sent_links params \")\n sys.stderr.write(\"to True for joint model (by definition.)\\n\")\n elif self.model == \"pipeline_NE\":\n self.with_sent = False\n if args.with_sent:\n sys.stderr.write(\"Setting with_sent param to False for \")\n sys.stderr.write(\"first stage of pipeline model (by definition.)\\n\")\n # If we have an NE predictions file we're sticking in,\n # we're on the second stage of the pipeline\n elif self.model == \"pipeline_sent\":\n self.hidden_sent = True\n self.NE_links = False\n if args.NE_links:\n sys.stderr.write(\"Setting NE_links param to False for \")\n sys.stderr.write(\"second stage of pipeline model (by definition.)\\n\")\n if not self.pipeline_NEs:\n sys.stderr.write(\"Need output predictions from NE stage of the pipeline. \\n\") \n sys.stderr.write(\"Use option --pipeline-NE-in=file and --pipeline-NE-format=erma for ERMA-formatted predictions.\\n\")\n sys.stderr.write(\"And option --pipeline-NE-in=file and --pipeline-NE-format=conll for CoNLL-formatted predictions.\\n\")\n sys.exit()\n self.note = args.note\n self.clean_unique_id = self.clean(self.unique_id)\n if self.clean_unique_id != self.unique_id:\n sys.stderr.write(\"Warning: \" + self.unique_id + \" contains illegal chars.\\n\")\n sys.stderr.write(\"Will print this out as \" + self.clean_unique_id + \".\\n\")", "def _transform_outputs(self) -> None:\n self.outputs = None if self.outputs == {} else self.outputs", "def set_parameter(self, output):\n self.model.set_parameter(output);", "def error(input_, output):\n global number_of_neurons_by_layer\n if len(output) != number_of_neurons_by_layer[-1]:\n raise IndexError(\n f\"\\033[91mDesired output length is incorrect. It must be {number_of_neurons_by_layer[-1]}.\\033[m\")\n output = np.array(output).reshape(len(output), 1)\n flow(input_)\n layers[-1][\"error\"] = output - layers[-1][\"v\"]", "def SetOutputFilename(self, filename, output_name=None, output_type=None):\n\n if self._outputs is not None:\n\n for o in self._outputs:\n\n if not output_type is None:\n\n if o.GetType() == output_type:\n\n if output_name is None:\n\n o.SetFilename(filename)\n\n elif o.GetName() == output_name:\n\n o.SetFilename(filename)\n \n elif not output_name is None:\n\n if o.GetName() == output_name:\n \n o.SetFilename(filename)\n \n else:\n\n o.SetFilename(filename)\n else:\n\n print \"No outputs have been loaded\"", "def error2(input_, output):\n error(input_, output)\n layers[-1][\"error2\"] = layers[-1][\"error\"].T @ layers[-1][\"error\"]", "def _reconfigure_outputs(self):\n self._new_variables = []\n self.used_variables = []\n if not self.reconfigured: # safety to call it once\n # Generate new vars\n for p in self.preprocess_x:\n for var in p.new_vars:\n self.variables.append(var)\n self._new_variables.append(var)\n self.used_variables = self.variables.copy()\n for p in self.preprocess_x:\n # Eliminate vars\n for var in p.eliminated_vars:\n id = self.used_variables.index(var)\n del(self.used_variables[id])\n self.reconfigured = True", "def reset_parameters(self):\n self.rnn.reset_parameters()\n self.action_lookup.reset_parameters()\n\n # self.state_dict_lookup.reset_parameters()\n self.own_c_lookup.reset.parameters()\n self.own_s_lookup.reset_parameters()\n\n self.th_1_lookup.reset_parameters()\n self.th_2_lookup.reset_parameters()\n self.th_3_lookup.reset_parameters()\n self.f_1_lookup.reset.parameters()\n self.f_2_lookup.reset_parameters()\n self.f_3_lookup.reset_parameters()\n self.f_4_lookup.reset_parameters()\n\n self.bu_msg_lookup.reset_parameters()\n\n self.i_t_lookup.reset_parameters()\n self.lives_lookup.reset_parameters()\n\n self.prev_action_lookup.reset_parameters()\n # self.message.apply(weight_reset)\n self.output.apply(weight_reset)\n for p in self.rnn.parameters():\n p.data.uniform_(*self.init_param_range)", "def format_model_output(self, output, batch_size=1):\r\n return output", "def remove_expected_output(self, name):\n if name in self._expected_outputs:\n del self._expected_outputs[name]", "def processError(sMsg, sOutput):\n if sOutput == \"\":\n errorMsg(sMsg)\n else:\n errorMsg(sMsg + \":\\n \" + ' '.join(sOutput.splitlines(True)))", "def after_init(self):\n if self.options.format.appended:\n self.error_format = self.options.format.appended[0]", "def save_default_error(name):\n name_output = colored(name, attrs=['bold'])\n output_1 = colored(' - Error: Version name ', 'red')\n output_2 = colored(' is not allowed\\n', 'red')\n return output_1 + name_output + output_2", "def _populate_output(self):\n pass", "def _update_parameter_set_names(self):\n self._create_parameter_set_names()\n new_set_names = set(self._parameter_set_names.values()) - set(self.parameter_study.coords[_set_coordinate_key].values)\n null_set_names = self.parameter_study.coords[_set_coordinate_key].isnull()\n if any(null_set_names):\n self.parameter_study.coords[_set_coordinate_key][null_set_names] = list(new_set_names)\n self._parameter_set_names = self.parameter_study[_set_coordinate_key].squeeze().to_series().to_dict()", "def _get_inference_output_name(self):\n inference_output_name = 'output'\n if len(self['inference_output'].get_shape().as_list()) > 0:\n inference_output_name = 'inference_output'\n\n return inference_output_name" ]
[ "0.57665694", "0.55550444", "0.5478356", "0.5472496", "0.54560643", "0.54148453", "0.5400223", "0.5367741", "0.53485596", "0.52957", "0.5292765", "0.528896", "0.5284119", "0.52635086", "0.52328205", "0.5230758", "0.5223709", "0.52217895", "0.52121764", "0.51781875", "0.51714176", "0.5167468", "0.51551396", "0.5153123", "0.5132724", "0.5111971", "0.5101863", "0.50767875", "0.5058719", "0.50431323" ]
0.8067073
0
Returns the names of the covariates.
def get_covariate_names(self): if self._population_model is None: return [] return self._population_model.get_covariate_names()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def covariates(self) -> List[str]:\n return self._obj._names[\"covariates\"]", "def covariates(self):\n return None", "def _extract_covariates(self, covariate_names):\n # Format covariates to array of shape (n, c)\n c = len(covariate_names)\n n = len(self._ids)\n covariates = np.empty(shape=(n, c))\n for idc, name in enumerate(covariate_names):\n mask = self._data[self._obs_key] == self._covariate_dict[name]\n temp = self._data[mask]\n for idn, _id in enumerate(self._ids):\n mask = temp[self._id_key] == _id\n covariates[idn, idc] = \\\n temp.loc[mask, self._value_key].dropna().values\n\n return covariates", "def get_cora_label_names():\n # type: () -> List[str]\n return _label_names", "def get_covariate_pairs(self):\n if self.covariate_field not in self.matrix.obs.columns:\n raise ValueError(\"Covariate value not available in dataset\")\n from itertools import product\n covariate = set(self.matrix.obs[self.covariate_field])\n return product(covariate, covariate)", "def tcv_names(self):\n return self._tcvs", "def name_corr(self):\n raise NotImplementedError\n ## Build matrix of names\n corr_mat = []\n for ind in range(self.n_in):\n corr_mat.append(\n list(map(lambda s: s + \",\" + self.domain.var[ind], self.domain.var))\n )\n\n ## Access matrix of names\n corr_names = dict()\n corr_ind = triu_indices(self.n_in, 1)\n for knd in range(len(corr_ind[0])):\n ind = corr_ind[0][knd]\n jnd = corr_ind[1][knd]\n corr_names[\"corr_\" + str(knd)] = corr_mat[ind][jnd]\n\n return corr_names", "def get_components(self, norm=False):\n return self._var_names", "def covariate_rename(self):\n covariate_df = self.dismod_file.covariate\n id_name = dict(covariate_df[[\"covariate_id\", \"covariate_name\"]].to_records(index=False))\n return {name: f\"x_{idx}\" for (idx, name) in id_name.items()}", "def get_names(self):\n\n # log.debug(str(inspect.stack()[1][3]) + \" --> OC.get_names()\")\n return [x.options['name'] for x in self.get_list()]", "def name(self):\n return [o.name for o in self.obs]", "def others(self) -> List[str]:\n exclude = self._obj._names[\"covariates\"] + DATA_COLS\n return [col for col in self._obj.columns if col not in exclude]", "def fcv_names(self):\n return self._fcvs", "def cvars(occs):\n names = []\n canonicals = []\n for occ in occs:\n if occ.name in names:\n continue\n canonicals.append(occ)\n return canonicals", "def get_covariates(degree):\n\n base_variables = [\n \"smallm\",\n \"largem\",\n \"treatsmall\",\n \"treatlarge\",\n \"ssmall\",\n \"slarge\",\n \"streatsmall\",\n \"streatlarge\",\n ]\n if degree == 0:\n base = base_variables[0:4]\n return base\n if degree == 1:\n return base_variables\n else:\n for i in range(2, degree + 1):\n base_variables.append(f\"ssmall{i}\")\n base_variables.append(f\"slarge{i}\")\n base_variables.append(f\"streatsmall{i}\")\n base_variables.append(f\"streatlarge{i}\")\n return base_variables", "def tcv_name_list(self):\n return list(self._link_reg.tcv_names)", "def get_names(self):\n return [doc['name'] for doc in self.vocab]", "def get_variable_names(self):\n return [var[1] for var in self.variables]", "def getOfcVarNames( self ):\n\n if self.ofcVarNames:\n return self.ofcVarNames.keys()\n \n n = self.adb.get( \"nOfcVars\" )\n for indx in xrange( n ):\n name = self.adb.get( \"ofcVarName\",\n indx ) \n self.ofcVarNames[name] = indx\n\n return self.ofcVarNames.keys()", "def names(self):\n\n allnames = []\n for term in self.terms:\n allnames += term.names()\n return allnames", "def names(self):\n\n allnames = []\n for term in self.terms:\n allnames += term.names()\n return allnames", "def donor_names(self):\n return list(self.donors)", "def names(self) -> list[str]:", "def parentNCBInames(self):\n return self.parentClade.ncbiNames", "def donor_names(self):\n return [donor.name for donor in self.donors]", "def obs_names(self):\n return self._obs_names", "def get_cov_matrix_states(self):\n cov = numpy.diag(numpy.zeros(self.get_num_variables()))\n i = 0\n for v in self.variables:\n cov[i,i] = v.get_covariance()\n i += 1\n return cov", "def termnames(self):\n\n names = []\n for term in self.terms:\n names += [term.termname]\n return names", "def termnames(self):\n\n names = []\n for term in self.terms:\n names += [term.termname]\n return names", "def get_feature_names(self):\n\t\treturn np.array(['nouns', 'adjectives', 'verbs', 'adverbs'])" ]
[ "0.9059461", "0.7653818", "0.66643596", "0.6556078", "0.64953846", "0.64784676", "0.632451", "0.6303127", "0.6175361", "0.6151976", "0.61394966", "0.6138521", "0.6114289", "0.5997235", "0.5952127", "0.59334815", "0.5901747", "0.58754677", "0.5871938", "0.5863617", "0.5863617", "0.58628196", "0.58572525", "0.5856175", "0.5855837", "0.58512384", "0.58441055", "0.5843093", "0.5843093", "0.58419675" ]
0.85792655
1
Returns the names of the model parameters, i.e. the combined names of the mechanistic model parameters and the error model parameters when no population model has been set, or the names of population model parameters when a population model has been set. Any parameters that have been fixed to a constant value will not be included.
def get_parameter_names(self, exclude_pop_model=False): if (self._population_model is None) or exclude_pop_model: names = self._mechanistic_model.parameters() for error_model in self._error_models: names += error_model.get_parameter_names() return names return self._population_model.get_parameter_names()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_model_parameter_names():\n params = ['mu', 'rho']\n return params", "def parameter_names_from_model(model):\n variables = model.getVariables()\n itvar = variables.iterator()\n names = []\n for i in xrange(len(variables)):\n currentvar = itvar.Next()\n names.append(currentvar.GetName())\n return names", "def get_model_params(self):\n w1 = self.w1\n b1 = self.b1\n w2 = self.w2\n b2 = self.b2\n w3 = self.w3\n b3 = self.b3\n w4 = self.w4\n b4 = self.b4\n w5 = self.w5\n b5 = self.b5\n w6 = self.w6\n b6 = self.b6\n\n return w1, b1, w2, b2, w3, b3, w4, b4, w5, b5, w6, b6", "def get_hyperparameter_names():\n params = ['mu', 'nu', 'r', 's']\n return params", "def print_param_names(model):\n for (param_name, param) in model.get_parameters().items():\n print(param_name, param.shape)", "def model_parameters(self) -> Iterator[Tuple[str, torch.Tensor]]:\n return self._model.named_parameters()", "def get_parameter_names(self):\n parNames = []\n # for par in self.variables: # TODO: LIKELY A BUG! DOES THE SAME AS get_variable_names()\n for par in self.parameters: # TRYING TO SOLVE THE ISSUE\n # EstimationVariable\n parNames.append(par.name)\n return parNames", "def _get_fitted_param_names(self):\n return self._fitted_param_names", "def get_model_parameters(self, *model_parameters):\r\n\r\n parameters = {k: v for k, v in zip(self.model_parameter_names, model_parameters)}\r\n\r\n return parameters", "def get_prunable_parameters(\r\n model: Module,\r\n only_matrices: bool = True,\r\n # TODO: Replace exclude with a filter function per model.\r\n exclude: List[str] = [\"embed\", \"decoder.\", \"pooler.\", \"shared.\"],\r\n) -> List[Parameter]:\r\n # names = [name for name, _ in model.named_parameters()]\r\n # import pdb; pdb.set_trace()\r\n return [\r\n param\r\n for name, param in model.named_parameters()\r\n if (\r\n (not only_matrices or len(param.size()) == 2)\r\n and not any(substr in name for substr in exclude)\r\n )\r\n ]", "def get_model_parameters(model):\n if model.fit_intercept:\n params = (model.coef_, model.intercept_) # ????\n else:\n params = (model.coef_,)\n return params", "def parameters(self):\n res = dict()\n res[\"population_size\"] = self.population_size\n res[\"mutation_prob\"] = self.mutation_prob\n res[\"crossover\"] = self.crossover\n res[\"selection\"] = self.selection\n res[\"sigma\"] = self.sigma\n res[\"crossover_method\"] = self.crossover_method\n res[\"selection_method\"] = self.selection_method\n res[\"best_rate\"] = self.best_rate\n res[\"n_parents\"] = self.n_parents\n res[\"model_parameters\"] = self.model.total_parameters()\n res[\"IDCT_from\"] = self.IDCT_from\n res[\"elitism\"] = self.elitism\n return res", "def get_n_parameters(self, exclude_pop_model=False):\n if (self._population_model is None) or exclude_pop_model:\n n_parameters = self._mechanistic_model.n_parameters()\n for error_model in self._error_models:\n n_parameters += error_model.n_parameters()\n return n_parameters\n\n return self._population_model.n_parameters()", "def print_model_params(model):\n for param, value in zip(model.param_names, model.parameters):\n print(\"{:0.4f}\\t{}\".format(value, param))", "def potential_parameters(cls):\n return [\"k\", \"periodicity\", \"phase\", \"idivf\"]", "def potential_parameters(cls):\n return [\"k\", \"periodicity\", \"phase\", \"idivf\"]", "def param_unc_names(self) -> List[str]:\n return self._param_unc_names(self.model).decode(\"utf-8\").split(\",\")", "def get_model_params(self):\n\n results = self._model.fit()\n model_params = np.expand_dims(results.params.as_matrix(), 1)\n return model_params", "def get_likelihood_param_values(self):\n likelihood_param_values = {}\n for name in self.likelihood_params:\n likelihood_param_values[name] = getattr(self.model, name)\n return likelihood_param_values", "def get_mandatory_param_names(self):\n all_names = self.params.keys()\n return [name for name in all_names \n if not self.params[name].is_optional]", "def parameters(self):\n return self.model.parameters()", "def get_required_parameters(self) -> list:\n results = []\n if self.no_params or self.params_optional:\n return []\n else:\n for parameter, parameter_details in self.parameters.items():\n # Fixing issue #92\n # if parameter == \"effect\":\n # continue\n if not parameter_details.default_value:\n results.append(parameter_details.name)\n return results", "def param_names(\n self, *, include_tp: bool = False, include_gq: bool = False\n ) -> List[str]:\n return (\n self._param_names(self.model, int(include_tp), int(include_gq))\n .decode(\"utf-8\")\n .split(\",\")\n )", "def get_configuration_parameters_names(self):\n return (\n 'timestamp', 'model_name', 'weight_path', 'fit_history_path', 'learning_rate', 'load_weights',\n 'freeze_layers', 'margin', 'hard_sampling_batch_size', 'batch_size',\n 'number_of_validation_imgs', 'input_shape')", "def select_params( model, contains=[]):\n names = []\n for name, param in model.named_parameters():\n param.requires_grad = False\n if any(name.find(c) != -1 for c in contains):\n param.requires_grad = True\n names.append([name,param.numel()])\n\n total = sum(p.numel() for p in model.parameters()) \n p_str = \"\\nParameters: \\n\\nTotal: {} \\n\\nTrained: {} \\n\"\n print(p_str.format(total,sum([p for n,p in names])))\n for n,t in names: print(n,t)\n print(\"\\n\")", "def get_model_parameter_bounds():\n minf = float(\"-inf\")\n inf = float(\"inf\")\n params = dict(mu=(minf,inf), rho=(0.0 ,inf))\n return params", "def get_params(self):\n return {\n \"nspecies\": self.nspecies,\n \"lmax\": self.lmax,\n \"nmax\": self.nmax,\n \"rcut\": self.rcut,\n \"sigma\": self.sigma,\n \"trans_width\": self.trans_width\n }", "def get_model_params(self):\n return self._model_params", "def parameters_names(cls):\n return cls._Parameters._fields", "def get_layer_var_names(self):\n return(self.params)" ]
[ "0.8078527", "0.6911393", "0.6861655", "0.6757447", "0.6700816", "0.6638141", "0.6599225", "0.6582798", "0.65355724", "0.64979255", "0.6463585", "0.6457589", "0.6440606", "0.6431328", "0.6382589", "0.6382589", "0.63714576", "0.63475984", "0.6344106", "0.63392514", "0.6319101", "0.63015676", "0.6295641", "0.6291384", "0.62558126", "0.62386656", "0.62384623", "0.6234843", "0.621039", "0.61875534" ]
0.8200989
0
Sets the data of the modelling problem. The data contains information about the measurement time points, the measured values of the observables, the observable name, IDs to identify the corresponding individuals, and optionally information on the administered dose amount and duration.
def set_data( self, data, output_observable_dict=None, covariate_dict=None, id_key='ID', time_key='Time', obs_key='Observable', value_key='Value', dose_key='Dose', dose_duration_key='Duration'): # Check input format if not isinstance(data, pd.DataFrame): raise TypeError( 'Data has to be a pandas.DataFrame.') # If model does not support dose administration, set dose keys to None if not self._mechanistic_model.supports_dosing(): dose_key = None dose_duration_key = None keys = [id_key, time_key, obs_key, value_key] if dose_key is not None: keys += [dose_key] if dose_duration_key is not None: keys += [dose_duration_key] for key in keys: if key not in data.keys(): raise ValueError( 'Data does not have the key <' + str(key) + '>.') # Check output observable map outputs = self._mechanistic_model.outputs() observables = data[obs_key].dropna().unique() output_observable_dict = self._check_output_observable_dict( output_observable_dict, outputs, observables) # Check covariate name map covariate_names = self.get_covariate_names() covariate_dict = self._check_covariate_dict( covariate_dict, covariate_names, observables) self._id_key, self._time_key, self._obs_key, self._value_key = [ id_key, time_key, obs_key, value_key] self._data = data[keys] self._output_observable_dict = output_observable_dict self._covariate_dict = covariate_dict # Make sure data is formatted correctly self._clean_data(dose_key, dose_duration_key) self._ids = self._data[self._id_key].unique() # Extract dosing regimens self._dosing_regimens = None if dose_key is not None: self._dosing_regimens = self._extract_dosing_regimens( dose_key, dose_duration_key) # Set number of modelled individuals of population model if isinstance(self._population_model, chi.ReducedPopulationModel): # Unfix model parameters self._population_model = \ self._population_model.get_population_model() if self._population_model is not None: self._population_model.set_n_ids(len(self._ids)) # Check that covariates can be reshaped into (n, c) self._check_covariate_values(covariate_names)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def set_data(self, data):\n self.closeContext()\n self.clear()\n self.clear_messages()\n\n self.data = data\n if data is not None:\n n_instances = len(data)\n n_attrs = len(data.domain.attributes)\n self.infoLabel.setText(\"%i instances on input\\n%i attributes\" % (\n n_instances, n_attrs))\n\n self.graph_variables = [var for var in data.domain.attributes\n if var.is_continuous]\n if len(self.graph_variables) < 1:\n self.Information.not_enough_attrs()\n else:\n groupvars = [var for var in data.domain.variables +\n data.domain.metas if var.is_discrete]\n\n if len(groupvars) > 0:\n self.cb_attr.addItems([str(var) for var in groupvars])\n self.group_var = str(groupvars[0])\n self.group_variables = groupvars\n self.update_group_var()\n else:\n self._setup_plot()\n\n self.selection = []\n self.openContext(data)\n self.select_data_instances()\n self.commit()", "def set_data(self, data):\n self._model.set_data(data)\n self.__refresh()", "def set_data(self, dataset):\n if dataset is not None:\n self.infoa.setText('%d instances in input data set' % len(dataset))\n self.infob.setText('%d attributes in input data set' % len(dataset.domain.attributes))\n # Limited the batch size between 0.005 to 0.025, in\n # order tk=o make training fats and also accurate\n if(len(dataset) >= 200):\n self.batchsize = int(0.005 * len(dataset))\n self.batch_spin.setMinimum(int(0.005 * len(dataset)))\n self.batch_spin.setMaximum(int(0.025 * len(dataset)))\n else:\n # here the dataset is to small, hence fixed the\n # batch size programmatically\n self.batchsize = 1\n self.batch_spin.setMinimum(1)\n self.batch_spin.setMaximum(10)\n self.optionsBox.setDisabled(False)\n self.layerBox.setDisabled(False)\n self.updateLayer()\n self.dataset = dataset\n self.save_button.setDisabled(True)\n\n else:\n self.infoa.setText('No data on input yet, waiting to get something.')\n self.infob.setText('')\n self.optionsBox.setDisabled(True)\n self.layerBox.setDisabled(True)\n self.dataset = None", "def _setData(self):\n\n if not self.stationId:\n return\n \"\"\" \n # get the ressource url and adjust lat and lon from data portal\n query = sparqls.stationResource(self.stationId)\n key, val = RunSparql(query, 'array').run()\n if val: \n self.url = val[0][0]\n self.lat = float(val[0][2])\n self.lon = float(val[0][3])\n \"\"\"\n\n # it is possible, that a station id has multiple URI\n # ask for all URI\n query = sparqls.stationData(self.uri, 'all')\n data = RunSparql(query, 'pandas').run()\n\n if not data.empty:\n self._data = data\n else:\n self._data = 'no data available'\n\n # check if data is available and extract the 'unique' data products\n if isinstance(self._data, pd.DataFrame):\n p = self._data['specLabel'].unique()\n self._products = pd.DataFrame(p)\n\n # replace samplingheight=None with empty string\n self._data.samplingheight.replace(to_replace=[None], value=\"\", inplace=True)\n else:\n self._products = 'no data available'", "def set_data(self, data):\n\n # Convert voltages to currents and overwrite\n if self.use_unit == 'A':\n data['data'] = self.convert_to_unit(data['data'], self.use_unit)\n\n super(RawDataPlot, self).set_data(data)", "def set_generated_data(self, phd):\n \n if not phd.data_generated:\n raise ValueError('Data not found in {}'.format(phd))\n \n self.reset()\n \n self.true_data = phd.true_data\n self.timeline = phd.timeline\n self.observed_data = phd.observed_data\n self.n_time_steps = phd.n_time_steps\n self.e = phd.e\n self.region = phd.region\n self.poisson_window = phd.poisson_window\n self.poisson_coef = phd.poisson_coef\n self.poisson_mean = phd.poisson_mean\n self.poisson_cov = phd.poisson_cov\n\n self.r = phd.r\n self.data_generated = 1", "def setDmmInfo(self, data: list):\n repDmmInfo = [\n ['メーカー', data[0]],\n ['型式', data[1]],\n ['S/N', data[2]],\n ]\n self._dmm_info = repDmmInfo", "def set_data(self, data):\n\n pass", "def set_data(self, d):\n self._data = d\n self.is_data_set = True", "def _set_data(self):\n\n # Remove old elements from plot\n if self.scatter is not None:\n self.scatter.remove()\n if self.oneoneline is not None:\n self.oneoneline.remove()\n\n # Get new data and plot\n self.slice = self.results.set_index('Location').loc[self.locnaam, [self.input_parameter, self.result_parameter]].values.T\n self.scatter = self.ax.scatter(*self.slice, s=5, alpha=0.7, color='C0')\n\n # Determine axes limits\n lowerlim, upperlim = self.slice.min(), self.slice.max()\n span = (upperlim - lowerlim)\n lowerlim = max(0, lowerlim - 0.05 * span)\n upperlim = upperlim + 0.05 * span\n\n # Plot a diagonal 1:1 line\n self.oneoneline, = self.ax.plot([lowerlim, upperlim], [lowerlim, upperlim], color='grey', dashes=(4, 3), lw=1.0)\n\n # Set the axes limits\n self.ax.set_xlim(lowerlim, upperlim)\n self.ax.set_ylim(lowerlim, upperlim)\n self.canvas.draw()", "def create_data_model():\r\n data = {}\r\n data['distance_matrix'] = distance_matrix.tolist()\r\n data['time_matrix'] = time_matrix.tolist()\r\n data['time_windows'] = time_windows.tolist()\r\n data['pickups_deliveries'] = pickup_deliveries.tolist()\r\n data['demands'] = demand\r\n data['num_vehicles'] = 20\r\n data['vehicle_capacities'] = [20 * i / i for i in range(1, num_vehicles+1)]\r\n data['depot'] = (2 * length) - 1\r\n return data", "def stageData(self,m):\n obs = Variable(filename = self.source,\n variable_name = self.variable,\n alternate_vars = self.alternate_vars)\n if obs.time is None: raise il.NotTemporalVariable()\n self.pruneRegions(obs)\n \n # Try to extract a commensurate quantity from the model\n mod = m.extractTimeSeries(self.variable,\n alt_vars = self.alternate_vars,\n expression = self.derived,\n initial_time = obs.time_bnds[ 0,0],\n final_time = obs.time_bnds[-1,1],\n lats = None if obs.spatial else obs.lat,\n lons = None if obs.spatial else obs.lon)\n obs,mod = il.MakeComparable(obs,mod,\n mask_ref = True,\n clip_ref = True,\n extents = self.extents,\n logstring = \"[%s][%s]\" % (self.longname,m.name))\n \n # Check the order of magnitude of the data and convert to help avoid roundoff errors\n def _reduceRoundoffErrors(var):\n if \"s-1\" in var.unit: return var.convert(var.unit.replace(\"s-1\",\"d-1\"))\n if \"kg\" in var.unit: return var.convert(var.unit.replace(\"kg\" ,\"g\" ))\n return var\n def _getOrder(var):\n return np.log10(np.abs(var.data).clip(1e-16)).mean()\n order = _getOrder(obs)\n count = 0\n while order < -2 and count < 2:\n obs = _reduceRoundoffErrors(obs)\n order = _getOrder(obs)\n count += 1\n \n # convert the model data to the same unit\n mod = mod.convert(obs.unit)\n\n return obs,mod", "def set_data(self, time, data):\n for diagnostic in self._diagnostics_list:\n out = diagnostic(time, data)", "def fill_dataset(self):\n rm, rstd = self.get_rolling_stats()\n\n self.add_rolling_mean(rm)\n self.add_bollinger_bands(rstd)\n self.add_spy_info()\n self.add_beta_and_sharpe()\n self.add_stlouis_data()", "def setData(self, data: DataDictBase):\n super().setData(data)\n\n changes = self._analyzeData(data)\n self.plotDataType = determinePlotDataType(data)\n\n self._processPlotTypeOptions()\n self._plotData(adjustSize=True)", "def set_data():\r\n #if not os.path.exists(filepath):\r\n #download_data()\r\n metadata = read(filepath + flist[-1])\r\n ndata = metadata['num_cases_per_batch']\r\n ndim = metadata['num_vis']\r\n\r\n data, train, test = {}, {}, {}\r\n data['labels'] = metadata['label_names']\r\n data['ntraindata'] = metadata['num_cases_per_batch'] * (len(flist) - 2)\r\n data['ntestdata'] = metadata['num_cases_per_batch']\r\n data['ndim'] = metadata['num_vis']\r\n\r\n train['x'], train['y'] = convert_train(data['ntraindata'], data['ndim'])\r\n\r\n testdata = read(filepath + flist[-2])\r\n test['x'] = testdata['data']\r\n test['y'] = testdata['labels']\r\n\r\n data['train'], data['test'] = train, test\r\n save_pkl(data)", "def set_data(self , data_tuple:tuple): \n if(data_tuple != None): \n self.__data_idx = data_tuple[0]\n self.__data_value = data_tuple[1]\n self.__update_observers()", "def setDataUnits(self, dataunits):\n\t\tself.dataUnits = dataunits\n\t\t\n\t\tx, y, z = self.dataUnits[0].getDimensions()\n\t\tself.dims = (x, y, z)\n\t\tself.newDimX.SetValue(\"%d\" % x)\n\t\tself.newDimY.SetValue(\"%d\" % y)\n\t\tself.newDimZ.SetValue(\"%d\" % z)\n\t\tself.dimsLbl.SetLabel(self.currDimText % (x, y, z))\n\t\tself.onUpdateDims(None)\n\t\tself.onSetToHalfSize(None)", "def setData(self, data):\n self.data = data\n dagPath, components = self.__getGeometryComponents()\n self.setInfluenceWeights(dagPath, components)\n self.setBlendWeights(dagPath, components)\n\n for attr in ['skinningMethod', 'normalizeWeights']:\n cmds.setAttr('%s.%s' % (self.node, attr), self.data[attr])", "def setModelData(self, ledit, model, midx):\n sel = self._sel\n val = None\n txt = str(ledit.text())\n if txt:\n val = float(txt)\n cond = sel.give_cond(midx.row())\n cond[midx.column()] = val\n sel.notify_wizard()", "def set_data(self, data):\n self.data = data", "def setInfoData(self):\n self.infoData['id'] = str(self.id)\n self.infoData['name'] = str(self.name)\n self.infoData['space'] = str(self.space.id)\n self.infoData['size'] = str(self.size)\n self.infoData['ndof'] = str(self.ndof)\n self.infoData['type'] = str(self.type)\n self.infoData['operator'] = str(self.operator)\n self.infoData['operande_id'] = str(self.operande_id)\n self.infoData['func_arguments'] = str(self.func_arguments)\n self.infoData['nderiv'] = str(self.nderiv)\n self.infoData['parameval'] = str(self.parameval)\n self.infoData['paramevalfunc'] = str(self.paramevalfunc)\n self.infoData['loc_id'] = str(self.loc_id)", "def setDataModel(self, data_model: DataModel, v_id=-1):\n if v_id == -1:\n v_id = self.getCurrentId()\n assert v_id is not -1, \"Invalid set data command encountered.\"\n self._model.getViewerCtrl(v_id).updateModel(data_model)\n self._onDataChanged(v_id)", "def _setData(self):\n data_list = []\n results = self.query.all()\n formatter = date.getLocaleFormatter(self.request, \"date\", \"long\")\n for result in results:\n data ={}\n data[\"qid\"]= (\"m_\" + str(result.motion_id))\n data[\"subject\"] = u\"M \" + str(result.motion_number) + u\" \" + result.short_name\n data[\"title\"] = result.short_name\n if result.approval_date:\n data[\"result_item_class\"] = (\"workflow-state-\" + \n result.status + \"sc-after-\" + \n datetime.date.strftime(result.approval_date, \"%Y-%m-%d\"))\n else:\n data[\"result_item_class\"] = \"workflow-state-\" + result.status\n data[\"url\"] = url.set_url_context(\"motions/obj-\" + str(result.motion_id))\n data[\"status\"] = misc.get_wf_state(result)\n data[\"status_date\"] = formatter.format(result.status_date)\n data[\"owner\"] = \"%s %s\" %(result.owner.first_name, result.owner.last_name)\n data[\"type\"] = _(result.type)\n data[\"to\"] = \"\"\n data_list.append(data)\n self._data = data_list", "def _get_data(self) -> dict:\n LOGGER.debug(f\"Setting data property for {self.dirname}\")\n data = {}\n for axis in range(1, 4):\n # Subsample by 8 since this does not vary quickly\n data[f\"aoatter{axis}\"] = (\n self.tlm[f\"aoatter{axis}\"].vals[::ATT_ERR_SUBSAMP].astype(np.float32)\n )\n data[\"aokalstr\"] = self.tlm[\"aokalstr\"].vals\n # fmt: off\n data[\"npnt_kalm\"] = (\n (self.tlm[\"aopcadmd\"].vals == \"NPNT\")\n & (self.tlm[\"aoacaseq\"].vals == \"KALM\")\n )\n # fmt: on\n for slot in range(8):\n data[f\"aca_track{slot}\"] = self.tlm[f\"aoacfct{slot}\"].vals == \"TRAK\"\n data[f\"aca_ir{slot}\"] = self.tlm[f\"aoaciir{slot}\"].vals == \"ERR\"\n data[\"times\"] = self.tlm[\"aokalstr\"].times\n data[\"perigee_times\"] = self.tlm.perigee_times.astype(np.float32)\n data[\"perigee\"] = self.perigee.date\n data[\"rad_entry\"] = self.rad_entry.date\n data[\"rad_exit\"] = self.rad_exit.date\n data[\"obss\"] = self.obss.as_array()\n\n return data", "def set_data(self):\n # take care of samples\n patients = self.samples.iloc[:,1].tolist()\n samples = self.samples.iloc[:,0].tolist()\n self.samples = pd.DataFrame(patients,index = samples,columns = ['patient']) # indexed by sample\n #\n # take care of expression data\n cols = self.expression.SYMBOL.tolist() # set new column names to transposed expression_data \n \n new_exp = self.expression.T.ix[1:,:] # transpose\n new_exp.columns = cols\n self.expression = new_exp # add columns\n self.data = pd.merge(self.expression,self.samples,left_index = True,right_index=True) # merged data sets\n #pd.merge(df1,df2,how = 'left',left_index=True,right_index=True) # do a left join", "def set_data(self,pdata):\n self.uid.data=pdata[0]\n self.pid.data=pdata[1]\n self.pName.data=pdata[2]\n self.pAge.data=pdata[3]\n self.dateOfSubmission.data=pdata[4]\n self.bedType.data=pdata[5]\n self.address.data=pdata[6]\n self.city.data=pdata[7]\n self.state.data=pdata[8]\n self.status.data=pdata[9]", "def __init__(self, name, data):\n super(PoissonEM, self).__init__(name)\n\n self._register_variable('mock_data', differentiable=True)\n self.data = data\n self.update_var_param_types(mock_data=ArrayParameter)\n self._set_original_variables()", "def setData(self, **kwds):\n self.text = kwds.pop('text', [])\n self.data = kwds\n if 'pos' in self.data:\n npts = self.data['pos'].shape[0]\n self.data['data'] = np.empty(npts, dtype=[('index', int)])\n self.data['data']['index'] = np.arange(npts)\n self.setTexts(self.text)\n self.updateGraph()", "def setData(self, data):\n self.data = data" ]
[ "0.6253465", "0.5959073", "0.59506583", "0.58824116", "0.58592606", "0.5852012", "0.58044004", "0.5789111", "0.5774705", "0.57636905", "0.57049507", "0.5695745", "0.5694147", "0.566052", "0.5614362", "0.56030023", "0.56024325", "0.55722237", "0.5571405", "0.5559015", "0.55556196", "0.55426526", "0.55294406", "0.55192465", "0.54990315", "0.54978323", "0.5489525", "0.5487714", "0.54823387", "0.5477169" ]
0.61870927
1
Sets the prior distribution of the model parameters. The logprior dimensions are assumed to be ordered according to
def set_log_prior(self, log_prior): # Check prerequesites if self._data is None: raise ValueError('The data has not been set.') # Check inputs if not isinstance(log_prior, pints.LogPrior): raise ValueError( 'The log-prior has to be an instance of pints.LogPrior.') if log_prior.n_parameters() != self.get_n_parameters(): raise ValueError( 'The dimension of the log-prior has to be the same as the ' 'number of parameters in the model. There are <' + str(self.get_n_parameters()) + '> model parameters.') self._log_prior = log_prior
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def log_prior(self):\n raise NotImplementedError(\"the log_prior property should \"\n \"be defined in the Estimator sub-class\")", "def set_prior(self,field):\n self.observation_thresholds = [i/self.observations for i in range(0,self.observations)]\n self.observation_samples = 1\n # TODO: For use after integrating image processing with MCESP for Game-Delayed Reinforcements\n # self.norm = field.max()", "def setPrior(self,xPrior,priorWeight):\n assert self.regularizationLambda == 0\n if not isinstance(xPrior,np.ndarray):\n xPrior = np.array(xPrior)\n self.count = 1\n self.sumWeight = priorWeight\n self.scale = 1\n self.AtA = np.eye(self.n)*priorWeight\n self.AtAinv = np.eye(self.n)/priorWeight\n self.Atb = xPrior*priorWeight\n self.btb = np.dot(xPrior,xPrior)*priorWeight\n self.degenerate = False\n self.x = xPrior", "def log_prior(self, x_scaled):\n x = scale_inverse_transform(self.parameters_scaler, x_scaled)\n ln_prior = {}\n for key in self.param_names:\n try:\n ln_prior[key] = self.priors[key].log_prob(x[:, self.param_names.index(key)])\n except TypeError:\n x = tf.cast(x, tf.float32)\n ln_prior[key] = self.priors[key].log_prob(x[:, self.param_names.index(key)])\n ln_prior_sum = tf.math.reduce_sum(tf.convert_to_tensor(list(ln_prior.values()), dtype=float_type),\n axis=0)\n # If prior is finite, replace with zero\n zero_prior = tf.zeros_like(ln_prior_sum)\n constraints = tf.math.is_inf(ln_prior_sum)\n tensor_log_prior = tf.where(constraints, ln_prior_sum, zero_prior)\n return tensor_log_prior", "def log_prior(self, params):\n # log likelihood function, see:\n # https://en.wikipedia.org/wiki/Multivariate_normal_distribution#Likelihood_function\n variance = self.std ** 2\n ndim = params.ndim\n mean_diff = params - self.mean\n scaled_sq_err = jnp.dot(mean_diff, mean_diff) / variance\n # log determinant of covariance matrix\n log_det_cov = 2 * ndim * jnp.log(self.std)\n norm_term = ndim * jnp.log(2 * jnp.pi)\n return -0.5 * (log_det_cov + scaled_sq_err + norm_term)", "def gaussian_prior(self):\n self.prior = sps.multivariate_normal(self.m0,self.S0)", "def set_prior(self, parameter, prior):\n\n if parameter in self.parameter_map:\n self._mcmc.set_prior(self.parameter_map[parameter], prior)\n else:\n raise AstropyUserWarning(\"Parmater {name} not found in parameter\"\n \"map\".format(name=parameter))", "def log_prior(self, params):", "def lnprior(self,theta):\n kwargs = dict(zip(self.params,theta))\n err = np.seterr(invalid='raise')\n try:\n lnprior = np.sum(np.log([self.priors[k](v) for k,v in kwargs.items()]))\n except FloatingPointError,ValueError:\n lnprior = -np.inf\n np.seterr(**err)\n return lnprior", "def log_prior_parameters(self, x):\n par_dict = self.get_par_dict(x)\n exclude_parameters = list(set(par_dict.keys())-set(self.fit_parameters)-set(self.nuisance_parameters))\n prob_dict = self.par_obj.get_logprobability_all(par_dict, exclude_parameters=exclude_parameters)\n return sum([p for obj, p in prob_dict.items()])", "def log_prior_parameters(self, x):\n par_dict = self.get_par_dict(x)\n exclude_parameters = list(set(par_dict.keys())-set(self.fit_parameters)-set(self.nuisance_parameters))\n prob_dict = self.par_obj.get_logprobability_all(par_dict, exclude_parameters=exclude_parameters)\n return sum([p for obj, p in prob_dict.items()])", "def lnprior(self, params):\n self.debug.start_function('lnprior')\n lower_bounds = self.mcmc_version.prior_bounds[:, 0]\n upper_bounds = self.mcmc_version.prior_bounds[:, 1]\n inside_bounds = np.logical_and(params > lower_bounds,\n params < upper_bounds)\n\n if False in inside_bounds:\n self.debug.end_function()\n return self.zero_lhood\n\n if self.has_logz:\n z_input = params[self.param_idxs['logz']]\n else:\n z = params[self.param_idxs['z']]\n z_input = np.log10(z / z_sun)\n\n prior_lhood = np.log(self.z_prior(z_input))\n\n # ===== anisotropy/inclination priors =====\n if self.has_two_f:\n xi_ratio = params[self.param_idxs['f_p']] / params[self.param_idxs['f_b']]\n prior_lhood += np.log(self.xi_ratio_prior(xi_ratio))\n elif self.has_xi_ratio:\n xi_ratio = params[self.param_idxs['xi_ratio']]\n d_b = params[self.param_idxs['d_b']]\n prior_lhood += np.log(self.xi_ratio_prior(xi_ratio))\n prior_lhood += np.log(self.d_b_prior(d_b))\n\n self.debug.variable('prior_lhood', prior_lhood, formatter='f')\n self.debug.end_function()\n return prior_lhood", "def logdprior(parameters, hyperparameters):\n sigma_w_part = parameters[0] + invgamma_logpdf(parameters[0],\n hyperparameters[\"sigma_w_shape\"], hyperparameters[\"sigma_w_scale\"])\n sigma_v_part = parameters[1] + invgamma_logpdf(parameters[1], hyperparameters[\"sigma_v_shape\"], hyperparameters[\"sigma_v_scale\"])\n return sigma_w_part + sigma_v_part", "def get_prior(self):\n assert self._prior in self._priors, 'Unsupported prior! Check the _priors attribute for a list of priors.'\n if self._prior == 'Gaussian':\n prior = 0.5 * torch.sum(self.parameters ** 2)/self.prior_var\n elif self._prior == 'Cauchy':\n dimconst = (self.parameters.shape[0] + 1)/2.\n prior = dimconst*torch.log(self.prior_var + torch.sum(self.parameters ** 2))\n elif self._prior == 'Sparse':\n n = self.dataset.shape[1]\n gauss_prior = 0.5 * torch.sum(torch.exp(self.parameters[-1] * torch.exp(self.parameters[n:2*n]) * self.parameters[:n] ** 2))\n gamma_density = torch.distributions.Gamma(1.5,0.5)\n# gamma_prior = -gamma_density.log_prob(torch.exp(self.parameters[n:])).sum()\n# lambda_density = torch.distributions.Gamma(1.5,0.5)\n lambda_prior = -gamma_density.log_prob(torch.exp(self.parameters[n:])).sum()\n prior = gauss_prior + lambda_prior\n return prior", "def lnprior(self):\n \n return", "def prior_param(self, param_dict={}): \n self.param_obj = Params(param_dict) # parameter object \n self.param_names = param_dict.keys() \n self.n_params = len(param_dict.keys()) # number of parameters in theta ", "def prior(self, batch_size: int = 1) -> Distribution:\n prior_params = self.prior_params.expand(\n batch_size, *self.prior_params.shape[-1:]\n )\n mu, log_sigma = prior_params.chunk(2, dim=-1)\n\n # return the distribution `p(z)`\n return Normal(mu, log_sigma.exp())", "def set_prior(self,which,what):\n\n which = self.grep_param_names(which)\n\n #check tied situation\n tie_partial_matches = [tie for tie in self.tied_indices if (not set(tie).isdisjoint(set(which))) & (not set(tie)==set(which))]\n if len(tie_partial_matches):\n raise ValueError, \"cannot place prior across partial ties\"\n tie_matches = [tie for tie in self.tied_indices if set(which)==set(tie) ]\n if len(tie_matches)>1:\n raise ValueError, \"cannot place prior across multiple ties\"\n elif len(tie_matches)==1:\n which = which[:1]# just place a prior object on the first parameter\n\n\n #check constraints are okay\n if isinstance(what, (priors.gamma, priors.log_Gaussian)):\n assert not np.any(which[:,None]==self.constrained_negative_indices), \"constraint and prior incompatible\"\n assert not np.any(which[:,None]==self.constrained_bounded_indices), \"constraint and prior incompatible\"\n unconst = np.setdiff1d(which, self.constrained_positive_indices)\n if len(unconst):\n print \"Warning: constraining parameters to be positive:\"\n print '\\n'.join([n for i,n in enumerate(self._get_param_names()) if i in unconst])\n print '\\n'\n self.constrain_positive(unconst)\n elif isinstance(what,priors.Gaussian):\n assert not np.any(which[:,None]==self.all_constrained_indices()), \"constraint and prior incompatible\"\n else:\n raise ValueError, \"prior not recognised\"\n\n\n #store the prior in a local list\n for w in which:\n self.priors[w] = what", "def set_prior_distribution(self, dist: BaseDistribution):\n # TODO(thiagovas): Raise an exception if len(dist) != self.n_rows.\n self.prior = dist\n return self", "def add_prior(self, prior):\n if self.rate_variation:\n # Gamma prior with mean 1 over all mutation rates\n sub_prior = ET.SubElement(prior, \"prior\", {\"id\":\"featureClockRatePrior.s:%s\" % self.name, \"name\":\"distribution\"})\n compound = ET.SubElement(sub_prior, \"input\", {\"id\":\"featureClockRateCompound:%s\" % self.name, \"spec\":\"beast.core.parameter.CompoundValuable\", \"name\":\"x\"})\n plate = ET.SubElement(compound, \"plate\", {\n \"var\":\"feature\",\n \"range\":\",\".join(self.features)})\n ET.SubElement(plate, \"var\", {\n \"idref\":\"featureClockRate:%s:$(feature)\" % self.name})\n gamma = ET.SubElement(sub_prior, \"input\", {\"id\":\"featureClockRatePriorGamma:%s\" % self.name, \"spec\":\"beast.math.distributions.Gamma\", \"name\":\"distr\", \"alpha\":\"@featureClockRateGammaShape:%s\" % self.name, \"beta\":\"@featureClockRateGammaScale:%s\" % self.name})\n # Exponential hyperprior on scale of Gamma prior\n # Exponential prior favours small scales over large scales, i.e. less rate variation\n # Mean scale 0.23 chosen for general sensibility, e.g.:\n # - Prior distribution is roughly 50/50 that ratio of fastest\n # to slowest feature rate in a dataset of size 200 is below\n # or above 10.\n # - Prior probability of roughly 0.90 that this ratio is below\n # 100.\n sub_prior = ET.SubElement(prior, \"prior\", {\"id\":\"featureClockRateGammaScalePrior.s:%s\" % self.name, \"name\":\"distribution\", \"x\":\"@featureClockRateGammaScale:%s\" % self.name})\n ET.SubElement(sub_prior, \"Exponential\", {\"id\":\"featureClockRateGammaShapePriorExponential.s:%s\" % self.name, \"mean\":\"0.23\", \"name\":\"distr\"})", "def compute_log_prior(self,params: ndarray) -> float:\n ln_tE = params[0]\n ln_A0 = params[1]\n ln_deltaT = params[2]\n fbl = params[3]\n mb = params[4]\n\n # Equation (16,15,17) (note that Albrow uses \"log\" for log10)\n log10e = np.log10(np.exp(1))\n ln_pr_ln_tE = np.log(0.476) - ((log10e*ln_tE - 1.333)**2 / 0.330) + np.log(log10e)\n ln_pr_ln_A0 = np.log(0.660) - (1.289*log10e*ln_A0) + np.log(log10e)\n ln_pr_ln_deltaT = np.log(0.156) - ((log10e*ln_deltaT - 1.432)**2 / 0.458) +\\\n np.log(log10e)\n \n # Paper doesnt mention the prior used, but I assume it to be uniform\n ln_pr_fbl = uniform.logpdf(fbl,0.0,1.0)\n\n # Paper doesnr mention the prior used but I will asuumed it to be uniform\n ln_pr_mb = uniform.logpdf(mb,self.mag_min - 1.0, self.mag_max + 1.0)\n \n \n return ln_pr_fbl + ln_pr_ln_A0 + ln_pr_ln_deltaT + ln_pr_ln_tE + ln_pr_mb", "def set_prior_priorunc_general(self):\n\n #-- some configurations apply absolute uncertainties\n lai_coeff_absunc = None\n statevec_absunc = None\n is_generic_prior = False\n\n #--\n if self.prior_states_file!=None:\n states_file = self.prior_states_file\n basename = os.path.basename(states_file)\n if os.path.splitext(basename)[1]=='.nc':\n msg = \"Prior state information will be read from ***{}***\".format(states_file)\n FileLogger.info(msg)\n self._setprior_jules(states_file)\n msg = \"...reading prior DONE\"\n FileLogger.info(msg)\n elif os.path.splitext(basename)[1]=='.csv':\n msg = \"Prior state information will be read from ***{}***\".format(states_file)\n FileLogger.info(msg)\n self._setprior_csv(states_file)\n msg = \"...reading prior DONE\"\n FileLogger.info(msg)\n else:\n msg = \"Unrecognised format of states file ***{}***. Cannot continue!\".format(\n states_file)\n FileLogger.fatal(msg)\n raise RuntimeError(msg)\n return\n elif self.prior_inifile!=None:\n lai_coeff_absunc, statevec_absunc = self._setprior_from_inifile()\n else:\n self._setprior_generic_agriculture()\n is_generic_prior = True\n statevec_absunc = self.generic_prior_unc\n\n #-- set uncertainty values\n self._set_priorunc( lai_coeff_absunc=lai_coeff_absunc,\n statevec_absunc=statevec_absunc,\n is_generic_prior=is_generic_prior )", "def _log_prior_gradients(self):\n x = self._get_params()\n ret = np.zeros(x.size)\n [np.put(ret,i,p.lnpdf_grad(xx)) for i,(p,xx) in enumerate(zip(self.priors,x)) if not p is None]\n return ret", "def log_prior(x):\n logp = (-0.5 * x.pow(2) - torch.tensor(2 * math.pi).sqrt().log()).sum(dim=1)\n return logp", "def add_rate_parameter(self, source_name, log_prior=None):\n self.rate_parameters[source_name] = log_prior", "def logPriorFlat(paramsVec, params):\n logPrior = 0 #ln(1) = 0\n if params is None:\n #Maximally flat prior: p=1 always\n pass\n else:\n paramsDict = params.valuesdict()\n\n #Loop through parameter bounds and update the prior\n for kindex, key in enumerate(paramsDict.keys()):\n if (params[key].min < paramsVec[kindex] < params[key].max):\n pass\n else:\n logPrior = -np.inf #ln(0) = -inf\n return logPrior", "def lnprior(theta, ref_time, fit_qm=False, prior_params=prior_params_default):\n \n if fit_qm:\n Omega_angle, omega_angle, i_angle, a_axis, ecc, period, T0, mu_delta, \\\n mu_alpha, pi_p, Ddelta_ref, Dalpha_ref, q_m = theta\n else:\n Omega_angle, omega_angle, i_angle, a_axis, ecc, period, T0, mu_delta, \\\n mu_alpha, pi_p, Ddelta_ref, Dalpha_ref = theta\n \n lprior = 0\n lprior += st.uniform.logpdf(Omega_angle, loc=0, scale=180)\n lprior += st.uniform.logpdf(omega_angle, loc=-180, scale=360)\n lprior += st.uniform.logpdf(i_angle, loc=0, scale=90)\n \n lprior += st.halfnorm.logpdf(a_axis, **prior_params['a_axis'])\n \n lprior += st.uniform.logpdf(ecc, loc=0, scale=1)\n \n lprior += st.uniform.logpdf(period, **prior_params['period'])\n lprior += st.uniform.logpdf(T0, loc=ref_time, scale=period)\n \n lprior += st.norm.logpdf(mu_delta, **prior_params['mu_delta'])\n lprior += st.norm.logpdf(mu_alpha, **prior_params['mu_alpha'])\n\n lprior += st.halfnorm.logpdf(pi_p, **prior_params['pi_p'])\n \n lprior += st.norm.logpdf(Ddelta_ref, **prior_params['Ddelta_ref'])\n lprior += st.norm.logpdf(Dalpha_ref, **prior_params['Dalpha_ref'])\n \n if fit_qm:\n lprior += st.halfnorm.logpdf(q_m, **prior_params['q_m'])\n \n return lprior", "def get_log_prior(samples):\n prior_distribution = tfp.distributions.Normal(loc=0., scale=1.)\n log_prior = tf.reduce_sum(prior_distribution.log_prob(samples), axis=1)\n return log_prior", "def buildWPriorTerm(self):\r\n\r\n # self.w_prior.shape == (minibatch size,)\r\n self.w_prior = 0.5*T.sum(1 + T.log(self.qwgy_var) - self.qwgy_mu**2-self.qwgy_var, axis=1)\r\n\r\n self.w_prior_modif = - T.maximum(self.hyper['treshold_w_prior'], -self.w_prior)", "def buildZPriorTerm(self):\r\n\r\n # shape is (batch size,)\r\n self.z_prior = - T.mean(T.sum(T.exp(self.log_pzgxw)*(self.log_pzgxw + T.log(self.hyper['num_clust'])), axis=3), axis=[1,2])\r\n\r\n self.z_prior_modif = - T.maximum(self.hyper['treshold_z_prior'], - self.z_prior)" ]
[ "0.6979534", "0.67951566", "0.6770433", "0.67217827", "0.6695372", "0.6652549", "0.6615611", "0.66131043", "0.65986574", "0.6573988", "0.6573988", "0.6571616", "0.6439268", "0.6432067", "0.64283925", "0.6425549", "0.64170766", "0.6353341", "0.6342298", "0.62882614", "0.62469316", "0.62004423", "0.6193541", "0.61859035", "0.6142054", "0.614148", "0.61377007", "0.61342514", "0.61101013", "0.6109235" ]
0.8004486
0
Sets the population model. A population model specifies how model parameters vary across individuals. The dimension of the population model has to match the number of model parameters.
def set_population_model(self, population_model): # Check inputs if not isinstance(population_model, chi.PopulationModel): raise TypeError( 'The population model has to be an instance of ' 'chi.PopulationModel.') # Make sure that dimension of population model is correct n_parameters = self.get_n_parameters(exclude_pop_model=True) if population_model.n_dim() != n_parameters: raise ValueError( 'The dimension of the population model does not match the ' 'number of bottom-level parameters. There are ' '<' + str(n_parameters) + '> bottom-level parameters.') # Remember population model self._population_model = population_model # Set number of modelled individuals, if data has been set already if self._data is not None: self._population_model.set_n_ids(len(self._ids)) # Set dimension names to bottom-level parameters names = self.get_parameter_names(exclude_pop_model=True) self._population_model.set_dim_names(names) # Check that covariates can be found, if data has already been set if self._data is not None: try: # Get covariate names covariate_names = self.get_covariate_names() observables = self._data[self._obs_key].dropna().unique() self._covariate_dict = self._check_covariate_dict( self._covariate_dict, covariate_names, observables) except ValueError: # New population model and data are not compatible, so reset # data self._data = None warn( 'The covariates of the new population model could not ' 'automatically be matched to the observables in the ' 'dataset. The data was therefore reset. Please set the ' 'data again with the `set_data` method and specify the ' 'covariate mapping.', UserWarning) # Set prior to default self._log_prior = None
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def setPop(self, pop: Population):\n self.population = pop\n self.population_size = pop.size()", "def init_pop(self):\n genes = np.random.randn( self.population_size * self.individual.gene_count )\n self.population = genes.reshape((self.population_size, -1))\n #print(self.population)", "def evolve_population(self, **options):\n new_population = self.population.evolve(**options)\n self.population = new_population\n self.generation = new_population.generation_number", "def __init__(self, model, num_solutions):\r\n \r\n self.model = model\r\n\r\n self.num_solutions = num_solutions\r\n\r\n # A list holding references to all the solutions (i.e. networks) used in the population.\r\n self.population_weights = self.create_population()", "def set_model(self, model):\n '''returns a model'''\n if self.model==\"Lasso\":\n modelo = Lasso()\n elif self.model==\"Ridge\":\n modelo = Ridge()\n elif self.model == \"RandomForest\":\n modelo = RandomForestRegressor(random_state = 42)\n else:\n if self.model == \"XGBoost\":\n modelo = xgb.XGBRegressor()\n #modelo = xgb.XGBRegressor(booster = 'gbtree', objective ='reg:squarederror',\n # colsample_bytree = 0.3, learning_rate = 0.35,\n # max_depth = 10, alpha = 0.1, n_estimators = 500)\n\n\n return modelo", "def with_population_variance(self, variance):\n\t\tself.variables['population_variance'] = variance\n\t\treturn self", "def set_model(self, model_name):\n pass", "def init_population(self):\n pass", "def model_family(self, model_family: str):\n\n self._model_family = model_family", "def setSigma(self, sigma):\n assert len(sigma) == self.explorationlayer.paramdim\n # change the parameters of the exploration layer (owner is self.module)\n self.explorationlayer._setParameters(sigma, self.module)", "def set_model(self, model=None):\n self.model = model", "def set_model(self, likelihood_model_instance):\n pass", "def set_model(self, likelihood_model_instance):\n pass", "def set_Model(newModel):\n global model\n model = newModel\n print(\"model is set\")\n print(model)", "def set_parameters(self, **kwargs):\n kwargs.pop('population_size', None)\n super().set_parameters(population_size=1, **kwargs)\n self.candidates = None", "def _initialize_model(self):\n max_value = self.data.max()\n\n if self.model_type == self._GAUSSIAN2D:\n model = models.Gaussian2D(\n x_mean=self.x, y_mean=self.y, x_stddev=1, y_stddev=1\n )\n model.amplitude = max_value\n\n # Establish reasonable bounds for the fitted parameters\n model.x_stddev.bounds = (0, self._box / 4)\n model.y_stddev.bounds = (0, self._box / 4)\n model.x_mean.bounds = (self.x - 5, self.x + 5)\n model.y_mean.bounds = (self.y - 5, self.y + 5)\n\n elif self.model_type == self._MOFFAT2D:\n model = models.Moffat2D()\n model.x_0 = self.x\n model.y_0 = self.y\n model.gamma = 2\n model.alpha = 2\n model.amplitude = max_value\n\n # Establish reasonable bounds for the fitted parameters\n model.alpha.bounds = (1, 6)\n model.gamma.bounds = (0, self._box / 4)\n model.x_0.bounds = (self.x - 5, self.x + 5)\n model.y_0.bounds = (self.y - 5, self.y + 5)\n\n model += models.Const2D(self.fit_sky())\n model.amplitude_1.fixed = True\n return model", "def create_population(self):\n stagnation = DefaultStagnation(self.config.population, self.reporters)\n self.reporters = ReporterSet()\n self.reproduction = DefaultReproduction(self.reporters, stagnation)\n \n # Create a population from scratch, then partition into species\n self.population = self.reproduction.create_new(config=self.config,\n num_genomes=self.config.population.pop_size)\n self.species = DefaultSpecies(reporters=self.reporters)\n self.species.speciate(config=self.config,\n population=self.population,\n generation=self.generation,\n logger=self.log)\n \n # Add to each of the species its elites\n self.update_species_fitness_hist()\n \n # Use 'print' to output information about the run\n reporter = StdOutReporter()\n self.add_reporter(reporter)\n \n # Save newly made population\n self.save()\n \n # Write population configuration to file\n with open(f\"population{'_backup' if self.use_backup else ''}/\"\n f\"storage/\"\n f\"{self.folder_name}/\"\n f\"{self}/\"\n f\"config.txt\", 'w') as f:\n f.write(self.config.read())", "def set_model(self, model):\n self.model = model", "def set_model(self, model):\n self.model = model", "def set_model(self):\n self.model = self.get_model()", "def set_param(self, weights, mu, sigma):\n #XXX: when fromvalues is called, parameters are called twice...\n k, d, mode = check_gmm_param(weights, mu, sigma)\n if not k == self.k:\n raise GmParamError(\"Number of given components is %d, expected %d\" \n % (k, self.k))\n if not d == self.d:\n raise GmParamError(\"Dimension of the given model is %d, \"\\\n \"expected %d\" % (d, self.d))\n if not mode == self.mode and not d == 1:\n raise GmParamError(\"Given covariance mode is %s, expected %s\"\n % (mode, self.mode))\n self.w = weights\n self.mu = mu\n self.va = sigma\n\n self.__is_valid = True", "async def gpt2_set_model(self, ctx, *, arg=None):\n print('Command gpt2_set_model triggered')\n if arg:\n if arg in VALID_DEFAULT_MODELS:\n self.update_config(model_name=arg)\n else:\n await ctx.send(f\"ERROR: Invalid model name {arg}\")\n else:\n await ctx.send(\"ERROR: Argument required\")", "def model_setup(self):\n self.DNN = SganMLP(self.settings.number_of_bins)\n self.D = SganMLP(self.settings.number_of_bins)\n self.G = Generator()", "def setModel(self, *args):\n return _libsbml.L3ParserSettings_setModel(self, *args)", "def setModel(self, *args):\n return _libsbml.SBMLDocument_setModel(self, *args)", "def setModel(self, model):\n self._model: SceneGraphModel = model\n self._dataMapper.setModel(model)\n self._dataMapper.addMapping(self.ui.uiViewport, 2)\n self._dataMapper.addMapping(self.ui.uiViewportAuxiliry, 3)\n self._dataMapper.addMapping(self.ui.uiViewportName, 4)\n self._dataMapper.addMapping(self.ui.uiViewportCoordinate, 5)", "def setModel(self, model):\n self._model: SceneGraphModel = model\n self._dataMapper.setModel(model)\n self._dataMapper.addMapping(self.ui.uiViewport, 2)\n self._dataMapper.addMapping(self.ui.uiViewportAuxiliry, 3)\n self._dataMapper.addMapping(self.ui.uiViewportName, 4)\n self._dataMapper.addMapping(self.ui.uiViewportCoordinate, 5)", "def setModel(self, model):\n self._model: SceneGraphModel = model\n self._dataMapper.setModel(model)\n self._dataMapper.addMapping(self.ui.uiViewport, 2)\n self._dataMapper.addMapping(self.ui.uiViewportAuxiliry, 3)\n self._dataMapper.addMapping(self.ui.uiViewportName, 4)\n self._dataMapper.addMapping(self.ui.uiViewportCoordinate, 5)", "def setModel(self, model):\n self._model: SceneGraphModel = model\n self._dataMapper.setModel(model)\n self._dataMapper.addMapping(self.ui.uiViewport, 2)\n self._dataMapper.addMapping(self.ui.uiViewportAuxiliry, 3)\n self._dataMapper.addMapping(self.ui.uiViewportName, 4)\n self._dataMapper.addMapping(self.ui.uiViewportCoordinate, 5)", "def set_model(self, model):\n\n # attach the model to the object\n self._likelihood_model = model\n\n # the position for the point source is freed\n for key in self._likelihood_model.point_sources.keys():\n self._likelihood_model.point_sources[key].position.ra.free = True\n self._likelihood_model.point_sources[key].position.dec.free = True\n\n # set proper priors for the coordinates\n self._likelihood_model.point_sources[key].position.ra.prior = Uniform_prior(lower_bound=0., upper_bound=360)\n self._likelihood_model.point_sources[key].position.dec.prior = Cosine_Prior(lower_bound=-90., upper_bound=90)" ]
[ "0.62167", "0.5926654", "0.5786187", "0.56787527", "0.54684395", "0.5381719", "0.5370427", "0.5369406", "0.53193176", "0.5302784", "0.52923334", "0.52427626", "0.52427626", "0.5241639", "0.5236702", "0.523217", "0.52262396", "0.52212846", "0.52212846", "0.52067775", "0.5190474", "0.5165172", "0.51602805", "0.5075249", "0.5073089", "0.50708735", "0.50708735", "0.50708735", "0.50708735", "0.5036422" ]
0.78179437
0
Runs many iterations of the two_player_game_iter, totalling results.
def full_game(iters, n=30): # Create empty total matrices total_1 = np.zeros((n, n)) total_2 = np.zeros((n, n)) # Simulate iters for _ in range(iters): # Get single iter mat_1, mat_2 = two_player_game_iter(n=n) # Add each payoff to totals total_1 += mat_1 total_2 += mat_2 return total_1, total_2
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def playGames(self, num, sonete,secuence,mcts,verbose=False):\n eps_time = AverageMeter()\n bar = Bar('Arena.playGames', max=num)\n end = time.time()\n eps = 0\n maxeps = int(num)\n finalScore1=0\n finalScore2=0\n\n num = int(num/2)\n oneWon = 0\n twoWon = 0\n draws = 0\n gameResults=[]\n global nround\n actions=[]\n self.player1, self.player2 = self.player1, self.player1\n board = self.game.getInitBoard()\n for i in range(100):\n nround = i\n #action,sonete = self.playGame(sonete,sequences,nround,verbose=verbose)\n pi = mcts.getActionProb(sonete, temp=1)\n #actions.append(action)\n\n eps_time.update(time.time() - end)\n end = time.time()\n\n\n return actions#finalScore1, finalScore2#oneWon, twoWon, draws", "def test_multiple_games(self, iteration=10):\n # TODO: multithread?\n for i in range(iteration):\n self.test_one_game()", "def analyze_end_performance(self) -> None:\n self.logger.info(f\"###### FINAL RESULTS FOR EACH GAME###### \\n\")\n total_results = [0, 0, 0, 0]\n for game in self.instance_predictions:\n self.logger.info(f\"Simulated game {game.home_team.name} vs {game.away_team.name} \"\n f\"{len(self.instance_predictions[game])} times.\")\n confusion_matrix = [0, 0, 0, 0]\n for predicted_winner in self.instance_predictions[game]:\n actual_winner = game.home_team if game.home_team.scores.get(\n GamePeriod.TOTAL) > game.away_team.scores.get(GamePeriod.TOTAL) else game.away_team\n actual_home_team_won = True if actual_winner == game.home_team else False\n predicted_home_team_won = True if predicted_winner == game.home_team else False\n confusion_matrix = recursive_build_confusion_matrix(confusion_matrix, actual_home_team_won,\n predicted_home_team_won)\n total_results[0] += confusion_matrix[0]\n total_results[1] += confusion_matrix[1]\n total_results[2] += confusion_matrix[2]\n total_results[3] += confusion_matrix[3]\n\n for k, v in analyze_confusion_matrix(confusion_matrix, len(self.instance_predictions[game])).items():\n self.logger.info(f\"{k} : {v}\")\n self.logger.info(\"\\n###### FINAL RESULTS FOR ALL GAMES###### \\n\")\n final_stats = analyze_confusion_matrix(total_results, sum(total_results))\n for k, v in final_stats.items():\n self.logger.info(f\"{k} : {v}\")\n self.write_stats_to_json(final_stats, self.outfile)", "def playGames(self, num, verbose=False):\n oneWon = 0\n twoWon = 0\n draws = 0\n print(\"Player1 as First, Player2 as Second\")\n for _ in range(num):\n print((oneWon, twoWon, draws))\n gameResult = self.playGame(verbose=verbose)\n if gameResult == 1:\n oneWon += 1\n elif gameResult == -1:\n twoWon += 1\n else:\n draws += 1\n\n self.player1, self.player2 = self.player2, self.player1\n print(\"Player1 as Second, Player2 as First\")\n for i in range(num):\n print((oneWon, twoWon, draws))\n gameResult = self.playGame(verbose=verbose)\n if gameResult == -1:\n oneWon += 1\n elif gameResult == 1:\n twoWon += 1\n else:\n draws += 1\n\n print((oneWon, twoWon, draws))\n return oneWon, twoWon, draws", "def run(self):\n numOfWins = 0;\n for i in range(self.numOfGames):\n gameState = GameState()\n agentIndex = 0 # 0 for First Player (AI), 1 for Second Player (Human)\n while True:\n if agentIndex == 0: \n timed_func = util.TimeoutFunction(self.AIPlayer.getAction, int(self.maxTimeOut))\n try:\n start_time = time.time()\n action = timed_func(gameState, self.gameRules)\n except util.TimeoutFunctionException:\n print(\"ERROR: Player %d timed out on a single move, Max %d Seconds!\" % (agentIndex, self.maxTimeOut))\n return False\n\n if not self.muteOutput:\n print(\"Player 1 (AI): %s\" % action)\n else:\n action = self.HumanAgent.getAction(gameState, self.gameRules)\n if not self.muteOutput:\n print(\"Player 2 (Human): %s\" % action)\n gameState = gameState.generateSuccessor(action)\n if self.gameRules.isGameOver(gameState.boards):\n break\n if not self.muteOutput:\n gameState.printBoards(self.gameRules)\n\n agentIndex = (agentIndex + 1) % 2\n if agentIndex == 0:\n print(\"****player 2 wins game %d!!****\" % (i+1))\n else:\n numOfWins += 1\n print(\"****Player 1 wins game %d!!****\" % (i+1))\n\n print(\"\\n****Player 1 wins %d/%d games.**** \\n\" % (numOfWins, self.numOfGames))", "def run(self):\n numOfWins = 0;\n for i in range(self.numOfGames):\n gameState = GameState()\n agentIndex = 0 # 0 for First Player (AI), 1 for Second Player (Human)\n while True:\n if agentIndex == 0: \n timed_func = util.TimeoutFunction(self.AIPlayer.getAction, int(self.maxTimeOut))\n try:\n start_time = time.time()\n action = timed_func(gameState, self.gameRules)\n except util.TimeoutFunctionException:\n print(\"ERROR: Player %d timed out on a single move, Max %d Seconds!\" % (agentIndex, self.maxTimeOut))\n return False\n\n if not self.muteOutput:\n print(\"Player 1 (AI): %s\" % action)\n else:\n action = self.HumanAgent.getAction(gameState, self.gameRules)\n if not self.muteOutput:\n print(\"Player 2 (Human): %s\" % action)\n gameState = gameState.generateSuccessor(action)\n if self.gameRules.isGameOver(gameState.boards):\n break\n if not self.muteOutput:\n gameState.printBoards(self.gameRules)\n\n agentIndex = (agentIndex + 1) % 2\n if agentIndex == 0:\n pdb.set_trace()\n print(\"****player 2 wins game %d!!****\" % (i+1))\n else:\n numOfWins += 1\n print(\"****Player 1 wins game %d!!****\" % (i+1))\n\n print(\"\\n****Player 1 wins %d/%d games.**** \\n\" % (numOfWins, self.numOfGames))", "def tally_results(self, verbose=False):\n\t\tself.tally={\n\t\t\tself.player1.name: {\n\t\t\t\t'wins': 0,\n\t\t\t\t'draws': 0,\n\t\t\t\t'losses': 0\n\t\t\t},\n\t\t\tself.player2.name: {\n\t\t\t\t'wins': 0,\n\t\t\t\t'draws': 0,\n\t\t\t\t'losses': 0\n\t\t\t}\n\t\t}\n\t\tfor key, value in self.winner_dict.items():\n\t\t\tself.tally[self.player1.name]['wins']+=1 if value == self.player1.name else 0\n\t\t\tself.tally[self.player1.name]['draws']+=1 if value is None else 0\n\t\t\tself.tally[self.player1.name]['losses']+=1 if value == self.player2.name else 0\n\t\t\tself.tally[self.player2.name]['wins']+=1 if value == self.player2.name else 0\n\t\t\tself.tally[self.player2.name]['draws']+=1 if value is None else 0\n\t\t\tself.tally[self.player2.name]['losses']+=1 if value == self.player1.name else 0\n\t\tif verbose:\n\t\t\tprint('\\n--- FINAL RESULT ---\\n')\n\t\t\ttally_pretty=pd.DataFrame(self.tally).to_markdown()\n\t\t\tprint(tally_pretty)\n\t\t\tif self.tally[self.player1.name]['wins'] == self.tally[self.player2.name]['wins']:\n\t\t\t\tprint('\\nIt\\'s a draw!\\n')\n\t\t\telse:\n\t\t\t\twinner=self.player1.name if self.tally[self.player1.name]['wins'] > self.tally[self.player2.name]['wins'] else self.player2.name\n\t\t\t\tprint('\\n{player} wins the game!\\n'.format(player=winner))", "def run(self):\r\n noMove = 0\r\n while(noMove < 2):\r\n options = self.get_valid_moves()\r\n if len(options) > 0:\r\n res = False\r\n while(not res):\r\n move = self.players[self.turn-1].get_move(self.board.copy(),options.copy())\r\n res = self.update_board(move,_testing=False)\r\n else:\r\n noMove += 1\r\n self.turn = (self.turn * 2 ) % 3 # 1 --> 2 2 --> 1\r\n return self.gameCount()", "def play(self):\n utilities = {\n player: []\n for player\n in self.players\n }\n start_time = time.time()\n prev_print = 0\n for j in range(self.n_games):\n random.shuffle(self.players)\n initial_state = self.Game(\n self.players\n )\n contr = ahorn.Controller(\n initial_state\n )\n final_state = contr.play()\n for player in self.players:\n utilities[player].append(final_state.get_utility(player))\n\n elapsed = time.time()-start_time\n elapsed_since_print = time.time()-prev_print\n if self.verbose and ((elapsed_since_print > self.verbose_seconds) or j == self.n_games-1):\n prev_print = time.time()\n print(\"{}\".format(str(self.Game)))\n print(\n \"Game {} out of {} in {:2.1f}s ({:2.1f}s per game)\".format(\n j+1,\n self.n_games,\n elapsed,\n elapsed/(j+1)\n )\n )\n\n print(\"=\"*25)\n for player in sorted(self.players):\n low, mid, high = Arena.bootstrap(\n utilities[player],\n func=statistics.mean,\n confidence=self.confidence\n )\n print(\"{}\\t|\\t{:2.3f}/{:2.3f}/{:2.3f}\".format(\n str(player),\n low,\n mid,\n high\n ))\n print(\"\")\n result = {\n player: Arena.bootstrap(\n utility,\n func=statistics.mean,\n confidence=self.confidence\n )[1]\n for player, utility\n in utilities.items()\n }\n return result", "def test(self, num_test=1000):\n\n self.num_test = num_test\n self.player_wins = 0\n self.opponent_wins = 0\n self.optimal_wins = 0\n self.optimal_losses = 0\n\n self.game.restart()\n\n for test in range(num_test):\n self.game.deal_cards()\n possible_actions = self.game.get_actions()\n\n player_state = self.game.get_player_state()\n player_action = self.player.get_action(player_state,\n possible_actions,\n explore_exploit='exploit')\n opponent_state = self.game.get_opponent_state()\n opponent_action = self.opponent.get_action(opponent_state,\n possible_actions)\n\n (self.game.set_player_action(player_action)\n .set_opponent_action(opponent_action))\n player_score, opponent_score = self.game.get_scores()\n\n if player_score > opponent_score:\n self.player_wins += 1\n elif opponent_score > player_score:\n self.opponent_wins += 1\n\n optimal_result = self.game.get_optimal_result()\n if optimal_result > 0:\n self.optimal_wins += 1\n elif optimal_result < 0:\n self.optimal_losses += 1\n\n print(\"Testing done!\")", "def find_pcts(p1, p2, start_b = [], iter = 10000):\n win_record = []\n for i in range(iter):\n deck = Deck()\n need = 5 - len(start_b)\n b2 = draw_sure(deck, need, p1+p2+start_b)\n win_record.append(_who_wins(start_b + b2, p1, p2, printout = False))\n return [win_record.count(1) / float(len(win_record)), \n win_record.count(2) / float(len(win_record))\n ]", "def run_iteration(self):\n # Choose the player's starting hands and remove from deck.\n starting_hands_for_players = self.select_hands_for_players()\n self._reset_deck(starting_hands_for_players)\n\n # Finish the board\n iteration_board_cards = self.board_cards[:]\n while len(iteration_board_cards) < 5:\n iteration_board_cards.append(self.current_deck.pop())\n\n index_to_best_hands = self._get_best_hands_for_each_player(\n starting_hands_for_players, iteration_board_cards)\n winning_indices = self._get_winning_indices(index_to_best_hands)\n\n # Now update the statistics.\n for idx in winning_indices:\n self.win_stats[idx] += 1.0 / len(winning_indices)\n for idx, best_hand in index_to_best_hands.iteritems():\n if idx in winning_indices:\n if len(winning_indices) > 1:\n self.player_stats[idx].increment_rank(\n best_hand.hand_rank, TIE_RESULT)\n else:\n self.player_stats[idx].increment_rank(\n best_hand.hand_rank, WIN_RESULT)\n else:\n self.player_stats[idx].increment_rank(\n best_hand.hand_rank, LOSS_RESULT)", "def start_tournament(self):\n for i in range(0, len(self.agents)):\n for j in range(i+1, len(self.agents)):\n p1, p2 = self.agents[i], self.agents[j]\n p1_total_win = 0\n p2_total_win = 0\n for game_num in range(self.G):\n p1_wins, p2_wins, actions = self.play_game(p1, p2)\n p1_total_win += p1_wins\n p2_total_win += p2_wins\n print(p1.name + \": \" + str(p1_total_win) + \" wins, \" + p2.name + \": \" + str(p2_total_win) + \" wins\")\n if self.topp_visualization:\n p1_num = p1.filename.split(\"ep_\")[1].split(\".h5\")[0]\n p2_num = p2.filename.split(\"ep_\")[1].split(\".h5\")[0]\n os.chdir(ROOT_DIR)\n self.visualizer.visualize(actions, p1_num + \"_\" + p2_num)\n self.print_result()", "def playGames(self, num, verbose=False):\n\n num = int(num / 2)\n prevWon = 0\n newWon = 0\n draws = 0\n for _ in tqdm(range(num), desc=\"Arena.playGames (1)\"):\n gameResult = self.playGame(verbose=verbose)\n if gameResult == 1:\n prevWon += 1\n elif gameResult == -1:\n newWon += 1\n else:\n draws += 1\n\n self.landlord, self.farmers = self.farmers, self.landlord\n\n for _ in tqdm(range(num), desc=\"Arena.playGames (2)\"):\n gameResult = self.playGame(verbose=verbose)\n if gameResult == -1:\n prevWon += 1\n elif gameResult == 1:\n newWon += 1\n else:\n draws += 1\n\n return prevWon, newWon, draws", "def run_simulation(self, num_games=10):\n for _ in range(num_games):\n self.result.append(self.single_game())", "def play(self):\n print(\"Board size: {}x{} with {} games using pieces: {}\".format(self.size[0], self.size[1], self.num_games, self.pieces))\n print(\"Player 1 using layout '{}' and play strategy '{}'\".format(self.layouts[0], self.plays[0]))\n print(\"Player 2 using layout '{}' and play strategy '{}'\".format(self.layouts[1], self.plays[1]))\n print(\"Running...\")\n self.start_time = time.time()\n\n for game in range(self.num_games):\n if self.verbose: print(\"Playing game {}:\".format(game))\n players = (Player(\"Player 1\", self.size[0], self.size[1], self.pieces, self.layouts[0], self.plays[0], self.verbose),\n Player(\"Player 2\", self.size[0], self.size[1], self.pieces, self.layouts[1], self.plays[1], self.verbose))\n\n finished = False\n game_round = 0\n\n while not finished:\n game_round += 1\n for i in range(2):\n player = players[i]\n opponent = players[0] if i == 1 else players[1]\n\n attack_pos = player.get_next_attack()\n player.set_attack_result(attack_pos, *opponent.is_hit(attack_pos))\n\n if opponent.is_player_dead() is True:\n self.wins[i] += 1\n self.tries[i] += game_round\n finished = True\n if self.verbose: print(\"Player {} won the game on round {}\\n\".format(i+1, game_round))\n break", "def play_multiple_games(players, num_games=10, seed=2):\n total_games_winners = {}\n for player in players:\n if player.name not in total_games_winners:\n total_games_winners[player.name] = 0\n random.seed(seed)\n for game in range(num_games):\n print('-------- Game', game, '--------')\n random.shuffle(players)\n print('Initial game positions: ', players, '\\n')\n if all(x > 1 for x in [p.amount for p in players]):\n rotation_winners = play_multiple_rotations(players)\n for player_name in total_games_winners:\n total_games_winners[player_name] += rotation_winners[player_name]\n print()\n # print('Final Win Count: ', total_games_winners)\n print(players)", "def round_loop(list_of_players, score_chart):\n rounds = 0\n while True:\n rounds += 1\n initialize_round(list_of_players)\n inform_players(list_of_players)\n loop_until_thalom(list_of_players)\n give_round_scores(list_of_players)\n score_chart.update_scores(rounds, list_of_players)\n # score_chart.compute_totals_scores()\n if not continue_playing():\n break", "def run(self, count=1, trace=False):\n for _ in range(count):\n self.game.reset()\n self.game.play([self.player1, self.player2], trace=trace)\n self.winning_moves += self.game.encode_win()\n\n if not self.game.winner:\n self.record.draw += 1\n elif self.game.winner.marker == 'X':\n self.record.player1 += 1\n elif self.game.winner.marker == 'O':\n self.record.player2 += 1\n print(self.record)", "def play_simulation(self, n_iter=1000):\r\n final_wins = final_wins = {t: 0 for t in self.teams.dteams.keys()}\r\n season_teams_ranked, _ = get_playoffs(self.season_calendar, self.teams_info)\r\n for i in tqdm(range(n_iter)):\r\n if not self.playoffs_only:\r\n self.season.play_regular_season(self.teams)\r\n season_teams_ranked = self.season.playoffs_teams_ranked\r\n\r\n playoffs_sim = Playoffs(season_teams_ranked, self.gsim)\r\n winner_playoff = playoffs_sim.get_winner(self.teams)\r\n\r\n final_wins[winner_playoff] += 1\r\n\r\n return final_wins", "def run_game(self, p1, p2):\n could_win = [True, True] # can each player win?\n data = {k:[0.0] for k in self.col_names}\n for rnd in range(self.num_rounds):\n before = data.copy()\n p1_row = Game.timeout(p1.take_turn, (data, (self.vic_types[0], self.vic_cols[0])))\n if p1_row is None:\n return (1, \"Player 1 timed out\")\n elif isinstance(p1_row, Exception):\n return (1, p1_row)\n if data != before:\n return (1, \"Player 1 altered previous rows in data on their turn.\")\n\n before = data.copy()\n p2_row = Game.timeout(p2.take_turn, (data, (self.vic_types[1], self.vic_cols[1])))\n if p2_row is None:\n return (2, \"Player 2 timed out\")\n elif isinstance(p2_row, Exception):\n return (2, p2_row)\n if data != before:\n return (2, \"Player 2 altered previous rows in data on their turn.\")\n\n # append each row, looking for missing key or non-float value\n for p,row in [(0, p1_row), (1, p2_row)]:\n for k in data:\n if k not in row or not isinstance(row[k], float):\n could_win[p] = False\n return((p+1, \"Player {} returned a row that was not valid (bad key or not float value).\\n\".format(p+1)))\n elif row[k] > 1023 or row[k] < -1023:\n could_win[p] = False\n return((p+1, \"Player {} returned a row that had a number out of range.\\n\".format(p+1)))\n else:\n data[k].append(round(row[k],5))\n\n if all(could_win):\n wins = [self.check_condition(data, i) for i in range(2)]\n if all(wins) or not any(wins):\n winner = 0\n elif wins[0]:\n winner = 1\n else:\n winner = 2\n elif could_win[0]:\n winner = 1\n else:\n winner = 2\n\n return [data, \n (str(p1), self.vic_types[0], self.vic_cols[0]), \n (str(p2), self.vic_types[1], self.vic_cols[1]), \n winner,\n \"gg\"\n ]", "def test_after_jam_step_two(self):\n for test_suite_class in self.jam_step_2_test_suite_list:\n test_suite = test_suite_class(self)\n results = test_suite.run()\n self.test_results += results", "def play_game():\n board = create_board()\n while True:\n for player in [1, 2]:\n random_place(board, player)\n result = evaluate(board)\n if result != 0:\n return result", "def run_all_iterations(self):\n self.start_time = time.time()\n for _ in xrange(self.iterations):\n self.run_iteration()\n self.elapsed_time = time.time() - self.start_time\n\n self.print_statistics()", "def print_results(results, number_universe, flag_fair, players, neutral_player, max_turn):\n nb_games = len(results)\n\n # print parameters\n print(\"=== Parameters ===\")\n print(f\"Number of players : {len(players)}\")\n for p in players:\n print(f\" - player {p.name}\")\n print(f'Number of different universes : {number_universe}')\n print(f'Number of games played : {nb_games}')\n print(f'Number of games played per universe : {int(nb_games/number_universe)} ({\"\" if flag_fair else \"no \"}fair game : permutation players {\"\" if flag_fair else \"not \"}enabled)')\n print(f'Game unfinished if this number of turn is reached : {max_turn}')\n\n # preparation\n result_player = {} # {class Player:int, ..., None:int}\n list_turn = []\n nb_unfinished_games = 0\n for r in results.values():\n if r[\"winner\"] is not None: # the game has a winner\n list_turn.append(r[\"turn\"])\n else:\n nb_unfinished_games += 1\n nb = result_player.get(r[\"winner\"], 0)\n nb += 1\n result_player[r[\"winner\"]] = nb\n\n # print results\n print()\n print(\"=== Results ===\")\n if nb_unfinished_games == nb_games:\n print(\"All games are unfinished\")\n return\n print(\"End of games at turn (finished game only)\")\n print(f\" - mean : {round(mean(list_turn), 1)}\")\n print(f\" - median : {median(list_turn)}\")\n print(\"Percent of victory (number of victory)\")\n for p in players:\n nb_victory = result_player.get(p.number, 0)\n percent = round(nb_victory / nb_games * 100, 1)\n print(f\" - player {p.name} : {percent}% ({nb_victory})\")\n nb_victory = result_player.get(neutral_player.number, 0)\n percent = round(result_player.get(neutral_player.number, 0) / nb_games * 100, 1)\n print(f\"(- draw : {percent}% ({nb_victory}) )\")\n print(f\"(- unfinished : {round(nb_unfinished_games/nb_games*100, 1)}% ({nb_unfinished_games}) )\")\n return", "def display_stats(self):\n print(\"Simulation took: {:.2f} seconds to execute\".format(time.time() - self.start_time))\n for i, win in enumerate(self.wins):\n average = 0\n if win:\n average = float(self.tries[i]) / win\n print(\"Player {} wins: {} with (average number of rounds: {:.2f})\".format(i+1, win, average))", "def play_n_game(n_games, n_toss):\n results_list = []\n for _ in range(n_games):\n results_list.append(play_one_game(n_toss))\n dict_proba = {}\n for j in range (n_toss + 1):\n if results_list.count(j) != 0:\n dict_proba[j] = results_list.count(j)/n_games\n else:\n continue\n return dict_proba", "def eprank_iter(game_mat: np.ndarray, num_players:int, num_iters:int) -> Iterable:\n # number of games\n N = game_mat.shape[0]\n\n # prior skill variance (prior mean is always 0)\n pv = 0.5\n\n # Helper functions\n psi = lambda x: norm.pdf(x)/norm.cdf(x)\n lam = lambda x: psi(x) * (psi(x) + x)\n\n # intialize marginal means and precisions\n Ms = np.zeros(num_players)\n Ps = np.zeros(num_players)\n\n # initialize matrices of game to skill messages, means and precisions\n Mgs = np.zeros((N, 2))\n Pgs = np.zeros((N, 2))\n\n # initialize matrices of game to skill to game messages, means and precisions\n Msg = np.zeros((N, 2))\n Psg = np.zeros((N, 2))\n last_Ms, last_Ps = 0, 1\n\n for iter in range(num_iters):\n for p in range(num_players): # compute marginal player skills\n games_won = np.where(game_mat[:, 0] == p)[0]\n games_lost = np.where(game_mat[:, 1] == p)[0]\n Ps[p] = 1./pv + np.sum(Pgs[games_won, 0]) + np.sum(Pgs[games_lost, 1])\n Ms[p] = np.sum(Pgs[games_won, 0] * Mgs[games_won, 0]) / Ps[p] \\\n + np.sum(Pgs[games_lost, 1] * Mgs[games_lost, 1]) / Ps[p]\n\n # (2) compute skill to game messages\n Psg = Ps[game_mat] - Pgs\n Msg = (Ps[game_mat] * Ms[game_mat] - Pgs * Mgs) / Psg\n\n # (3) compute game to performance messages\n vgt = 1 + np.sum(1. / Psg, axis=1)\n mgt = Msg[:, 0] - Msg[:, 1]\n\n # (4) approximate the marginal on performance differences\n Mt = mgt + np.sqrt(vgt) * psi(mgt / np.sqrt(vgt))\n Pt = 1. / (vgt * (1 - lam(mgt / np.sqrt(vgt))))\n\n # (5) compute performance to game messages\n ptg = Pt - 1. / vgt\n mtg = (Mt * Pt - mgt / vgt) / ptg\n\n # (6) compute game to skills messages\n Pgs = 1. / (1 + 1. / ptg[:, None] + 1. / np.flip(Psg, axis=1))\n Mgs = np.stack([mtg, -mtg], axis=1) + np.flip(Msg, axis=1)\n\n yield np.copy(Ms), np.copy(Ps)", "def calculateWinRate():\n times = 10\n winRate = 0.0\n for i in range(times):\n game = Game('user', 6, 6)\n winRate += game.play(5, False, True, False, False)\n winRate = winRate/times\n print \"Winrate:\", winRate", "def test_multiple_players_return_own_results(self):\r\n observed = highscore.highscore(self.fixture_player1, self.fixture_score_high1)\r\n self.assertAlmostEquals(observed, self.fixture_score_high1)\r\n observed = highscore.highscore(self.fixture_player2, self.fixture_score_high2)\r\n self.assertAlmostEquals(observed, self.fixture_score_high2)" ]
[ "0.6592306", "0.637418", "0.6361511", "0.62523794", "0.6164459", "0.6154878", "0.6153801", "0.61084986", "0.6085923", "0.60651904", "0.6061598", "0.6013569", "0.59991294", "0.59905803", "0.59622914", "0.59505624", "0.59090394", "0.58888763", "0.5882414", "0.5851301", "0.5847728", "0.5842703", "0.5832395", "0.58255875", "0.5816176", "0.5815027", "0.5797244", "0.5755897", "0.5744541", "0.57401466" ]
0.684276
0
loads and merges annotation dicts for data_dir
def get_annotations(data_dirs): anno_filename = glob.glob('{}/*.json'.format(data_dirs[0]))[0] with open(anno_filename, 'r') as anno_file: annotations = json.load(anno_file) for data_dir in data_dirs[1:]: anno_filename = glob.glob('{}/*.json'.format(data_dir))[0] with open(anno_filename, 'r') as anno_file: annotations.update(json.load(anno_file)) return annotations
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_annotations(data_folder):\n annotations_files = os.listdir('data_annotations')\n\n annotations = {}\n for file_name in annotations_files:\n annotation = json.load(\n open(f'{data_folder}/annotations/{file_name}', 'r')\n )\n key = int(annotation['entity_id'])\n annotations[key] = annotation['value']['value']\n\n return annotations", "def _get_annotations(self) -> List[Dict[int, Dict[str, Any]]]:\n annotations = []\n for item in self.collector:\n data_file_type = os.path.basename(item).split(\".\")[-1]\n annotations.append(\n load_annotation_file(\n os.path.join(\n self.annotation_folder,\n os.path.basename(item).replace(data_file_type, \"json\"),\n )\n )\n )\n\n return annotations", "def _load_annotations(self):\n if self._raw_annotations is not None:\n return self._raw_annotations\n\n dataset_file = os.path.join(self._annotation_path, 'complete_dataset_v{}.pkl'.format(self._version))\n idx_file = os.path.join(self._annotation_path, 'splits_indices_v{}.pkl'.format(self._version))\n\n def get_split_from_ds(ds, idx):\n split = {}\n keys = sorted(ds.keys())\n for j in xrange(len(idx)):\n k = keys[idx[j]]\n split[k] = ds[k]\n return split\n\n with open(idx_file, 'rb') as fid:\n indices = cPickle.load(fid)[self._image_set]\n with open(dataset_file, 'rb') as fid:\n ds = cPickle.load(fid)\n self._raw_annotations = get_split_from_ds(ds, indices)\n\n return self._raw_annotations", "def load_annotations(self):\n # get keys\n with open(self.ann_file, 'r') as fin:\n keys = [line.strip().split(' ')[0] for line in fin]\n # get frame index list for LQ frames\n frame_index_list = []\n for i in range(self.num_input_frames):\n # Each clip of Vimeo90K has 7 frames starting from 1. So we use 9\n # for generating frame_index_list:\n # N | frame_index_list\n # 1 | 4\n # 3 | 3,4,5\n # 5 | 2,3,4,5,6\n # 7 | 1,2,3,4,5,6,7\n frame_index_list.append(i + (9 - self.num_input_frames) // 2)\n\n data_infos = []\n for key in keys:\n folder, subfolder = key.split('/')\n lq_paths = []\n for i in frame_index_list:\n lq_paths.append(\n osp.join(self.lq_folder, folder, subfolder, f'im{i}.png'))\n gt_paths = [osp.join(self.gt_folder, folder, subfolder, 'im4.png')]\n\n data_infos.append(\n dict(lq_path=lq_paths, gt_path=gt_paths, key=key))\n\n return data_infos", "def updateAnnotations(self):\n self.backupDatafiles()\n print(\"Updating annotation files \", self.field(\"trainDir\"))\n listOfDataFiles = QDir(self.field(\"trainDir\")).entryList(['*.data'])\n for file in listOfDataFiles:\n # Read the annotation\n segments = Segment.SegmentList()\n newsegments = Segment.SegmentList()\n segments.parseJSON(os.path.join(self.field(\"trainDir\"), file))\n allSpSegs = np.arange(len(segments)).tolist()\n newsegments.metadata = segments.metadata\n for segix in allSpSegs:\n seg = segments[segix]\n if self.field(\"species\") not in [fil[\"species\"] for fil in seg[4]]:\n newsegments.addSegment(seg) # leave non-target segments unchanged\n else:\n for seg2 in self.segments:\n if seg2[1] == seg:\n # find the index of target sp and update call type\n seg[4][[fil[\"species\"] for fil in seg[4]].index(self.field(\"species\"))][\"calltype\"] = self.clusters[seg2[-1]]\n newsegments.addSegment(seg)\n newsegments.saveJSON(os.path.join(self.field(\"trainDir\"), file))", "def load_data(self, annotation_json, images_dir):\r\n # Load json from file\r\n json_file = open(annotation_json)\r\n coco_json = json.load(json_file)\r\n json_file.close()\r\n \r\n # Add the class names using the base method from utils.Dataset\r\n source_name = \"coco_like\"\r\n ids={}\r\n i=0\r\n for category in coco_json['categories']:\r\n i+=1\r\n class_id = category['id']\r\n ids[class_id]=i\r\n class_name = category['name']\r\n if class_id < 1:\r\n print('Error: Class id for \"{}\" cannot be less than one. (0 is reserved for the background)'.format(class_name))\r\n return\r\n \r\n self.add_class(source_name, class_id, class_name)\r\n for annotation in coco_json['annotations']:\r\n annotation[\"category_id\"]=ids[annotation[\"category_id\"]]\r\n \r\n # Get all annotations\r\n \r\n annotations = {}\r\n for annotation in coco_json['annotations']:\r\n image_id = annotation['image_id']\r\n if image_id not in annotations:\r\n annotations[image_id] = []\r\n annotations[image_id].append(annotation)\r\n \r\n # Get all images and add them to the dataset\r\n seen_images = {}\r\n for image in coco_json['images']:\r\n image_id = image['id']\r\n if image_id in seen_images:\r\n print(\"Warning: Skipping duplicate image id: {}\".format(image))\r\n else:\r\n seen_images[image_id] = image\r\n try:\r\n image_file_name = image['file_name']\r\n image_width = image['width']\r\n image_height = image['height']\r\n except KeyError as key:\r\n print(\"Warning: Skipping image (id: {}) with missing key: {}\".format(image_id, key))\r\n \r\n image_path = os.path.abspath(os.path.join(images_dir, image_file_name))\r\n image_annotations = annotations[image_id]\r\n \r\n # Add the image using the base method from utils.Dataset\r\n self.add_image(\r\n source=source_name,\r\n image_id=image_id,\r\n path=image_path,\r\n width=image_width,\r\n height=image_height,\r\n annotations=image_annotations\r\n )", "def _load_annotations(self):\n annotation_file = self._filepath(self.ANNOTATION_FILE)\n with open(annotation_file) as f:\n json_data = json.load(f)\n\n return json_data", "def _read_annotations(self) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray]:\n print('Loading annotations...')\n \n if self.caching:\n # Get last modified timestamp of the cache path\n cache_path = pathlib.Path(self.cache_path)\n cache_timestamp = cache_path.stat().st_mtime\n\n is_empty = not any(cache_path.iterdir())\n\n data_path = pathlib.Path(os.path.join(self.dataset_dir, self.dataset_name + '_unroll.json'))\n data_timestamp = data_path.stat().st_mtime\n\n # If the data is newer than the cached data, we have to update it. Else we take the cached data\n if is_empty or (data_timestamp > cache_timestamp):\n with open(os.path.join(self.dataset_dir, self.dataset_name + '_unroll.json')) as f:\n # Read file by line: persons, objects, actions\n for i, json_obj in enumerate(f):\n json_data = json.loads(json_obj)\n\n # Process and separate data into persons, objects and activities\n if i == 0:\n persons, person_ids = self._process_persons(json_data['persons'])\n elif i == 1:\n objects, object_ids = self._process_objects(json_data['objects'])\n elif i == 2:\n activities, activity_names = self._process_activities(json_data['actions'])\n else:\n print('Incorrect format in annotation file')\n exit()\n \n # Update cached files\n np.save(os.path.join(cache_path, 'persons.npy'), persons)\n np.save(os.path.join(cache_path, 'person_ids.npy'), person_ids)\n np.save(os.path.join(cache_path, 'objects.npy'), objects)\n np.save(os.path.join(cache_path, 'object_ids.npy'), object_ids)\n np.save(os.path.join(cache_path, 'activities.npy'), activities)\n np.save(os.path.join(cache_path, 'activity_names.npy'), activity_names)\n else:\n persons = np.load(os.path.join(cache_path, 'persons.npy'), allow_pickle=True)\n person_ids = np.load(os.path.join(cache_path, 'person_ids.npy'), allow_pickle=True)\n objects = np.load(os.path.join(cache_path, 'objects.npy'), allow_pickle=True)\n object_ids = np.load(os.path.join(cache_path, 'object_ids.npy'), allow_pickle=True)\n activities = np.load(os.path.join(cache_path, 'activities.npy'), allow_pickle=True)\n activity_names = np.load(os.path.join(cache_path, 'activity_names.npy'), allow_pickle=True)\n else:\n with open(os.path.join(self.dataset_dir, self.dataset_name + '_unroll.json')) as f:\n # Read file by line: persons, objects, actions\n for i, json_obj in enumerate(f):\n json_data = json.loads(json_obj)\n\n # Process and separate data into persons, objects and activities\n if i == 0:\n persons, person_ids = self._process_persons(json_data['persons'])\n elif i == 1:\n objects, object_ids = self._process_objects(json_data['objects'])\n elif i == 2:\n activities, activity_names = self._process_activities(json_data['actions'])\n else:\n print('Incorrect format in annotation file')\n exit()\n\n return persons, objects, activities, person_ids, object_ids, activity_names", "def annotate_articles(data_folder):\n articles_files = os.listdir('data')\n annotations = get_annotations()\n \n all_articles = {}\n for index, file_name in enumerate(articles_files):\n article = json.load(open(f'{data_folder}/articles/{file_name}', 'r'))\n print(f'{index} - {article[\"source\"][\"id\"]}')\n article['label'] = annotations.get(article['source']['id'], None)\n all_articles[article['id']] = filter_data(article)\n\n with open(f'{data_folder}/dataset.json', 'w') as f:\n json.dump(all_articles, f)", "def load_annotations(self):\n assert self.ann_file.endswith('.pkl')\n ann_info = hload_pkl(self.ann_file)\n\n video_infos = []\n for i, video_info in enumerate(ann_info):\n frame_dir = video_info['filename']\n video_info['filename'] = osp.join(self.data_prefix, video_info['filename'])\n video_info['frame_dir'] = frame_dir\n video_info['index'] = i\n \n video_info['text'] = [video_info['text']] \n video_infos.append(video_info) \n del ann_info\n\n return video_infos", "def load_datasets(data_dir: str) -> Tuple[List[Annotation], List[Annotation], List[Annotation]]:\n train_data = annotations_from_jsonl(os.path.join(data_dir, 'train.jsonl'))\n val_data = annotations_from_jsonl(os.path.join(data_dir, 'val.jsonl'))\n test_data = annotations_from_jsonl(os.path.join(data_dir, 'test.jsonl'))\n return train_data, val_data, test_data", "def load_dataset(self, dataset_dir, json_path):\n # Add classes. We have only one class to add.\n self.add_class(\"glomerulus\", 1, \"glomerulus\")\n\n \n\n # Load annotations\n # VGG Image Annotator saves each image in the form:\n # { 'filename': '28503151_5b5b7ec140_b.jpg',\n # 'regions': {\n # '0': {\n # 'region_attributes': {},\n # 'shape_attributes': {\n # 'all_points_x': [...],\n # 'all_points_y': [...],\n # 'name': 'polygon'}},\n # ... more regions ...\n # },\n # 'size': 100202\n # }\n # We mostly care about the x and y coordinates of each region\n json_path=\"../../data/hubmap/train/aaa6a05cc.json\"", "def load_annos(self):\n data = None\n with open(self.anno_path, 'r') as file:\n if self.ext == '.json':\n data = json.load(file)\n\n # Label start at index 0\n if data is not None:\n for anno in data['annotations']:\n anno['category_id'] -= 1\n\n for anno in data['categories']:\n anno['id'] -= 1\n\n return data", "def _load_data(self, cfg):\r\n\r\n if self._split == \"train\":\r\n self._annotations = self._load_lists(cfg.EGO4D_STA.TRAIN_LISTS)\r\n elif self._split == \"val\":\r\n self._annotations = self._load_lists(cfg.EGO4D_STA.VAL_LISTS)\r\n else:\r\n self._annotations = self._load_lists(cfg.EGO4D_STA.TEST_LISTS)", "def ingest_annotations(directory, annotation_type):\n in_golden = annotation_type == \"manual\"\n doc_type = None\n issue_number = None\n bid = None\n annotated_pages = []\n file_prefix = \"page\"\n try:\n bid = directory.split('/')[len(directory.split('/'))-1:][0]\n record = Metadata.objects(bid=bid).first()\n assert record is not None\n except Exception as e:\n bid,issue_number = directory.split('/')[len(directory.split('/'))-2:]\n record = Metadata.objects(bid=bid).first()\n try:\n doc_type = record[\"type_document\"]\n except Exception as e:\n doc_type = None\n logger.warning('The record for %s is not in MongoDB'%bid)\n try:\n page_numbers = {int(os.path.basename(fname).replace(\"page-\",\"\").split('.')[0]):os.path.basename(fname).split('.')[0] \n for fname in glob.glob(\"%s/*.ann\"%directory)}\n except Exception as e:\n page_numbers = {int(os.path.basename(fname).replace(\"image-\",\"\").split('.')[0]):os.path.basename(fname).split('.')[0] \n for fname in glob.glob(\"%s/*.ann\"%directory)}\n file_prefix = \"image\"\n # TODO: handle the exception of document not in the DB\n logger.info(\"Ingesting the annotations from directory \\\"%s\\\"\"%directory)\n if(issue_number != None):\n logger.info(\"Found document %s-%s [type=%s]\"%(bid,issue_number,doc_type))\n else:\n logger.info(\"Found document %s [type=%s]\"%(bid,doc_type))\n try:\n if(doc_type==\"journal\"):\n doc = LBDocument.objects(internal_id=\"%s-%s\"%(bid,issue_number)).first()\n if doc is None:\n doc = LBDocument.objects(internal_id=\"%s-%s\"%(bid, convert_issue_number(issue_number))).first()\n elif(doc_type==\"monograph\"):\n doc = LBDocument.objects(bid=bid).first()\n logger.info(\"%s has %i pages\"%(doc.internal_id, len(doc.pages)))\n for page_n in sorted(page_numbers):\n logger.debug(\"Reading in annotations for page %i from file %s/ %s\"%(page_n,directory,page_numbers[page_n]))\n entities_with_continuations = {}\n entities,relations = read_ann_file(page_numbers[page_n],directory)\n fulltext = codecs.open(\"%s/%s.txt\"%(directory,page_number2image_name(page_n, string=file_prefix)),'r', 'utf-8').read()\n line_breaks = find_newlines(fulltext)\n #logger.info(\"Found %i entities, %i relation in %s\"%(len(entities), len(relations), directory))\n doc_id = \"%s-%s-%s\"%(bid, issue_number, page_numbers[page_n])\n try:\n page = next((page for page in doc.pages if page.single_page_file_number==page_n))\n if(page[\"in_golden\"]==True):\n annotated_pages.append(page.id)\n logger.info(\"found %i entities in %s (p. %i)\"%(len(entities),doc_id,page_n))\n logger.info(\"found %i relations in %s (p. %i)\"%(len(relations.keys()),doc_id,page_n))\n \"\"\"\n Parse the `ContainedIN` relations and identify annotations that should be merged together.\n IDs of candidates for merging are stored in a dict(), e.g. {\"T1\":[\"T2\",\"T4\"]}\n \"\"\"\n entities_with_continuations = {}\n if len(relations.keys())>0:\n for relation_key in relations:\n args = relations[relation_key][\"arguments\"]\n if args[0] in entities_with_continuations:\n entities_with_continuations[args[0]].append(args[1])\n else:\n entities_with_continuations[args[0]] = [args[1]]\n logger.debug(\"(%s-%s) entities to be merged: %s\"%(doc_id,page_n,entities_with_continuations))\n \"\"\"\n Create the annotations (`entities` dict). \n Later they will be stored into the MongoDB\n \"\"\"\n for entity in entities:\n entities[entity][\"ingestion_timestamp\"] = datetime.utcnow()\n entities[entity][\"annotation_ingester_version\"] = __version__\n entities[entity][\"entity_type\"] = entities[entity][\"entity_type\"].lower( )\n entities[entity][\"filename\"] = \"%s/%s%s\"%(directory,page_numbers[page_n],\".ann\")\n if(doc_type==\"journal\"):\n entities[entity][\"bid\"] = bid\n entities[entity][\"pageid\"] = doc_id\n elif(doc_type==\"monograph\"):\n entities[entity][\"bid\"] = bid\n entities[entity][\"pageid\"] = \"%s-%s\"%(bid,page_numbers[page_n])\n entities[entity][\"container\"] = entities[entity][\"entity_type\"] in container_annotations\n # ref to page_id (from content_loader) ✓\n for position in entities[entity][\"positions\"]:\n line_number = find_linenumber_for_string(position[\"start\"],position[\"end\"], line_breaks)\n logger.debug(\"%s is found at line %s\"%(entity,line_number))\n position[\"line_n\"] = line_number\n position[\"page_id\"] = page.id\n positions_by_offset = sorted(entities[entity][\"positions\"]\n ,key=lambda position: position['start'])\n entities[entity][\"positions\"] = sorted(positions_by_offset\n , key=lambda position: Page.objects(id=position['page_id']).first().single_page_file_number)\n logger.debug(\"Annotations %s %s\"%(entity,entities[entity]))\n \"\"\"\n Now take the candidates for merging identified above and populate the annotations.\n Still nothing is saved into MongoDB at this stage.\n \"\"\"\n for ann_id in entities_with_continuations:\n try:\n logger.debug(\"Starting to merge SP and SF entities into meta-annotations (%s-%s)\"%(doc_id, page_n))\n logger.debug(\"%s will be merged with %s\"%(ann_id,\"+\".join(entities_with_continuations[ann_id])))\n top_entity_types = \"_\".join([entities[ann_id][\"entity_type\"]]+[entities[annid][\"entity_type\"] \n for annid in entities_with_continuations[ann_id]])\n logger.debug(\"%s\"%top_entity_types)\n new_entity = copy.deepcopy(entities)[ann_id] \n #container = True \n new_entity[\"ann_id\"] = \"%s+%s\"%(ann_id,\"+\".join(entities_with_continuations[ann_id]))\n new_entity[\"entity_type\"] = \"meta-annotation\"\n new_entity[\"top_entity_types\"] = top_entity_types\n new_entity[\"top_entities_ids\"] = [ann_id]\n new_entity[\"top_entities_ids\"] += [id for id in entities_with_continuations[ann_id]]\n fname = new_entity[\"filename\"]\n new_entity[\"filename\"] = [fname]\n for to_merge_id in entities_with_continuations[ann_id]:\n to_merge = dict(entities)[to_merge_id]\n new_entity[\"filename\"]+= [to_merge[\"filename\"]]\n new_entity[\"positions\"] = new_entity[\"positions\"] + to_merge[\"positions\"]\n positions_by_offset = sorted(new_entity[\"positions\"]\n ,key=lambda position: position['start'])\n new_entity[\"positions\"] = sorted(positions_by_offset\n ,key=lambda position: Page.objects(id=position['page_id']).first().single_page_file_number)\n new_entity[\"filename\"] = \", \".join(list(set(new_entity[\"filename\"])))\n surface_start = new_entity[\"positions\"][0][\"start\"]\n surface_end = new_entity[\"positions\"][-1][\"end\"]\n new_entity[\"surface\"] = fulltext[surface_start:surface_end]\n entities[new_entity[\"ann_id\"]] = new_entity\n logger.debug(new_entity)\n except Exception as e:\n logger.error(\"The merging of %s in (%s-%s) failed with error\\\"%s\\\"\"%(new_entity[\"ann_id\"],bid,page_n,e))\n \"\"\"\n Now all annotations will be stored into the MongoDB. \n And some specific fields (e.g. `top_entities`) are sorted, and annotations updated \n accordingly in the DB. \n \"\"\"\n try:\n annotations = []\n for entity in entities.values():\n annotation = Annotation(**entity)\n annotation.positions = [PagePosition(**position) for position in entity[\"positions\"]]\n annotation.save()\n annotations.append(annotation)\n page.annotations_ids = [] #TODO\n page.annotations_ids = annotations\n page.is_annotated = True\n page.save()\n logger.debug(\"Following annotations were inserted into MongoDB: %s\"%([annotation.id for annotation in annotations]))\n logger.info(\"%i annotations were inserted into MongoDB\"%len(annotations))\n except Exception as e:\n raise e\n containers = [annotation for annotation in annotations if annotation[\"container\"]] \n contained = [annotation for annotation in annotations if not annotation[\"container\"]]\n meta_annotations = [annotation for annotation in annotations if annotation[\"entity_type\"]==\"meta-annotation\"]\n logger.debug(\"meta annotations: %s\"%meta_annotations)\n \"\"\"\n Resolve the top entities in the meta-annotations: replace entity IDs with \n a reference to the annotation in the MongoDB.\n \"\"\"\n for annotation in meta_annotations:\n top_entities_ids = annotation[\"top_entities_ids\"]\n logger.debug('resolving top_entities')\n top_entities = [Annotation.objects(ann_id=ann_id, pageid=annotation.pageid).first() for ann_id in top_entities_ids]\n #top_entities = list([db_conn.annotations.find_one({\"ann_id\":ann_id,\"pageid\":annotation[\"pageid\"]}) for ann_id in top_entities_ids])\n logger.debug(\"Top entities before sorting %s\"%[ann.id for ann in top_entities])\n annotation[\"top_entities\"] = sort_annotations_by_offset(top_entities)\n logger.debug(\"Top entities after sorting %s\"%[ann.id for ann in top_entities])\n annotation[\"top_entities\"] = top_entities\n annotation.save()\n logger.debug(\"Updating meta-annotation: %s\"%annotation.id)\n \"\"\"\n Transform contains relations between entities into references between annotations \n in the MongoDB.\n \"\"\"\n for annotation in sort_annotations_by_offset(containers):\n if(len(annotation[\"positions\"]) > 1):\n start = annotation[\"positions\"][0][\"start\"]\n end = annotation[\"positions\"][len(annotation[\"positions\"])-1][\"end\"]\n else:\n start = annotation[\"positions\"][0][\"start\"]\n end = annotation[\"positions\"][0][\"end\"]\n annotation[\"contains\"] = []\n for contained_annotation in sort_annotations_by_offset(contained):\n if(len(contained_annotation[\"positions\"])>1):\n if(contained_annotation[\"positions\"][0][\"start\"] >= start\n and contained_annotation[\"positions\"][len(contained_annotation[\"positions\"])-1][\"end\"] <= end):\n annotation[\"contains\"].append(contained_annotation)\n logger.debug(\"[%s] Annotation %s (%s) contains %s (%s)\"%(\n doc_id\n ,annotation[\"ann_id\"]\n ,annotation[\"id\"]\n ,contained_annotation[\"ann_id\"]\n ,contained_annotation[\"id\"]))\n annotation.save()\n else:\n if(contained_annotation[\"positions\"][0][\"start\"] >= start\n and contained_annotation[\"positions\"][0][\"end\"] <= end):\n annotation[\"contains\"].append(contained_annotation)\n logger.debug(\"[%s] Annotation %s (%s) contains %s (%s)\"%(\n doc_id\n ,annotation[\"ann_id\"]\n ,annotation[\"id\"]\n ,contained_annotation[\"ann_id\"]\n ,contained_annotation[\"id\"]))\n annotation.save()\n else:\n page.is_annotated = False\n logger.info(\"%s was ignored because it's not in the golden set\"%doc_id)\n except StopIteration as e:\n logger.error(\"The annotations for %s-%s p. %i can't be ingested\"%(bid, issue_number, page_n))\n except Exception as e:\n logger.error(\"The annotations for %s-%s can't be ingested. Got error %s\"%(bid, issue_number, e))\n return annotated_pages", "def getAnnotationData(annotatedFolderPathList):\n enList, frList, refList, annotList = [], [], [], []\n # be sure the format is right\n if type(annotatedFolderPathList) is str:\n annotatedFolderPathList = [annotatedFolderPathList]\n # get the lists of annotations and sentences\n for path in annotatedFolderPathList:\n sentEnPath = u'{0}sample.en'.format(path)\n sentFrPath = u'{0}sample.fr'.format(path)\n sentAnnotPath = u'{0}sampleAnnotation.tsv'.format(path)\n sentRefPath = u'{0}sampleReference.tsv'.format(path)\n enList, frList, refList, annotList = extractLineData(sentEnPath, sentFrPath, sentRefPath, sentAnnotPath,\n enList, frList, refList, annotList)\n return enList, frList, refList, annotList", "def __init__(self, cfg, data_dir, train_files):\n self.cfg = cfg\n self.imgs, self.ids, self.anns = None, None, None\n self.data_dir = data_dir\n self.product_labels = {}\n print('loading annotations into memory...')\n tic = time.time()\n self.datasets = []\n if type(train_files) != list:\n train_files = [train_files]\n for train_file in train_files:\n labels_file = os.path.dirname(train_file)\n labels_file = os.path.join(labels_file, 'labels.txt')\n with open(labels_file, 'r') as f:\n self.product_names = {}\n for line in f:\n label, prod_name = line.split()\n self.product_labels[prod_name] = int(label)\n with open(train_file, 'r') as f:\n dataset = {}\n train_file_dir = os.path.dirname(train_file)\n for line in f:\n img, ann_file = line.split()\n img = os.path.join(train_file_dir, 'images',\n os.path.basename(img))\n ann_file = os.path.join(train_file_dir, 'annotations',\n os.path.basename(ann_file))\n dataset[img] = ann_file\n self.datasets.append(dataset)\n print('Done (t={:0.2f}s)'.format(time.time() - tic))\n self.create_index()", "def load_annotations(self):\n assert self.ann_file.endswith('.pkl')\n ann_info = hload_pkl(self.ann_file)\n\n video_infos = []\n for i, video_info in enumerate(ann_info):\n filename = osp.join(self.data_prefix, video_info['filename']) \n video_info['filename'] = filename\n frame_dir = video_info['filename']\n video_info['frame_dir'] = frame_dir \n video_info['index'] = i\n video_info['label'] = -1 \n video_info['text'] = [video_info['text']] \n video_infos.append(video_info) \n del ann_info\n return video_infos", "def load_annotations(self):\n assert self.ann_file.endswith('.pkl')\n ann_info = hload_pkl(self.ann_file)\n\n video_infos = []\n for i, video_info in enumerate(ann_info):\n filename = osp.join(self.data_prefix, video_info['filename']) \n video_info['filename'] = filename\n frame_dir = video_info['filename']\n video_info['frame_dir'] = frame_dir \n video_info['index'] = i\n video_info['label'] = -1 \n video_info['text'] = [video_info['text']] \n video_infos.append(video_info) \n del ann_info\n return video_infos", "def load_metadata(self, path):\n self.paths = []\n self.annotations = []\n\n with open(path, \"r\") as f:\n for line in f:\n line = line.strip().split(\" \")\n \n rgb_path = line[0]\n\n if len(line) > 1:\n bounding_boxes = np.array([list(map(int, box.split(','))) for box in line[1:]])\n else:\n bounding_boxes = []\n \n self.annotations.append({\n \"rgb_path\": rgb_path, \n \"bounding_boxes\": bounding_boxes,\n })", "def _load_nimble_annotation(self, index):\n filename = os.path.join(self._data_path, 'Annotations_Python', index + '.json')\n #currently only one bbox is considered.\n assert os.path.exists(cache_file),'Annotation {} has to be here'.format(filename)\n \n num_objs = 1\n boxes = np.zeros((num_objs, 4), dtype=np.uint16)\n gt_classes = np.zeros((num_objs), dtype=np.int32)\n overlaps = np.zeros((num_objs, self.num_classes), dtype=np.float32)\n # \"Seg\" area for pascal is just the box area\n seg_areas = np.zeros((num_objs), dtype=np.float32)\n\n f = open(filename,'r')\n\n # Load object bounding boxes into a data frame.\n for ix, obj in enumerate(objs):\n cls = 1 \n gtboxes_1[ix, :] = obj.bbox\n gtboxes_2[ix,:] = obj.gtbbox\n gt_classes_1[ix] = cls\n overlaps_1[ix, cls] = 1.0\n seg_areas_1[ix] = 0\n gt_classes_1[ix] = cls\n overlaps_1[ix, cls] = 1.0\n seg_areas_1[ix] = 0\n\n overlaps = scipy.sparse.csr_matrix(overlaps)\n\n return {'donor_file' : donor_file,\n 'boxes_1' : gtboxes_1,\n 'boxes_2' : gtboxes_2,\n 'gt_classes_1': gt_classes_1,\n 'gt_overlaps_1' : overlaps_1,\n 'gt_classes_2': gt_classes_2,\n 'gt_overlaps_2' : overlaps_2,\n 'flipped' : False,\n 'seg_areas_1' : seg_areas_1,\n 'seg_areas_2' : seg_areas_2}", "def load_coco_ann_files(self):\n if self.type == 'train':\n datasets = [\n (os.path.join(self.dataset_root, 'coco', 'train2014'),\n COCO(os.path.join(self.dataset_root, 'coco',\n 'annotations_trainval2014', 'person_keypoints_train2014.json'))),\n (os.path.join(self.dataset_root, 'coco', 'train2017'),\n COCO(os.path.join(self.dataset_root, 'coco',\n 'annotations_trainval2017', 'person_keypoints_train2017.json'))),\n # (os.path.join(self.dataset_root, 'mpii', 'images'),\n # COCO(os.path.join(self.dataset_root, 'mpii',\n # 'annotations', 'train.json')))\n ]\n else:\n datasets = [\n (os.path.join(self.dataset_root, 'coco', 'val2014'),\n COCO(os.path.join(self.dataset_root, 'coco',\n 'annotations_trainval2014', 'person_keypoints_val2014.json'))),\n (os.path.join(self.dataset_root, 'coco', 'val2017'),\n COCO(os.path.join(self.dataset_root, 'coco',\n 'annotations_trainval2017', 'person_keypoints_val2017.json')))\n ]\n\n dict_list = []\n for dataset_path, dataset in datasets:\n img_ids = dataset.getImgIds()\n\n for idx in img_ids:\n try:\n img = dataset.loadImgs([idx])[0]\n ann_ids = dataset.getAnnIds([idx])\n anns = dataset.loadAnns(ann_ids)\n\n if [ann['keypoints'] for ann in anns] and not all([ann['keypoints'] == [0]*51 for ann in anns]):\n keypoints = [ann['keypoints'] for ann in anns if ann['keypoints'] != [0]*51]\n for i in range(len(keypoints)):\n if 'coco' in dataset_path:\n keypoints[i] = keypoints[i] + ([0, 0, 0] if not (keypoints[i][17] and keypoints[i][20])\n else [(keypoints[i][15] + keypoints[i][18]) // 2, (keypoints[i][16] + keypoints[i][19]) // 2, 1])\n else:\n keypoints[i] = keypoints[i] + ([0, 0, 0] if not (keypoints[i][41] and keypoints[i][38])\n else [(keypoints[i][39] + keypoints[i][36]) // 2, (keypoints[i][40] + keypoints[i][37]) // 2, 1])\n\n if len([kp for kp in keypoints if kp != [0]*54]) <= 4:\n dict_list.append({'path': os.path.join(dataset_path, img[\"file_name\"]),\n 'keypoints': [kp for kp in keypoints if kp != [0]*54]})\n except:\n print(f'Skipped: {idx}')\n\n final_dataset = pd.DataFrame.from_dict(dict_list)\n\n return final_dataset", "def get_data(input_path):\n all_imgs = []\n classes_count = {}\n class_mapping = {}\n\n # parsing Flag\n visualise = False\n\n # MSCOCO directory\n data_path = input_path\n\n print('Parsing annotation files')\n annot_path = os.path.join(data_path, 'annotations_bbox')\n imgs_path = os.path.join(data_path, 'images')\n\n # images directory (train, val, trainval, test)\n imgsets_path_trainval = os.path.join(data_path, 'images', 'trainval.txt')\n imgsets_path_train = os.path.join(data_path, 'images', 'train.txt')\n imgsets_path_val = os.path.join(data_path, 'images', 'val.txt')\n imgsets_path_test = os.path.join(data_path, 'images', 'test.txt')\n\n trainval_files = []\n train_files = []\n val_files = []\n test_files = []\n\n with open(imgsets_path_trainval) as f:\n for line in f:\n trainval_files.append(line.strip())\n\n with open(imgsets_path_train) as f:\n for line in f:\n train_files.append(line.strip())\n\n with open(imgsets_path_val) as f:\n for line in f:\n val_files.append(line.strip())\n\n # test-set (default) not included in MSCOCO\n if os.path.isfile(imgsets_path_test):\n with open(imgsets_path_test) as f:\n for line in f:\n test_files.append(line.strip())\n\n # annotation read\n annots_train = json.load(open(os.path.join(annot_path, 'bbox_train2017.json'), 'r'))\n annots_val = json.load(open(os.path.join(annot_path, 'bbox_val2017.json'), 'r'))\n annots = dict()\n annots['train'] = annots_train\n annots['val'] = annots_val\n\n for part in ['train', 'val']:\n annots_keys = tqdm(annots[part].keys())\n for img_name in annots_keys:\n annots_keys.set_description(\"Processing %s\" % img_name)\n for bbox in annots[part][img_name]:\n class_name = bbox['label'].replace(' ', '')\n all_imgs.append({\n \"filepath\": os.path.join(data_path, 'images', '%s2017' % part, \"%s.jpg\" % img_name),\n \"width\": None,\n \"height\": None,\n \"bboxes\": [{\n \"class\": class_name,\n \"x1\": bbox['bbox']['x1'],\n \"y1\": bbox['bbox']['x2'],\n \"x2\": bbox['bbox']['y1'],\n \"y2\": bbox['bbox']['y2'],\n \"difficult\": False\n }],\n \"image_id\": img_name,\n \"imageset\": part\n })\n if class_name not in classes_count:\n classes_count[class_name] = 1\n else:\n classes_count[class_name] += 1\n if class_name not in class_mapping:\n class_mapping[class_name] = len(class_mapping)\n\n # visualise bounding boxes\n if visualise:\n img = cv2.imread(annotation_data['filepath'])\n for bbox in annotation_data['bboxes']:\n cv2.rectangle(img, (bbox['x1'], bbox['y1']), (bbox['x2'], bbox['y2']), (0, 0, 255))\n cv2.imshow('img', img)\n print(annotation_data['imageset'])\n cv2.waitKey(0)\n\n return all_imgs, classes_count, class_mapping", "def load_annotations(self):\n assert self.ann_file.endswith('.pkl')\n ann_info = hload_pkl(self.ann_file)\n\n video_infos = []\n for i, video_info in enumerate(ann_info):\n info_dict = {} \n info_dict['filename'] = video_info['vid_name']\n frame_dir = info_dict['filename']\n info_dict['frame_dir'] = frame_dir\n info_dict['index'] = i\n info_dict['label'] = video_info['answer_idx']\n info_dict['answers'] = video_info['answers']\n info_dict['question'] = video_info['q']\n info_dict['subtitle'] = video_info['located_sub_text']\n info_dict['frame_ind'] = video_info['located_frame']\n info_dict['total_frames'] = video_info.get('total_frames', -1)\n video_infos.append(info_dict) \n del ann_info\n\n return video_infos", "def load_data(self, annotation_json, images_dir):\n # Load json from file\n json_file = open(annotation_json)\n car_door_json = json.load(json_file)\n json_file.close()\n \n # Add the class names using the base method from utils.Dataset\n source_name = \"car_parts\"\n for category in car_door_json['categories']:\n class_id = category['id']\n class_name = category['name']\n if class_id < 1:\n print('Error: Class id for \"{}\" cannot be less than one. (0 is reserved for the background)'.format(class_name))\n return\n \n self.add_class(source_name, class_id, class_name)\n \n # Get all annotations\n annotations = {}\n for annotation in car_door_json['annotations']:\n image_id = annotation['image_id']\n if image_id not in annotations:\n annotations[image_id] = []\n annotations[image_id].append(annotation)\n \n # Get all images and add them to the dataset\n seen_images = {}\n for image in car_door_json['images']:\n image_id = image['id']\n if image_id in seen_images:\n print(\"Warning: Skipping duplicate image id: {}\".format(image))\n else:\n seen_images[image_id] = image\n try:\n image_file_name = image['file_name']\n image_width = image['width']\n image_height = image['height']\n except KeyError as key:\n print(\"Warning: Skipping image (id: {}) with missing key: {}\".format(image_id, key))\n \n image_path = os.path.abspath(os.path.join(images_dir, image_file_name))\n image_annotations = annotations[image_id]\n \n # Add the image using the base method from utils.Dataset\n self.add_image(\n source=source_name,\n image_id=image_id,\n path=image_path,\n width=image_width,\n height=image_height,\n annotations=image_annotations\n )", "def merge_pred(ann_path, mode=\"val\", name=\"merged_annotations\"):\n files = os.listdir(ann_path)\n data_files = []\n for file_name in files:\n if \"json\" in file_name:\n data_files.append(os.path.join(ann_path, file_name))\n pred = {\"images\": [], \"annotations\": []}\n for file in data_files:\n anno = json.load(open(file, 'r'))\n if \"images\" in anno:\n for img in anno[\"images\"]:\n pred[\"images\"].append(img)\n if \"annotations\" in anno:\n for ann in anno[\"annotations\"]:\n pred[\"annotations\"].append(ann)\n json.dump(pred, open('{}/{}_{}.json'.format(ann_path, name, mode), 'w'))", "def _load_original_dataset(data_directory, setname):\n\n Sign = collections.namedtuple(\"Sign\", [\"visibility\", \"type\", \"name\"])\n data_directory = pathlib.Path(data_directory)\n filename = data_directory / setname / \"annotations.txt\"\n with tf.io.gfile.GFile(filename) as f:\n files, annotations = zip(*(l.strip().split(\":\", 1) for l in f))\n\n all_signs = []\n for annotation in annotations:\n signs = []\n for sign in annotation.split(\";\"):\n if sign == [\"\"] or not sign: continue\n parts = [s.strip() for s in sign.split(\",\")]\n if parts[0] == \"MISC_SIGNS\": continue\n signs.append(Sign(parts[0], parts[5], parts[6]))\n all_signs.append(signs)\n\n filepaths = (data_directory / setname / f for f in files)\n return zip(filepaths, all_signs)", "def load_annotations(self):\n assert self.ann_file.endswith('.pkl')\n ann_info = hload_pkl(self.ann_file)\n\n video_infos = []\n for i, video_info in enumerate(ann_info):\n info_dict = {} \n info_dict['filename'] = video_info['vid_name'] if 'filename' not in video_info else video_info['filename']\n frame_dir = info_dict['filename']\n info_dict['frame_dir'] = frame_dir\n info_dict['index'] = i\n info_dict['label'] = video_info['answer_idx']\n info_dict['answers'] = video_info['answers'] if 'answers' in video_info else video_info['text']\n info_dict['question'] = video_info['question'] if 'question' in video_info else \"\"\n video_infos.append(info_dict) \n del ann_info\n\n return video_infos", "def parse_image_annotations(self, image_dir, annotations):\n filename_ids = {}\n for i, annot in enumerate(annotations['images']):\n filename_ids[annot['file_name']] = i\n\n # order image data by file name\n images_annot_by_fname = {}\n for i, annot in enumerate(annotations['images']):\n images_annot_by_fname[annot['file_name']] = {\n \"file_name\": os.path.join(image_dir, annot['file_name']),\n \"width\": annot['width'],\n \"height\": annot['height'],\n \"id\": annot['id'],\n \"coco_url\": annot['coco_url'],\n }\n\n # order image data by file id\n images_fname_by_id = {}\n for i, annot in enumerate(annotations['images']):\n images_fname_by_id[annot['id']] = annot['file_name']\n\n return filename_ids, images_annot_by_fname, images_fname_by_id", "def map_annotated_to_annot(annotated_files: Union[list, np.array],\n annot_list: list[crowsetta.Annotation],\n annot_format: str,\n annotated_ext: str | None = None) -> dict[pathlib.Path : crowsetta.Annotation]:\n if type(annotated_files) == np.ndarray: # e.g., vak DataFrame['spect_path'].values\n annotated_files = annotated_files.tolist()\n\n if annot_format in ('birdsong-recognition-dataset', 'yarden', 'generic-seq'):\n annotated_annot_map = _map_using_notated_path(annotated_files, annot_list)\n else:\n try:\n annotated_annot_map = _map_using_ext(annotated_files, annot_list, annot_format, method='remove')\n except MapUsingExtensionError:\n try:\n annotated_annot_map = _map_using_ext(annotated_files, annot_list, annot_format, method='replace',\n annotated_ext=annotated_ext)\n except MapUsingExtensionError as e:\n raise ValueError(\n 'Could not map annotated files to annotations.\\n'\n 'Please see this section in the `vak` documentation:\\n'\n 'https://vak.readthedocs.io/en/latest/howto/howto_prep_annotate.html'\n '#how-does-vak-know-which-annotations-go-with-which-annotated-files'\n ) from e\n\n return annotated_annot_map" ]
[ "0.68433934", "0.6776701", "0.65336627", "0.64016545", "0.63647145", "0.6360142", "0.6300034", "0.6286142", "0.62682825", "0.62356395", "0.6151858", "0.61417496", "0.60985434", "0.6070481", "0.60614765", "0.5994977", "0.59927946", "0.59677225", "0.59677225", "0.5963747", "0.5961413", "0.595764", "0.5951373", "0.5931607", "0.59270746", "0.5916148", "0.59125835", "0.5908562", "0.58830774", "0.5841526" ]
0.7242496
0
writes out train and val txt files for caffe
def write_textfiles(train, val, anno): """ used only for side effect """ # fn creates text file line in form '<filename> <int mapping of grip type>' # for each train/val file and writes each line in corresponding # train.txt/val.txt for training # to_line = lambda fname:'{} {}'.format(fname,labelmap[anno[fname]['grip']]) to_line = lambda fname:'{} {}'.format(fname,labelmap[anno[fname]['grip']]) train_str = '\n'.join(map(to_line, train)) val_str = '\n'.join(map(to_line, val)) with open('train.txt', 'w') as trainfile: trainfile.write(train_str) with open('val.txt', 'w') as valfile: valfile.write(val_str)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def generate_train_txt(name, path):\n with open(path + '/test.txt', 'a') as file:\n file.write('/content/YOLO_metric/data/obj/' + name + '\\n')", "def write_to_train_file(files: List, train_file_path: str) -> None:\n f = open(train_file_path, \"w\")\n text_to_save = \"\"\n for i, img_path in enumerate(files):\n img_path_stripped = img_path.replace(\"/darknet\", \"\")\n if i == len(files) - 1:\n text_to_save += img_path_stripped\n else:\n text_to_save += img_path_stripped + \"\\n\"\n\n f.write(text_to_save)\n f.close()", "def train(self, trainfile):", "def write_txt(self):\n random.seed(self.seed)\n sites = ['BIDMC', 'HK', 'I2CVB', 'ISBI', 'ISBI_15', 'UCL']\n site_files, site_masks = self.read_file_names()\n\n for idx in range(len(site_files)):\n # get files name\n files = site_files[idx]\n segmentation = site_masks[idx]\n len_files = len(files)\n site_label = sites[idx]\n # shuffle the patient's file\n indices = list(range(len_files))\n random.shuffle(indices)\n\n if self.split_te == None:\n # get list of indices\n split = int(np.floor(self.split_val*len_files))\n train_idx = indices[split:]\n valid_idx = indices[:split]\n split_un_sup = int(self.split_sup * len(train_idx))\n train_sup_idx = train_idx[split_un_sup:]\n train_unsup_idx = train_idx[:split_un_sup]\n # slice the original list with the indices\n files_train_sup = [files[i] for i in train_sup_idx]\n files_train_unsup = [files[i] for i in train_unsup_idx]\n masks_train_sup = [segmentation[i] for i in train_sup_idx]\n masks_train_unsup = [segmentation[i] for i in train_unsup_idx]\n files_val = [files[i] for i in valid_idx]\n masks_val = [segmentation[i] for i in valid_idx]\n # write txt file\n self.generate_txt('train_supervised_files_tr_val_' + site_label + '.txt', files_train_sup, masks_train_sup)\n self.generate_txt('train_unsupervised_files_tr_val_' + site_label + '.txt', files_train_unsup, masks_train_unsup)\n self.generate_txt('val_files_tr_val_' + site_label + '.txt', files_val, masks_val)\n else:\n # get list of indices\n split_tr_te = int(np.floor(self.split_te*len_files))\n train_idx_tmp = indices[split_tr_te:]\n test_idx = indices[:split_tr_te]\n split_tr_val = int(self.split_val*len(train_idx_tmp))\n train_idx = train_idx_tmp[split_tr_val:]\n valid_idx = train_idx_tmp[:split_tr_val]\n split_un_sup = int(self.split_sup * len(train_idx))\n train_sup_idx = train_idx[split_un_sup:]\n train_unsup_idx = train_idx[:split_un_sup]\n # slice the original list with the indices\n files_train_sup = [files[i] for i in train_sup_idx]\n files_train_unsup = [files[i] for i in train_unsup_idx]\n masks_train_sup = [segmentation[i] for i in train_sup_idx]\n masks_train_unsup = [segmentation[i] for i in train_unsup_idx]\n files_test = [files[i] for i in test_idx]\n masks_test = [segmentation[i] for i in test_idx]\n files_val = [files[i] for i in valid_idx]\n masks_val = [segmentation[i] for i in valid_idx]\n # write txt file\n self.generate_txt('train_supervised_files_tr_te_val_' + site_label + '.txt', files_train_sup, masks_train_sup)\n self.generate_txt('train_unsupervised_files_tr_te_val_' + site_label + '.txt', files_train_unsup, masks_train_unsup)\n self.generate_txt('test_files_tr_te_val_'+site_label+'.txt', files_test, masks_test)\n self.generate_txt('val_files_tr_te_val_'+site_label+'.txt', files_val, masks_val)", "def write_train_data(lafs, ltf_dir, enc, trainf):\n with open(trainf, 'w') as f:\n\n A_vals = set()\n B_vals = set()\n G_vals = set()\n ltfs = []\n\n for laf in lafs:\n # Check that the LTF and LAF are valid.\n bn = os.path.basename(laf);\n ltf = os.path.join(ltf_dir, bn.replace('.laf.xml', '.ltf.xml'));\n ltfs.append(ltf)\n\n A_vals, B_vals, G_vals = get_ABG_value_sets(ltfs, logger)\n\n\n# laf_doc = load_doc(laf, LAFDocument, logger);\n# ltf_doc = load_doc(ltf, LTFDocument, logger);\n# if laf_doc is None or ltf_doc is None:\n# continue;\n \n # Extract features/targets.\n# try:\n # Extract tokens.\n# try:\n# tokens, token_ids, token_onsets, token_offsets, token_As, token_Bs, token_Gs = ltf_doc.tokenizedWithABG();\n# except:\n# tokens, token_ids, token_onsets, token_offsets = ltf_doc.tokenized();\n# token_As = token_Bs = token_Gs = None;\n# if token_As != None:\n# A_vals.update(token_As)\n# if token_Bs != None:\n# B_vals.update(token_Bs)\n# if token_Gs != None:\n# G_vals.update(token_Gs)\n# except:\n# logger.warn('ABG values not found for %s. Skipping.' % laf);\n# continue;\n\n print(\"Found the following number of values for ABG:\\nA: {}\\nB: {}\\nG: {}\\n\".format(len(A_vals), len(B_vals), len(G_vals)))\n\n for laf in lafs:\n # Check that the LTF and LAF are valid.\n bn = os.path.basename(laf);\n ltf = os.path.join(ltf_dir, bn.replace('.laf.xml', '.ltf.xml'));\n laf_doc = load_doc(laf, LAFDocument, logger);\n ltf_doc = load_doc(ltf, LTFDocument, logger);\n if laf_doc is None or ltf_doc is None:\n continue;\n \n # Extract features/targets.\n try:\n # Extract tokens.\n try:\n tokens, token_ids, token_onsets, token_offsets, token_nums, token_As, token_Bs, token_Gs, token_Fs, token_Js = ltf_doc.tokenizedWithABG();\n except:\n tokens, token_ids, token_onsets, token_offsets, token_nums = ltf_doc.tokenized();\n token_As = token_Bs = token_Gs = token_Fs = token_Js = None;\n \n # Convert mentions to format expected by the encoder; that is,\n # (tag, token_onset, token_offset).\n mentions = laf_doc.mentions();\n if len(mentions) == 0:\n mentions_ = [];\n else:\n # Map to the minimal enclosing span of tokens in the\n # supplied LTF.\n entity_ids, tags, extents, char_onsets, char_offsets = zip(*mentions);\n mention_onsets, mention_offsets = convert_extents(char_onsets, char_offsets,\n token_onsets, token_offsets);\n mentions_ = list(zip(tags, mention_onsets, mention_offsets));\n\n # Eliminate overlapping mentions, retaining whichever\n # is first when sorted in ascending order by (onset, offset).\n sort_mentions(mentions_);\n prev_mention_offset = -1;\n temp_mentions_ = [];\n for tag, mention_onset, mention_offset in mentions_:\n if mention_onset > prev_mention_offset:\n temp_mentions_.append([tag, mention_onset, mention_offset]);\n prev_mention_offset = mention_offset;\n mentions_ = temp_mentions_;\n\n feats, targets = enc.get_feats_targets(tokens, mentions_, token_nums, token_As, token_Bs, token_Gs, token_Fs, token_Js, A_vals, B_vals, G_vals);\n\n except:\n logger.warn('Feature extraction failed for %s. Skipping.' % laf);\n continue;\n\n # Write to file.\n write_crfsuite_file(f, feats, targets);", "def create_train_sets(self, proportion_val):\n l_path = os.listdir(self.image_folder_path)\n lr_path = random.sample(l_path, len(l_path))\n val_files = lr_path[: round(proportion_val * len(lr_path))]\n train_files = lr_path[round(proportion_val * len(lr_path)) :]\n delete_files(self.root_name, \"/VOC2021/ImageSets/Main\")\n write_txt(\"train.txt\", self.txt_path, train_files)\n write_txt(\"val.txt\", self.txt_path, val_files)", "def write_train_data_to_files(sizes,\n trainFListFpath = os.path.join(DATA_DIR, 'trainFnames.txt'),\n outputDir = DATA_DIR):\n\n for width, height in sizes:\n\n X_train, y = create_training_data_table(trainFListFpath, width, height)\n\n # train X\n np.savetxt(os.path.join(outputDir, 'X_train_%i_%i.csv' % (width, height)),\n X_train, delimiter=',')\n\n # train y\n np.savetxt(os.path.join(outputDir, 'y.csv'), y, delimiter=',')", "def create_train(train_img_path):\n\n f = open(\"train.txt\", \"w+\")\n for subdirs, dirs, files in os.walk(train_img_path):\n for filename in files:\n if filename.endswith(\".jpg\"):\n train_image_path = os.path.join(train_img_path, filename)\n print(train_image_path)\n f.write(train_image_path + \"\\n\")\n f.close()", "def write_data(data_to_write_train, data_to_write_test, train_path, eval_path ,test_path):\n aligned_lists_train = data_to_write_train[0]\n raw_lists_train = data_to_write_train[2]\n\n aligned_lists_eval = data_to_write_test[0]\n raw_lists_eval = data_to_write_test[2]\n\n aligned_lists_test = data_to_write_test[1]\n raw_lists_test = data_to_write_test[3]\n\n filelist = list([train_path, eval_path, test_path])\n\n for file in filelist:\n aligned_path = os.path.join(file, 'aligned_image')\n raw_path = os.path.join(file, 'raw_image')\n os.mkdir(aligned_path)\n os.mkdir(raw_path)\n\n # raw image data\n for Idx, train_raw in enumerate(raw_lists_train):\n img = Image.open(train_raw)\n img.save(train_path+'/raw_image/img_'+f'{Idx:04d}.jpg')\n if Idx%100 == 0:\n print('\\t%d images are saved'% Idx); \n print('\\tTrain raw images saved! ')\n\n for Idx, eval_raw in enumerate(raw_lists_eval):\n img = Image.open(eval_raw)\n img.save(eval_path+'/raw_image/img_'+f'{Idx:04d}.jpg')\n if Idx%100 == 0:\n print('\\t%d images are saved'% Idx); \n print('\\tEval raw images saved! ')\n\n for Idx, test_raw in enumerate(raw_lists_test):\n img = Image.open(test_raw)\n img.save(test_path+'/raw_image/img_'+f'{Idx:04d}.jpg')\n if Idx%100 == 0:\n print('\\t%d images are saved'% Idx); \n print('\\tTest raw images saved! ')\n\n # aligned image data\n for Idx, train_aligned in enumerate(aligned_lists_train):\n img = Image.open(train_aligned)\n img.save(train_path+'/aligned_image/img_'+f'{Idx:04d}.jpg')\n if Idx%100 == 0:\n print('\\t%d images are saved'% Idx); \n print('\\tTrain aligned images saved! ')\n\n for Idx, eval_aligned in enumerate(aligned_lists_eval):\n img = Image.open(eval_aligned)\n img.save(eval_path+'/aligned_image/img_'+f'{Idx:04d}.jpg')\n if Idx%100 == 0:\n print('\\t%d images are saved'% Idx); \n print('\\tEval aligned images saved! ')\n\n for Idx, test_aligned in enumerate(aligned_lists_test):\n img = Image.open(test_aligned)\n img.save(test_path+'/aligned_image/img_'+f'{Idx:04d}.jpg')\n if Idx%100 == 0:\n print('\\t%d images are saved'% Idx); \n print('\\tTest aligned images saved! ')", "def to_file(self, fn):\n store.store_dict(fn, 'trainalgorithm', self.to_dict())", "def store_training_validation_file_list(data_paths, save_dir, train_num,\n logger):\n training_dir = data_paths[0]\n validation_dir = data_paths[1]\n\n save_list = os.path.join(save_dir, '{}_train_valid_file_list.txt'.format(\n train_num))\n\n\n with open(save_list, \"w\") as f:\n\n def get_images(path):\n\n sub_dirs = [x[0] for x in os.walk(path)]\n sub_dirs.sort()\n\n for sub_dir in sub_dirs:\n images = glob.glob(sub_dir + '/*.jpg')\n \n # for dirs containing jpgs, write the dir path and files to save_list\n if len(images) > 0:\n f.write(sub_dir + \"\\n\")\n for image in images:\n f.write(\" \" + pathlib.Path(image).name + \"\\n\")\n\n f.write(\"LIST OF FILES USED IN RUN {}\\n\".format(train_num))\n f.write(\"===============================\\n\")\n\n f.write(\"TRAINING\\n\")\n f.write(\"--------\\n\")\n\n get_images(training_dir)\n\n f.write(\"VALIDATION\\n\")\n f.write(\"----------\\n\")\n\n get_images(validation_dir)\n\n logger.info(\"File Generation: %s\",\n \"Training and validation files list generated.\")", "def train_enroller(self, train_files, enroller_file):\n # save something\n bob.io.base.save(_data, enroller_file)", "def on_epoch_end(self, epoch, epoch_logs):\n\n train_preds = []\n test_preds = []\n\n train_filepath = '{}_train.txt'.format(self.save_filepath)\n test_filepath = '{}_test.txt'.format(self.save_filepath)\n\n train = (train_filepath, self.X_train, self.y_train)\n test = (test_filepath, self.X_test, self.y_test)\n\n for fp, X, y in (train, test): \n with open(fp, 'a+') as f: \n f.write('Epoch {}: \\n'.format(epoch))\n f.write('-' * 50 + '\\n')\n for x, y_true in zip(X, y): \n y_pred = generate_sequence(self.model, x)\n y_pred_str = map_idxs_to_str(y_pred, self.idx_word_dct)\n y_true_str = map_idxs_to_str(y_true, self.idx_word_dct)\n f.write('Actual: ' + repr(y_true_str) + '\\n')\n f.write('Predicted: ' + repr(y_pred_str))\n f.write('\\n')\n\n f.write('\\n' * 2)", "def export(self, output_dir, config, train_ratio=0.7, delimiter=\",\"):\n model_dir = os.path.join(output_dir, self.model_id)\n if not os.path.exists(model_dir):\n os.makedirs(model_dir)\n X_tr, X_te = self.get_train_test_embeddings(config, train_ratio)\n #save text feature matrix\n idx = config[\"dimension\"]\n tr_text = csr_matrix(X_tr[:,:idx])\n te_text = csr_matrix(X_te[:,:idx])\n print(\"text\", tr_text.shape, te_text.shape)\n save_npz(os.path.join(model_dir, \"train_text\"), tr_text)\n save_npz(os.path.join(model_dir, \"test_text\"), te_text)\n #save history feature matrix\n if config.get(\"user_history\", False):\n tr_history = X_tr[:,idx:idx+4]\n te_history = X_te[:,idx:idx+4]\n np.savetxt(os.path.join(model_dir, \"train_history.csv\"), tr_history, delimiter=delimiter)\n np.savetxt(os.path.join(model_dir, \"test_history.csv\"), te_history, delimiter=delimiter)\n idx += 4\n print(\"history\", tr_history.shape, te_history.shape)\n # save node embeddings\n if \"user_ne\" in config and X_tr.shape[1] > idx:\n tr_network = X_tr[:,idx:]\n te_network = X_te[:,idx:]\n np.savetxt(os.path.join(model_dir, \"train_network.csv\"), tr_network, delimiter=delimiter)\n np.savetxt(os.path.join(model_dir, \"test_network.csv\"), te_network, delimiter=delimiter)\n print(\"network\", tr_network.shape, te_network.shape)\n #save labels\n np.savetxt(os.path.join(model_dir, \"train_label.csv\"), self.tr_label, delimiter=delimiter, fmt='%i')\n np.savetxt(os.path.join(model_dir, \"test_label.csv\"), self.te_label, delimiter=delimiter, fmt='%i')\n #save meta\n self.tr_meta[self._exported_meta_columns].to_csv(os.path.join(model_dir, \"train_meta.csv\"), index=False, sep=delimiter)\n self.te_meta[self._exported_meta_columns].to_csv(os.path.join(model_dir, \"test_meta.csv\"), index=False, sep=delimiter)\n print(\"Model was exported\")\n return model_dir", "def write_checkpoint(self):\n self.file_checkpoint_data = open(self.path_checkpoint, \"a+\")\n array_to_write = [str(self.radious), self.type_feature, self.type_filtering, self.h_filterig]\n self.file_checkpoint_data.write(','.join(array_to_write) + \"\\n\")\n self.file_checkpoint_data.flush()", "def write_to_file(train_file, test_file, log_dict):\n i = 0\n train_events = []\n test_events = []\n\n for key in log_dict:\n trace = log_dict[key]\n if random.randint(0,1) == 0: # Add file to training set with 50% chance\n for e_idx in range(len(trace)):\n train_events.append(\",\".join([str(x) for x in trace[e_idx]]) + \",\" + str(key) + \",0,None\")\n else: # Add file to test set\n if random.randint(0,100) > 50: # No anomaly injection with 50% chance\n for e_idx in range(len(trace)):\n test_events.append(\",\".join([str(x) for x in trace[e_idx]]) + \",\" + str(key) + \",0,None\")\n else: # Anomaly injection\n trace, types = introduce_anomaly(trace, single=False)\n for e_idx in range(len(trace)):\n test_events.append(\",\".join([str(x) for x in trace[e_idx]]) + \",\" + str(key) + \",1,\\\"\" + str(types) + \"\\\"\")\n\n with open(train_file, \"w\") as fout:\n fout.write(\",\".join([\"Time\", \"Activity\", \"Resource\", \"Weekday\", \"Case\", \"Anomaly\", \"Type\"]) + \"\\n\")\n for e in train_events:\n fout.write(e + \"\\n\")\n\n with open(test_file, \"w\") as fout:\n fout.write(\",\".join([\"Time\", \"Activity\", \"Resource\", \"Weekday\", \"Case\", \"Anomaly\", \"Type\"]) + \"\\n\")\n for e in test_events:\n fout.write(e + \"\\n\")", "def __save_datasets(self):\n self.train.to_csv('{}/{}/{}'.format(path_to_train_set, img_format, 'train.csv'))\n self.valid.to_csv('{}/{}/{}'.format(path_to_valid_set, img_format, 'valid.csv'))\n self.test.to_csv('{}/{}/{}'.format(path_to_test_set, img_format, 'test.csv'))", "def data_to_file(tweets, tweetsTest, alltweets, user_path_train, context_path_train, user_path_dev, context_path_dev):\n # write in train data\n # open user file name\n user_file = open(user_path_train, \"w+\")\n # place user tweets - one per line - in a file\n for tweetid in tweets:\n # get text of tweet with tweetid from user\n for t in alltweets[0]:\n if t.id == tweetid:\n tweet = t.text\n break\n # add string to file\n user_file.write(tweet + \"\\n\")\n user_file.close()\n # open context file name\n context_file = open(context_path_train, \"w+\")\n # place context tweets - one per \"time\" - in a file\n for tid, c in tweets.iteritems():\n # concatenate all context tweets into one string\n tweet = \"\"\n for t in c:\n tweet = tweet + \" \" + t.text\n # write mega-tweet to file\n context_file.write(tweet + \"\\n\")\n context_file.close()\n\n # write in test data\n user_file_dev = open(user_path_dev, \"w+\")\n # place user dev tweets - one per line - in a file\n for tweetid in tweetsTest:\n # get text of tweet with tweetid from user\n for t in alltweets[0]:\n if t.id == tweetid:\n tweet = t.text\n break\n # add string to file\n user_file_dev.write(tweet + \"\\n\")\n user_file_dev.close()\n\n # open context dev file name\n context_file_dev = open(context_path_dev, \"w+\")\n # place context tweets - one per \"time\" - in a file\n for tid, c in tweetsTest.iteritems():\n # concatenate all context tweets into one string\n tweet = \"\"\n for t in c:\n tweet = tweet + \" \" + t.text\n # write mega-tweet to file\n context_file_dev.write(tweet + \"\\n\")\n context_file_dev.close()", "def MakeDataSetFiles(dirname):\n\n\n if not os.path.exists(dirname):\n os.mkdir(dirname)\n if not os.path.exists(os.path.join(dirname, 'train')):\n os.mkdir(os.path.join(dirname, 'train'))\n if not os.path.exists(os.path.join(dirname, 'test')):\n os.mkdir(os.path.join(dirname, 'test'))\n data_train = fetch_20newsgroups(subset='train', categories=None, shuffle=True, random_state=42)\n data_test = fetch_20newsgroups(subset='test', categories=None, shuffle=True, random_state=42)\n\n if dirname[-1] == '/' or dirname[-1] == '\\\\':\n dirname = dirname[:-1]\n \n Util.WriteClassFile(data_train.target, os.path.join(dirname, 'train_classes.txt'))\n Util.WriteClassFile(data_test.target,os.path.join(dirname, 'test_classes.txt'))\n\n\n train_counter = 0;\n for doc in data_train.data:\n filename = 'train_' + str(train_counter).zfill(5);\n f = file(os.path.join(dirname, 'train', filename), 'w');\n f.write(doc.encode('ascii', 'ignore'));\n f.close();\n train_counter = train_counter + 1;\n\n test_counter = 0;\n for doc in data_test.data:\n filename = 'test_' + str(test_counter).zfill(5);\n f = file(os.path.join(dirname, 'test', filename), 'w');\n f.write(doc.encode('ascii', 'ignore'));\n f.close();\n test_counter = test_counter + 1;\n\n class_index = file(os.path.join(dirname, 'class_label_index.txt'), 'w')\n for label in data_train.target_names:\n class_index.write(label + '\\n')\n class_index.close()", "def write_training_metrics(self) -> None:\n self.trainer_metrics.write_training_metrics()", "def save2file(self):\n ids_input = []\n labels_input = []\n ids_path = os.path.join(self.path, 'ids')\n if not os.path.exists(ids_path):\n os.makedirs(ids_path)\n labels_path = os.path.join(self.path, 'labels')\n if not os.path.exists(labels_path):\n os.makedirs(labels_path)\n ids_total = len(self.test)\n for i in range(ids_total):\n ids_input = self.test[i][0]\n labels_input = self.test[i][1]\n file_name = \"ids/\" + str(i) + \".bin\"\n file_path = os.path.join(self.path, file_name)\n np.array(ids_input, dtype=np.int32).tofile(file_path)\n file_name = \"labels/\" + str(i) + \".bin\"\n file_path = os.path.join(self.path, file_name)\n np.array(labels_input, dtype=np.int32).tofile(file_path)\n print(\"\\n ****** Success! ******\\n \")", "def main(training_file_name):\n attribute, inverse = build_classifier(training_file_name)\n trained_file = open(TRAINED_FILE_NAME, mode='w')\n prolog(trained_file)\n write_body(trained_file, attribute, inverse)\n epilog(trained_file)", "def _dump_states(self, train=True):\n\t\tprefix = self.config.experiment_dir_name+\"/datastreams/\"\n\t\ttry:\n\t\t\tos.mkdir(prefix)\n\t\texcept:\n\t\t\tpass\n\n\t\tprefix += \"{}.pickle\"\n\n\t\tif train:\n\t\t\tself.train_accuracy.dump(prefix.format(\"train_accuracy\"))\n\t\t\tself.train_epochs.dump(prefix.format(\"train_epochs\"))\n\t\t\tself.train_loss.dump(prefix.format(\"train_loss\"))\n\t\t\tself.train_confusion_matrix.dump(prefix.format(\"train_confusion_matrix\"))\n\t\t\tself.learning_rate.dump(prefix.format(\"learning_rate\"))\n\t\telse:\n\t\t\tself.val_accuracy.dump(prefix.format(\"val_accuracy\"))\n\t\t\tself.val_epochs.dump(prefix.format(\"val_epochs\"))\n\t\t\tself.val_loss.dump(prefix.format(\"val_loss\"))\n\t\t\tself.val_confusion_matrix.dump(prefix.format(\"val_confusion_matrix\"))\n\t\t\"\"\"\n\t\tSave dataset specific metadata into experiment dir\n\t\t\"\"\"\n\t\t# TODO: Redo this with more information from dataset meta.json file\n\t\tmeta_path = self.config.experiment_dir_name+\"/meta.json\"\n\t\t_meta = {}\n\t\t_meta[\"classes\"] = self.classes\n\t\t_meta[\"plot_platform\"] = self.config.plot_platform\n\t\t# _meta[\"dataset_dir\"] = self.dataset.dataset_folder\n\t\tif not os.path.exists(meta_path):\n\t\t\tfp = open(meta_path, \"w\")\n\t\t\tfp.write(json.dumps(_meta))\n\t\t\tfp.close()", "def write_to_txt(batch, filepath, typ='vector', verbose ='dataset'):\n if typ == 'params':\n with open(filepath, \"w\") as txt:\n for param_pack in batch:\n txt.write(\"{} ; {} ; {} \\n\".format(param_pack.alphaL, \n param_pack.alphaR, param_pack.label))\n #txt.write(str(param_pack.alphaL) +\", \"+str(param_pack.alphaR) +\"\\n\")\n elif typ == 'vector':\n if verbose == 'human':\n with open(filepath, \"w\") as txt:\n for vector in batch:\n txt.write(str(vector[0]) + \"\\n\")\n txt.write(str(vector[1]) + \"\\n\")\n elif verbose == 'dataset':\n with open(filepath, \"w\") as txt:\n for vector in batch:\n #txt.write(str(vector[0].x) +\";\"+str(vector[0].y) +\";\"+ str(vector[0].angle) +\";\"+ str(vector[0].norm()) + \"\\n\")\n txt.write(str(vector[1].x) +\";\"+ str(vector[1].angle) +\";\"+ str(vector[1].norm()) + \"\\n\")", "def generate_txt(self, train_split=1.0):\n\n txtname = [\n join_paths(self.phase_path, 'train_list.txt'),\n join_paths(self.phase_path, 'val_list.txt')\n ]\n\n image_files_npy = os.listdir(self.image_path)\n label_files_npy = [\n name.replace(\"Case\", \"mask_case\") for name in image_files_npy\n ]\n\n self.split_files_txt(txtname[0], image_files_npy, label_files_npy,\n train_split)\n self.split_files_txt(txtname[1], image_files_npy, label_files_npy,\n train_split)", "def save_features_to_file(self):\n if not os.path.exists(self.features_save_path):\n os.makedirs(self.features_save_path)\n for s in self.sets:\n self.save_features_to_file_by_set(s)", "def write_trainingdata(args: ProcessTrainingArgs) -> None:\n log.info(\"Testing data is fold {} of {}\".format(args.testfold,\n args.folds.K))\n log.info(\"Writing training data to tfrecord in {}-point batches\".format(\n args.batchsize))\n n_rows = len(args.target_src)\n worker = _TrainingDataProcessor(args.feature_path, args.image_spec,\n args.halfwidth)\n sworker = Serialised(worker)\n tasks = list(batch_slices(args.batchsize, n_rows))\n out_it = task_list(tasks, args.target_src, sworker, args.nworkers)\n fold_it = args.folds.iterator(args.batchsize)\n tfwrite.training(out_it, n_rows, args.directory, args.testfold, fold_it)", "def create_train_file(img_folder_path: str, train_file_path: str) -> None:\n files = []\n for ext in (\"*.gif\", \"*.png\", \"*.jpg\", \"*.bmp\"):\n img_path = glob(join(img_folder_path, ext))\n if img_path:\n files.extend(img_path)\n\n write_to_train_file(files, train_file_path)\n\n print(\"Training files are created in \" + img_folder_path)", "def run(dataset = 1):\n train_list, test_list = load_list(dataset, False)\n train_imgs = process_list(train_list)\n test_imgs = process_list(test_list)\n with open(os.path.join(WORKING_DIR, 'data', 'train' + str(dataset) + '.txt'), 'w') as f:\n for img in train_imgs:\n f.write(img)\n f.write(' ')\n if img[-14] == 'F':\n f.write('1')\n else:\n f.write('0')\n f.write('\\n')\n with open(os.path.join(WORKING_DIR, 'data', 'test' + str(dataset) + '.txt'), 'w') as f:\n for img in test_imgs:\n f.write(img)\n f.write(' ')\n if img[-14] == 'F':\n f.write('1')\n else:\n f.write('0')\n f.write('\\n')", "def train(self):\n for e in range(self.train_config['nb_epochs']):\n self.on_epoch(e)\n\n with open(os.path.join(self.exp_path, 'config.yml'), 'w') as outfile:\n yaml.dump(self.config, outfile, default_flow_style=False)" ]
[ "0.7014946", "0.67300874", "0.660001", "0.6495438", "0.63600695", "0.6263932", "0.62282443", "0.62009114", "0.6172849", "0.614487", "0.60852087", "0.6045778", "0.60068756", "0.5990579", "0.5930968", "0.5901763", "0.5892108", "0.5886284", "0.5884193", "0.58708364", "0.5862634", "0.58560866", "0.58442336", "0.58320403", "0.5821017", "0.580995", "0.578044", "0.5771988", "0.5766107", "0.57512957" ]
0.7181774
0
moves train/val files to trainingdata dir after applying optional transformations of resizing and centercropping
def move_and_transform(train, val, size, resize=True, center_crop=False): load_image = lambda fname: cv2.imread(os.path.join(ALL_IMAGES, fname)) resize_image = lambda img: cv2.resize(img, (size, size)) move_image = lambda (img, fname): cv2.imwrite(fname, img) train_imgs = map(load_image, train) val_imgs = map(load_image, val) if center_crop: pass # TODO if resize: train_imgs = map(resize_image, train_imgs) val_imgs = map(resize_image, val_imgs) train_fnames = map(lambda fname: os.path.join(TRAIN_DIR, fname), train) val_fnames = map(lambda fname: os.path.join(VAL_DIR, fname), val) map(move_image, zip(train_imgs, train_fnames)) map(move_image, zip(val_imgs, val_fnames))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def transformation_for_training(train_dir):\n\n train_transforms = transforms.Compose([transforms.RandomRotation(30),\n transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], \n [0.229, 0.224, 0.225])])\n\n return datasets.ImageFolder(train_dir, transform=train_transforms)", "def preprocess_dir(data_path,\n output_path,\n dataset,\n n_train,\n new_size,\n ):\n img_type_dict = get_class_labels()\n\n print('Preprocessing:', dataset)\n target_data_path = data_path\n disease_dirs = os.listdir(target_data_path)\n disease_dirs = [d for d in disease_dirs if\n os.path.isdir(os.path.join(target_data_path, d))]\n img_stack, target_list = [], []\n img_names = []\n for img_type in disease_dirs:\n class_lbl = img_type_dict[img_type]\n n_class = int(n_train / len(disease_dirs))\n print('\\t', img_type)\n img_files_path = os.path.join(target_data_path, img_type)\n if not (os.path.isdir(img_files_path)):\n continue\n img_files = os.listdir(img_files_path)\n img_files = [f for f in img_files if f.endswith('.jpeg')]\n if dataset == 'train':\n img_files = img_files[0:n_class]\n for img_fname in img_files:\n img_path = os.path.join(img_files_path, img_fname)\n img_arr = np.array(Image.open(img_path))\n img_arr = skimage.transform.resize(img_arr, new_size)\n img_arr = (img_arr - img_arr.min()) / img_arr.max()\n img_stack.append(img_arr)\n target_list.append(class_lbl)\n img_names += [n.split('.')[0] for n in img_files]\n # Save preprocessed data\n save_data(output_path, img_stack, target_list,\n new_size, dataset, n_train, img_names)", "def populate_train_test_val_dirs_nonrandomly(root_dir=(os.getcwd()), val_ratio=0.15, test_ratio=0.05):\n\n ''' Creating partitions of the data after shuffling '''\n # Folder to copy images from\n src = join(root_dir, 'CoregisteredImages')\n\n all_file_names = [f for f in os.listdir(src) if isfile(join(src, f))]\n\n # Select the number of images to skip between validation images\n val_skip_number = len(all_file_names) / (val_ratio * len(all_file_names))\n\n # Select the number of images to skip between test images\n test_skip_number = len(all_file_names) / (test_ratio * len(all_file_names))\n\n # Get the list of validation file names, test file names, and train file names\n val_file_names = all_file_names[::int(val_skip_number)]\n test_file_names = [filename for filename in all_file_names[::int(test_skip_number + 1)] if filename not in val_file_names]\n train_file_names = [filename for filename in all_file_names if filename not in val_file_names and filename not in test_file_names]\n\n ''' Print the file distribution amongst the folders '''\n print_file_distribution(len(all_file_names), len(train_file_names), len(val_file_names), len(test_file_names))\n\n print(train_file_names)\n\n ''' Copy-Pasting Images '''\n for name in train_file_names:\n shutil.copy(join(root_dir, 'CoregisteredImages', name), root_dir + '/train/CoregisteredImages')\n shutil.copy(join(root_dir, 'BlurryImages', name), root_dir + '/train/BlurryImages')\n for name in val_file_names:\n shutil.copy(join(root_dir, 'CoregisteredImages', name), root_dir + '/val/CoregisteredImages')\n shutil.copy(join(root_dir, 'BlurryImages', name), root_dir + '/val/BlurryImages')\n for name in test_file_names:\n shutil.copy(join(root_dir, 'CoregisteredImages', name), root_dir + '/test/CoregisteredImages')\n shutil.copy(join(root_dir, 'BlurryImages', name), root_dir + '/test/BlurryImages')", "def populate_train_test_val_dirs_nonrandomly(root_dir, val_ratio=0.15, test_ratio=0.05, preliminary_clahe=True,\n apply_masks=True):\n\n ''' Creating partitions of the data after shuffling '''\n # Folder to copy images from\n src = join(root_dir, 'CoregisteredBlurryImages')\n\n all_file_names = [f for f in os.listdir(src) if isfile(join(src, f))]\n\n if val_ratio == 0.0:\n # Select the number of images to skip between validation images\n val_skip_number = len(all_file_names) + 1\n else:\n # Select the number of images to skip between validation images\n val_skip_number = len(all_file_names) / (val_ratio * len(all_file_names))\n\n if test_ratio == 0.0:\n # Select the number of images to skip between test images\n test_skip_number = len(all_file_names) + 1\n else:\n # Select the number of images to skip between test images\n test_skip_number = len(all_file_names) / (test_ratio * len(all_file_names))\n\n # Get the list of validation file names, test file names, and train file names\n val_file_names = all_file_names[::int(val_skip_number)]\n test_file_names = [filename for filename in all_file_names[::int(test_skip_number + 1)]\n if filename not in val_file_names]\n train_file_names = [filename for filename in all_file_names\n if filename not in val_file_names and filename not in test_file_names]\n\n # Print the file distribution among the folders\n logger.print_file_distribution(len(all_file_names), len(train_file_names), len(val_file_names),\n len(test_file_names))\n\n # Copy-Pasting images into train dataset\n for name in train_file_names:\n shutil.copy(join(root_dir, 'CoregisteredBlurryImages', name), root_dir + '/train/CoregisteredBlurryImages')\n shutil.copy(join(root_dir, 'ClearImages', name), root_dir + '/train/ClearImages')\n if apply_masks:\n shutil.copy(join(root_dir, 'Masks', name), root_dir + '/train/Masks')\n\n # Copy-Pasting images into val dataset\n for name in val_file_names:\n shutil.copy(join(root_dir, 'CoregisteredBlurryImages', name), root_dir + '/val/CoregisteredBlurryImages')\n shutil.copy(join(root_dir, 'ClearImages', name), root_dir + '/val/ClearImages')\n if apply_masks:\n shutil.copy(join(root_dir, 'Masks', name), root_dir + '/val/Masks')\n\n # Copy-Pasting images into test dataset\n for name in test_file_names:\n shutil.copy(join(root_dir, 'CoregisteredBlurryImages', name), root_dir + '/test/CoregisteredBlurryImages')\n shutil.copy(join(root_dir, 'ClearImages', name), root_dir + '/test/ClearImages')\n if apply_masks:\n shutil.copy(join(root_dir, 'Masks', name), root_dir + '/test/Masks')\n\n ''' Augment the images in each new folder '''\n # If we want to use preliminary adaptive equalization...\n if preliminary_clahe:\n pass\n # ... then first, apply Contrast Limited Adaptive Histogram Equalization to clear images in all folders\n CLAHE_image_folder(root_dir + '/train/ClearImages')\n CLAHE_image_folder(root_dir + '/val/ClearImages')\n CLAHE_image_folder(root_dir + '/test/ClearImages')\n\n # Then, apply histogram equalization to make the blurry images' histogram match that of the clear images\n hist_match_image_folder(root_dir=join(root_dir, 'train'),\n clear_dir_name='ClearImages',\n blurry_dir_name='CoregisteredBlurryImages',\n match_to_clear=True)\n hist_match_image_folder(root_dir=join(root_dir, 'val'),\n clear_dir_name='ClearImages',\n blurry_dir_name='CoregisteredBlurryImages',\n match_to_clear=True)\n hist_match_image_folder(root_dir=join(root_dir, 'test'),\n clear_dir_name='ClearImages',\n blurry_dir_name='CoregisteredBlurryImages',\n match_to_clear=True)", "def custom_preprocessor(out_dir=''):\n\n # Get name of data set from output directory\n data_name = os.path.split(out_dir)[1]\n\n # For tiny-imagenet-200\n if 'tiny' in data_name.lower():\n\n # Structure the training, validation, and test data directories\n train_dir = os.path.join(out_dir, 'train')\n class_dirs = [os.path.join(train_dir, o) for o in os.listdir(train_dir) if os.path.isdir(os.path.join(train_dir, o))]\n\n for c in class_dirs:\n for f in os.listdir(os.path.join(c, 'images')):\n os.rename(os.path.join(c,'images', f), os.path.join(c, f))\n for d in os.listdir(c):\n if d.find(\"JPEG\") == -1:\n if os.path.isfile(os.path.join(c, d)):\n os.remove(os.path.join(c, d))\n elif os.path.isdir(os.path.join(c, d)):\n os.rmdir(os.path.join(c, d))\n\n # Get validation annotations\n with open(os.path.join(out_dir, 'val/val_annotations.txt')) as f:\n content = f.readlines()\n\n for x in content:\n line = x.split()\n\n if not os.path.exists(os.path.join(out_dir, 'val/',line[1])):\n os.makedirs(os.path.join(out_dir, 'val/',line[1]))\n\n new_file_name = os.path.join(out_dir, 'val',line[1],line[0])\n old_file_name = os.path.join(out_dir, 'val/images',line[0])\n os.rename(old_file_name, new_file_name)\n\n\n # For LFW\n if 'lfw' in data_name.lower():\n\n os.rename(os.path.join(out_dir, 'lfw/'), os.path.join(out_dir, 'lfw_original/'))\n\n lfw_dir = os.path.join(out_dir, 'lfw_original/')\n people_dir = os.listdir(lfw_dir)\n\n num_per_class = 20\n\n new_dir = os.path.join(out_dir, 'lfw_' + str(num_per_class))\n\n if not os.path.isdir(new_dir):\n os.makedirs(new_dir)\n\n for p in people_dir:\n imgs = os.listdir(os.path.join(lfw_dir, p))\n if len(imgs) >= num_per_class:\n shutil.copytree(os.path.join(lfw_dir, p), os.path.join(new_dir, p))\n\n print('{} successfully downloaded and preprocessed.'.format(data_name))", "def populate_train_test_val_dirs_randomly(root_dir=(os.getcwd()), val_ratio=0.15, test_ratio=0.05):\n\n ''' Creating partitions of the data after shuffling '''\n # Folder to copy images from\n src = root_dir # The folder to copy images from\n\n all_file_names = [f for f in os.listdir(src) if isfile(join(src, f))]\n\n np.random.shuffle(all_file_names)\n\n train_file_names, val_file_names, test_file_names = np.split(np.array(all_file_names),\n [int(len(all_file_names) * (\n 1 - val_ratio + test_ratio)),\n int(len(all_file_names) * (1 - test_ratio))])\n ''' Print the file distribution amongst the folders '''\n print_file_distribution(len(all_file_names), len(train_file_names), len(val_file_names), len(test_file_names))\n\n print(train_file_names)\n\n ''' Copy-Pasting Images '''\n for name in train_file_names:\n shutil.copy(join(root_dir, 'CoregisteredImages', name), root_dir + '/train/CoregisteredImages')\n shutil.copy(join(root_dir, 'BlurryImages', name), root_dir + '/train/BlurryImages')\n for name in val_file_names:\n shutil.copy(join(root_dir, 'CoregisteredImages', name), root_dir + '/val/CoregisteredImages')\n shutil.copy(join(root_dir, 'BlurryImages', name), root_dir + '/val/BlurryImages')\n for name in test_file_names:\n shutil.copy(join(root_dir, 'CoregisteredImages', name), root_dir + '/test/CoregisteredImages')\n shutil.copy(join(root_dir, 'BlurryImages', name), root_dir + '/test/BlurryImages')", "def test_train_split(folder_name):\n\n class_folders = glob.glob(os.path.join(folder_name, '*'))\n\n class_names = [i.split('/')[-1] for i in class_folders]\n\n print(class_folders)\n\n train_folder_path = os.path.join(folder_name, 'train_dir')\n validation_folder_path = os.path.join(folder_name, 'val_dir')\n\n if not os.path.exists(train_folder_path):\n os.makedirs(train_folder_path)\n if not os.path.exists(validation_folder_path):\n os.makedirs(validation_folder_path)\n\n # Create the folder structure\n class_folders_train = []\n class_folders_val = []\n for class_name in class_names:\n # Create calss folder in the training directory\n class_folders_train.append(os.path.join(train_folder_path, class_name))\n if not os.path.exists(class_folders_train[-1]):\n os.makedirs(class_folders_train[-1])\n # Create class folder in the validation_directory\n class_folders_val.append(os.path.join(\n validation_folder_path, class_name))\n if not os.path.exists(class_folders_val[-1]):\n os.makedirs(class_folders_val[-1])\n\n class_files = []\n\n for idx, class_folder in enumerate(class_folders):\n class_files = glob.glob(os.path.join(class_folder, '*.jpg'))\n for file in class_files[:int(len(class_files) * 0.7)]:\n copyfile(file, os.path.join(\n class_folders_train[idx], file.split('/')[-1]))\n for file in class_files[int(len(class_files) * 0.7):]:\n print(file)\n print(os.path.join(class_folders_val[idx], file.split('/')[-1]))\n copyfile(file, os.path.join(\n class_folders_val[idx], file.split('/')[-1]))", "def write_data(data_to_write_train, data_to_write_test, train_path, eval_path ,test_path):\n aligned_lists_train = data_to_write_train[0]\n raw_lists_train = data_to_write_train[2]\n\n aligned_lists_eval = data_to_write_test[0]\n raw_lists_eval = data_to_write_test[2]\n\n aligned_lists_test = data_to_write_test[1]\n raw_lists_test = data_to_write_test[3]\n\n filelist = list([train_path, eval_path, test_path])\n\n for file in filelist:\n aligned_path = os.path.join(file, 'aligned_image')\n raw_path = os.path.join(file, 'raw_image')\n os.mkdir(aligned_path)\n os.mkdir(raw_path)\n\n # raw image data\n for Idx, train_raw in enumerate(raw_lists_train):\n img = Image.open(train_raw)\n img.save(train_path+'/raw_image/img_'+f'{Idx:04d}.jpg')\n if Idx%100 == 0:\n print('\\t%d images are saved'% Idx); \n print('\\tTrain raw images saved! ')\n\n for Idx, eval_raw in enumerate(raw_lists_eval):\n img = Image.open(eval_raw)\n img.save(eval_path+'/raw_image/img_'+f'{Idx:04d}.jpg')\n if Idx%100 == 0:\n print('\\t%d images are saved'% Idx); \n print('\\tEval raw images saved! ')\n\n for Idx, test_raw in enumerate(raw_lists_test):\n img = Image.open(test_raw)\n img.save(test_path+'/raw_image/img_'+f'{Idx:04d}.jpg')\n if Idx%100 == 0:\n print('\\t%d images are saved'% Idx); \n print('\\tTest raw images saved! ')\n\n # aligned image data\n for Idx, train_aligned in enumerate(aligned_lists_train):\n img = Image.open(train_aligned)\n img.save(train_path+'/aligned_image/img_'+f'{Idx:04d}.jpg')\n if Idx%100 == 0:\n print('\\t%d images are saved'% Idx); \n print('\\tTrain aligned images saved! ')\n\n for Idx, eval_aligned in enumerate(aligned_lists_eval):\n img = Image.open(eval_aligned)\n img.save(eval_path+'/aligned_image/img_'+f'{Idx:04d}.jpg')\n if Idx%100 == 0:\n print('\\t%d images are saved'% Idx); \n print('\\tEval aligned images saved! ')\n\n for Idx, test_aligned in enumerate(aligned_lists_test):\n img = Image.open(test_aligned)\n img.save(test_path+'/aligned_image/img_'+f'{Idx:04d}.jpg')\n if Idx%100 == 0:\n print('\\t%d images are saved'% Idx); \n print('\\tTest aligned images saved! ')", "def prepare_data(src, dst):\n\n data_prefix = 'miniCelebA_'\n for split in ['train', 'val', 'test']:\n print('processing %s split' % split)\n if (not os.path.exists(os.path.join(dst, 'x_' + split + '.npy')) or not\n os.path.exists(os.path.join(dst, 'y_' + split + '.npy'))):\n labels = glob(os.path.join(src, split, '*'))\n no_sample = 0\n for lb in labels:\n no_sample += len(os.listdir(lb))\n\n x = np.zeros((no_sample, 224, 224, 3))\n y = np.zeros((no_sample, 20))\n count = 0\n for lb in labels:\n files = glob(os.path.join(lb, '*.png'))\n for f in files:\n print('processing file: %s, with label %s' % (f, lb.split('/')[-1]))\n y[count] = to_categorical(int(lb.split('/')[-1]), 20)\n img = misc.imresize(misc.imread(f), (224, 224), 'bicubic')\n if img.ndim == 2:\n img = np.expand_dims(img, -1)\n img = np.concatenate((img, img, img), axis=-1)\n x[count] = img\n\n count += 1\n\n assert count == no_sample, \"number of sample (%d) is different than number of read image (%d)\" % (\n no_sample, count)\n\n x = get_deep_feature(x)\n np.save(os.path.join(dst, data_prefix + 'x_' + split + '.npy'), x)\n np.save(os.path.join(dst, data_prefix + 'y_' + split + '.npy'), y)", "def __init__(self, data_dir_original, data_dir_photoshopped, transform = data_transforms['train']):\n '''\n Notes:\n Would need to just save all the images and label them appropriately.\n Need to figure out how to just extract 1 photoshop transformation fo reach image for each \n \n '''\n cwd = os.path.dirname(os.path.realpath(__file__))\n # Process Photoshopped Images\n data_dir_photoshopped = os.path.join(cwd, '..', data_dir_photoshopped)\n #print(data_dir_photoshopped)\n p_filenames = os.listdir(data_dir_photoshopped)\n p_filenames = [os.path.join(data_dir_photoshopped, f) for f in p_filenames if f.endswith('.jpg')]\n p_labels = [1 for i in range(len(p_filenames))]\n \n # Process Original Images\n data_dir_original = os.path.join(cwd,'..', data_dir_original)\n o_filenames = os.listdir(data_dir_original)\n o_filenames = [os.path.join(data_dir_original, f) for f in o_filenames if f.endswith('.jpg')]\n o_labels = [0 for i in range(len(o_filenames))]\n \n # Add both types together\n self.filenames = p_filenames + o_filenames\n self.labels = p_labels + o_labels\n \n self.filenames, self.labels = shuffle(self.filenames, self.labels, random_state=42)\n self.transform = transform", "def preprocess_train(im, boxes, classes, inst_masks, mask, input_size, min_size=2,\n use_augment=False, training_scale=[0.3, 0.5, 0.7, 1.0]):\n ori_im = np.copy(im)\n target_h, target_w = input_size\n\n # ---------- old data_augmentation ----------\n if use_augment:\n if np.random.choice([0, 1]) != 0:\n scale = np.random.choice(training_scale) # adding more small objects\n im, inst_masks, mask, boxes, classes = random_scale(im, inst_masks, mask, boxes, classes, scale=scale)\n min_obj_cover = np.random.choice([0.8, 0.9, 1.0])\n # truncted examples may lead to multiple-detections..\n im, inst_masks, mask, boxes, classes = random_aspect_ratio(im, inst_masks, mask, boxes, classes,\n min_aspect_ratio=0.5, max_aspect_ratio=2.0,\n min_obj_cover=min_obj_cover)\n #\n # # r = np.random.randint(0, 3)\n # if np.random.rand() < 0.75:\n # im, inst_masks, mask, boxes, classes = fixed_scale(im, inst_masks, mask, boxes, classes, target_h, target_w)\n # else:\n # im, inst_masks, mask, boxes, classes = center_crop2fixed_pad(im, inst_masks, mask, boxes, classes, target_w, target_h,\n # min_size=min_size)\n\n # ---------- old data_augmentation ----------\n\n # ---------- none data_augmentation ----------\n im, inst_masks, mask, boxes, classes = fixed_scale(im, inst_masks, mask, boxes, classes, target_h, target_w)\n im, inst_masks, mask, boxes, classes = random_flip(im, inst_masks, mask, boxes, classes)\n # ---------- none data_augmentation ----------\n\n # ---------- old data_augmentation ----------\n im = distort_color(im)\n # ---------- old data_augmentation ----------\n\n im = imcv2_recolor(im)\n\n # add this because zeros numpy array will cause errors in torch Dataloader\n inst_masks = np.zeros([1, target_h, target_w], dtype=inst_masks.dtype) if inst_masks.size == 0 else inst_masks\n\n boxes = np.asarray(boxes, dtype=np.float32)\n return im, boxes, classes, inst_masks, mask, ori_im", "def sort_collected_data():\n\n def is_from_valid_set(fn):\n return fn.find(\"validation\") != -1\n\n source_dir = \"data\"\n\n x_train_dir = os.path.join(SEG_DATA_FOLDER, \"train\")\n y_train_dir = os.path.join(SEG_DATA_FOLDER, \"train_label\")\n x_valid_dir = os.path.join(SEG_DATA_FOLDER, \"val\")\n y_valid_dir = os.path.join(SEG_DATA_FOLDER, \"val_label\")\n\n for direc in [x_train_dir, y_train_dir, x_valid_dir, y_valid_dir]:\n mkdir_if_not_exist(direc)\n\n images = [x for x in os.listdir(source_dir) if x.find(\"png\") >= 0]\n inputs = [x for x in images if x.find(\"label\") == -1]\n labels = [x for x in images if x.find(\"label\") != -1]\n\n train_x = [x for x in inputs if not is_from_valid_set(x)]\n valid_x = [x for x in inputs if is_from_valid_set(x)]\n train_y = [x for x in labels if not is_from_valid_set(x)]\n valid_y = [x for x in labels if is_from_valid_set(x)]\n\n for f in train_x:\n shutil.copyfile(os.path.join(\"data\", f), os.path.join(x_train_dir, f))\n\n for f in train_y:\n shutil.copyfile(os.path.join(\"data\", f), os.path.join(y_train_dir, f))\n\n for f in valid_x:\n shutil.copyfile(os.path.join(\"data\", f), os.path.join(x_valid_dir, f))\n\n for f in valid_y:\n shutil.copyfile(os.path.join(\"data\", f), os.path.join(y_valid_dir, f))", "def get_files(self):\n train_images = glob(os.path.join(self.images_dir, '*%s' % self.im_extension)) \n train_labels = [x.replace(self.im_extension, '.npy').replace('images', 'groundTruth') for x in train_images]\n val_images = glob(os.path.join(self.val_images_dir, '*%s' % self.im_extension))\n val_labels = [x.replace(self.im_extension, '.npy').replace('images', 'groundTruth') for x in val_images]\n train_images = np.array(train_images)\n train_labels = np.array(train_labels)\n val_images = np.array(val_images)\n val_labels = np.array(val_labels)\n test_images = np.array(\n glob('/media/data_cifs/pytorch_projects/datasets/BSDS500_crops/data/images/test_nocrop/*.jpg'))\n test_labels = np.array(\n [x.replace('images', 'groundTruth').replace('.jpg', '.npy') for x in test_images])\n test_labels = np.array(\n [np.load(x) for x in test_labels])\n keep_idx = np.array([True if x.shape[0] > x.shape[1] else False for x in test_labels])\n test_images = test_images[keep_idx]\n test_labels = test_labels[keep_idx]\n test_images = np.stack([misc.imread(x) for x in test_images], 0)\n test_labels = np.stack(test_labels, 0)\n test_labels = test_labels[..., None]\n\n # Add constant padding to bottom/right\n if self.pad:\n test_images = util.pad(test_images, ((0, 0), (self.pad // 2, self.pad - self.pad // 2), (self.pad // 2, self.pad - self.pad // 2), (0, 0)), mode='linear_ramp')\n test_labels = util.pad(test_labels, ((0, 0), (self.pad // 2, self.pad - self.pad // 2), (self.pad // 2, self.pad - self.pad // 2), (0, 0)), mode='constant', constant_values=0)\n\n # Select images for training\n sort_idx = np.argsort(train_images)\n train_images = train_images[sort_idx[:self.train_size]]\n train_labels = train_labels[sort_idx[:self.train_size]]\n\n # Build CV dict\n cv_files, cv_labels = {}, {}\n cv_files[self.folds['train']] = train_images\n cv_files[self.folds['val']] = val_images\n cv_files[self.folds['test']] = test_images\n cv_labels[self.folds['train']] = train_labels\n cv_labels[self.folds['val']] = val_labels\n cv_labels[self.folds['test']] = test_labels\n return cv_files, cv_labels", "def populate_train_test_val_dirs_randomly(root_dir=(os.getcwd()), val_ratio=0.15, test_ratio=0.05):\n # Creating partitions of the data after shuffling\n # Folder to copy images from\n src = root_dir # The folder to copy images from\n\n all_file_names = [f for f in os.listdir(src) if isfile(join(src, f))]\n\n np.random.shuffle(all_file_names)\n\n train_file_names, val_file_names, test_file_names = np.split(np.array(all_file_names),\n [int(len(all_file_names) * (\n 1 - val_ratio + test_ratio)),\n int(len(all_file_names) * (1 - test_ratio))])\n # Print the file distribution amongst the folders\n logger.print_file_distribution(len(all_file_names), len(train_file_names), len(val_file_names),\n len(test_file_names))\n\n print(train_file_names)\n\n # Copy-Pasting Images\n for name in train_file_names:\n shutil.copy(join(root_dir, 'CoregisteredBlurryImages', name), root_dir + '/train/CoregisteredBlurryImages')\n shutil.copy(join(root_dir, 'ClearImages', name), root_dir + '/train/ClearImages')\n for name in val_file_names:\n shutil.copy(join(root_dir, 'CoregisteredBlurryImages', name), root_dir + '/val/CoregisteredBlurryImages')\n shutil.copy(join(root_dir, 'ClearImages', name), root_dir + '/val/ClearImages')\n for name in test_file_names:\n shutil.copy(join(root_dir, 'CoregisteredBlurryImages', name), root_dir + '/test/CoregisteredBlurryImages')\n shutil.copy(join(root_dir, 'ClearImages', name), root_dir + '/test/ClearImages')", "def main(src, dst, size):\r\n\ttrain_dst = os.path.join(dst, 'train')\r\n\ttest_dst = os.path.join(dst, 'test')\r\n\tlabel_paths = [os.path.join(src, 'labels', i) for i in os.listdir(os.path.join(src, 'labels'))]\r\n\timage_folders = [os.path.join(src, i) for i in os.listdir(src) if i != \"labels\"]\r\n\r\n\timage_paths = {}\r\n\tfor folder in image_folders:\r\n\t\timages = os.listdir(folder)\r\n\t\timage_paths[os.path.basename(folder)] = [os.path.join(folder, i) for i in images]\r\n\tif DEBUG:\r\n\t\tprint(\"image folders are : {}\".format(image_paths.keys()))\r\n\r\n\t# for each image assign its xyz coordinate\r\n\targs = []\r\n\r\n\ttrain_labels = [\"B1\", \"B2\", \"B3\", \"B5\", \"B6\"]\r\n\ttest_labels = [\"B4\"]\r\n\r\n\tfor l_p in label_paths:\r\n\t\tfolder = os.path.basename(l_p).split('_')[0]\r\n\t\tcamera = os.path.basename(l_p).split('_')[-1][0:-4]\r\n\r\n\t\timages = image_paths[folder]\r\n\t\tlabels = get_xyz_coord(l_p)\r\n\t\timages = list(filter(lambda x: os.path.basename(x).split(\"_\")[0] == camera, images))\r\n\t\tif DEBUG:\r\n\t\t\tprint(l_p, camera)\r\n\t\tfor i in images:\r\n\t\t\tindex = int(os.path.basename(i).split('_')[-1][0:-4])\r\n\t\t\tif os.path.basename(l_p)[0:2] in train_labels:\r\n\t\t\t\tdestination = os.path.join(train_dst, folder, os.path.basename(i))\r\n\t\t\telif os.path.basename(l_p)[0:2] in test_labels:\r\n\t\t\t\tdestination = os.path.join(test_dst, folder, os.path.basename(i))\r\n\t\t\telse:\r\n\t\t\t\traise ValueError\r\n\t\t\targs.append([i, destination, reorder(labels[index]), size])\r\n\r\n\tp = Pool()\r\n\tresults = list(tqdm.tqdm(p.imap(image_process, args), ascii=True, total=len(args)))\r\n\tp.close()\r\n\tp.join()\r\n\r\n\tannotations_train = edict()\r\n\tannotations_test = edict()\r\n\tfor r in results:\r\n\t\tdestination, uv_coord, depth, xyz, k = r\r\n\t\tfolder = os.path.basename(os.path.dirname(destination))\r\n\t\timage = os.path.basename(destination)\r\n\r\n\t\tif folder[0:2] in train_labels:\r\n\t\t\tannotations = annotations_train\r\n\t\telif folder[0:2] in test_labels:\r\n\t\t\tannotations = annotations_test\r\n\t\telse:\r\n\t\t\traise ValueError\r\n\r\n\t\tif folder not in annotations:\r\n\t\t\tannotations[folder] = edict()\r\n\t\t\tannotations[folder][image] = edict()\r\n\t\telse:\r\n\t\t\tannotations[folder][image] = edict()\r\n\t\tannotations[folder][image].uv_coord = uv_coord\r\n\t\tannotations[folder][image].k = k\r\n\t\tannotations[folder][image].depth = depth\r\n\t\tannotations[folder][image].xyz = xyz\r\n\r\n\twith open(os.path.join(train_dst, \"annotation.pickle\"), \"wb\") as handle:\r\n\t\tpickle.dump(annotations_train, handle)\r\n\r\n\twith open(os.path.join(test_dst, \"annotation.pickle\"), \"wb\") as handle:\r\n\t\tpickle.dump(annotations_test, handle)", "def transformation_for_testing(test_dir):\n \n # Define transformation\n test_transforms = transforms.Compose([transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], \n [0.229, 0.224, 0.225])])\n \n # Load the Data\n test_data = datasets.ImageFolder(test_dir, transform=test_transforms)\n \n return test_data", "def preprocess_images_and_labels(config,\n image_file_data,\n train_image_id_labels,\n val_image_id_labels):\n # Commenting out the line below in keeping with the comment block above the function. We don't\n # actually need to do this, because safe_create_dir will never overwrite an existing directory,\n # but better to be safe.\n # safe_create_dir(config.ImageDataConfig.preprocessed_image_path)\n\n # Add in a counter for tracking progress via the console\n counter = 0\n\n train_image_metadata, val_image_metadata = [], []\n for image_data in image_file_data:\n\n if image_data.image_id in train_image_id_labels:\n image_metadata = train_image_metadata\n image_label = train_image_id_labels[image_data.image_id]\n else:\n image_metadata = val_image_metadata\n image_label = val_image_id_labels[image_data.image_id]\n\n # TODO Stop squishing the image and handle cropping correctly sized windows at sample time.\n\n # Comment out the chunk below to avoid re-saving our images, which we have\n # already preprocessed. We just want to generate metadata for them.\n\t\"\"\"\n image = load_img(\n image_data.original_file_path,\n target_size=config.ImageDataConfig.size)\n new_file_path = os.path.join(\n config.ImageDataConfig.preprocessed_image_path,\n image_data.original_filename.upper().replace('PNG', 'JPG')) # Convert all images to jpegs.\n image.save(new_file_path, format='JPEG', quality=85)\n\t\"\"\"\n\n # We generate metadata, setting the image filepath as the original filepath, as we\n # have already preprocessed beforehand.\n original_file_path = image_data.original_file_path\n\n image_metadata.append(ProcessedImageMetadata(image_data.image_id, original_file_path, image_label))\n\n return train_image_metadata, val_image_metadata", "def exec_preprocess(self, curr_step):\n assert(self.curr_step_idx > 0 and self.dlist is not None), \"Step Error: Must call init before preprocess\" \n\n #verify raw data & dlist\n self.B_VER(self.sess_path, self.dlist)\n\n #move & preprocess each folder\n funclist = curr_step[\"funclist\"]\n raw_datadir = self.sess_path\n dest_datadir = self.sess_path\n new_dlist = []\n for i, folder in enumerate(self.dlist):\n flist = funclist[i]\n new_folder = self.data_utils.MOVE(raw_datadir, folder, dest_datadir, flist=flist, preview=False)\n new_dlist.append(new_folder)\n self.dlist = new_dlist\n self.default_vis(curr_step)", "def preprocess_with_train_data(self,\n data_dir: Path,\n output_processed_data_dir: Path,\n ) -> NoReturn:\n pass", "def prepare_data_dir(create_valid=DEFAULT_CREATE_VALID, valid_size=DEFAULT_VALID_SIZE) -> None:\n if create_valid and not os.path.isdir(VALID_PATH):\n print('Validation set not found, creating.')\n\n os.mkdir(VALID_PATH)\n\n for d in os.listdir(TRAIN_PATH):\n from_path = TRAIN_PATH + '/' + d\n to_path = VALID_PATH + '/' + d\n\n os.mkdir(to_path)\n\n files = os.listdir(TRAIN_PATH + '/' + d)\n random.shuffle(files)\n\n for f in files[:valid_size]:\n os.rename(from_path + '/' + f, to_path + '/' + f)\n\n elif not create_valid and os.path.isdir(VALID_PATH):\n print('Running without validation set, but ' + VALID_PATH + 'dir found. Recreate data dir before running.')\n exit(1)", "def Dev_Image_data_generator(folderlist,resize = (920,1200),Transformation = True, scaling = True, batch_size = 16):\n\n while True:\n total_classes = len(folderlist.keys())\n keys = folderlist.keys()\n Images = []\n Image_label = []\n for key in folderlist.keys():\n img_label = random.choice(folderlist[key])\n img = Image.open(img_label,'r')\n h = resize[1]\n l = int(img.size[1]*h/img.size[0])\n img = img.resize((h,l), Image.ANTIALIAS)\n background = Image.new('RGB', (resize[1], resize[0]), (255, 255, 255))\n img_w, img_h = img.size\n bg_w, bg_h = background.size\n offset = (int((bg_w - img_w) / 2), int((bg_h - img_h) / 2))\n background.paste(img, offset)\n background = np.asarray(background)\n if Transformation == True:\n rotation = rotate(background,random.choice(range(360)))\n translate = translate_xy(background,random.choice(range(resize[0]/4)),random.choice(range(resize[1]/4)))\n flip = cv2.flip(rotation,1)\n Y = np.concatenate((rotation[np.newaxis,:,:,:],flip[np.newaxis,:,:,:],translate[np.newaxis,:,:,:]))\n Images.append(Y)\n Images.append(background[np.newaxis,:,:,:])\n Image_label.append([key for i in range(4)])\n else:\n Images.append(background[np.newaxis,:,:,:])\n Image_label.append([key])\n Image_label = np.concatenate(Image_label)\n Images = np.concatenate(Images)\n Image_label = np.array(pd.get_dummies(Image_label))\n X_Image , Y_Image = shuffle(Images,Image_label,random_state=0)\n if scaling == True:\n X_Image = X_Image/255\n else:\n X_Image = X_Image\n batches = int(len(X_Image)/batch_size)\n for batch in range(batches):\n x = X_Image[batch*batch_size:(batch+1)*batch_size,:,:,:]\n y = Y_Image[batch*batch_size:(batch+1)*batch_size]\n yield((x,y))", "def training_data_generation(DATA_DIR, img_height_size, img_width_size, label_list):\r\n \r\n img_ms_files = glob.glob(DATA_DIR + '\\\\Train_MS' + '\\\\Train_*.tif')\r\n img_pan_files = glob.glob(DATA_DIR + '\\\\Train_Pan' + '\\\\Train_*.tif')\r\n polygon_files = glob.glob(DATA_DIR + '\\\\Train_Polygons' + '\\\\Train_*.geojson')\r\n \r\n img_ms_array_list = []\r\n img_pan_array_list = []\r\n mask_array_list = []\r\n \r\n for file in range(len(img_ms_files)):\r\n with rasterio.open(img_ms_files[file]) as f:\r\n metadata = f.profile\r\n img_ms = np.transpose(f.read(tuple(np.arange(metadata['count']) + 1)), [1, 2, 0])\r\n \r\n with rasterio.open(img_pan_files[file]) as g:\r\n metadata_pan = g.profile\r\n img_pan = np.expand_dims(g.read(1), axis = 2)\r\n \r\n ms_to_pan_ratio = metadata['transform'][0] / metadata_pan['transform'][0]\r\n \r\n if (img_height_size % ms_to_pan_ratio) != 0 or (img_width_size % ms_to_pan_ratio) != 0:\r\n raise ValueError('Please make sure that both img_height_size and img_width_size can be divided by {}'.format(int(ms_to_pan_ratio)))\r\n \r\n mask = training_mask_generation(img_pan_files[file], polygon_files[file], labels = label_list)\r\n \r\n img_ms_array, img_pan_array, mask_array = image_clip_to_segment_and_convert(img_ms, img_pan, mask, ms_to_pan_ratio, \r\n img_height_size, img_width_size)\r\n \r\n img_ms_array_list.append(img_ms_array)\r\n img_pan_array_list.append(img_pan_array)\r\n mask_array_list.append(mask_array)\r\n \r\n img_ms_full_array = np.concatenate(img_ms_array_list, axis = 0)\r\n img_pan_full_array = np.concatenate(img_pan_array_list, axis = 0)\r\n mask_full_array = to_categorical(np.concatenate(mask_array_list, axis = 0), num_classes = len(label_list))\r\n \r\n return img_ms_full_array, img_pan_full_array, mask_full_array", "def preprocess_data(self):\n\n self._preprocess_train_data()\n self._preprocess_test_data()", "def load_data(data_dir):\n train_dir = data_dir + '/train'\n valid_dir = data_dir + '/valid'\n test_dir = data_dir + '/test'\n\n # define your transforms for the training, validation, and testing sets\n data_transforms_training = transforms.Compose([\n transforms.RandomRotation(30),\n transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n ])\n\n data_transforms_validation = transforms.Compose([\n transforms.Resize(224),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n ])\n\n data_transforms_test = transforms.Compose([\n transforms.Resize(224),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n ])\n\n # Load the datasets with ImageFolder\n image_datasets_training = datasets.ImageFolder(train_dir, transform=data_transforms_training)\n image_datasets_validation = datasets.ImageFolder(valid_dir, transform=data_transforms_validation)\n image_datasets_test = datasets.ImageFolder(test_dir, transform=data_transforms_test)\n\n # Using the image datasets and the trainforms, define the dataloaders\n dataloaders_training = torch.utils.data.DataLoader(image_datasets_training, shuffle=True, batch_size=128)\n dataloaders_validation = torch.utils.data.DataLoader(image_datasets_validation, shuffle=True, batch_size=128)\n dataloaders_test = torch.utils.data.DataLoader(image_datasets_test, shuffle=True, batch_size=128)\n\n return {\"training_dataloader\": dataloaders_training,\n \"validation_dataloader\": dataloaders_validation,\n \"testing_dataloader\": dataloaders_test,\n \"class_to_idx\": image_datasets_training.class_to_idx}", "def preprocess_train_data(self):\r\n print(\"* Preprocessing training data.\", flush=True)\r\n prep.create_HDF_file(self.C.training_set, is_training_set=True)\r\n\r\n self.print_time_elapsed()", "def split_folder(data_dir, train_pct, val_pct):\n\n random.seed(1)\n\n IMG_SUFFIX = '*_sat.jpg'\n MASK_SUFFIX = '*_msk.png'\n\n glob_imgs = os.path.join(data_dir,IMG_SUFFIX)\n glob_masks = os.path.join(data_dir, MASK_SUFFIX)\n\n img_paths = np.array(sorted(glob.glob(glob_imgs)))\n mask_paths = np.array(sorted(glob.glob(glob_masks)))\n \n num_imgs = len(img_paths)\n index_lst = list(range(num_imgs))\n\n random.shuffle(index_lst)\n\n train_idx_bound = int(train_pct * num_imgs)\n train_imgs = img_paths[index_lst[:train_idx_bound]]\n train_masks = mask_paths[index_lst[:train_idx_bound]]\n\n val_idx_bound = int((train_pct + val_pct) * num_imgs)\n val_imgs = img_paths[index_lst[train_idx_bound: val_idx_bound]]\n val_masks = mask_paths[index_lst[train_idx_bound: val_idx_bound]]\n\n test_imgs = img_paths[index_lst[val_idx_bound:]]\n test_masks = mask_paths[index_lst[val_idx_bound:]]\n\n # Write the lists to their own directories\n copy_list_to_dir(train_imgs, \"train\")\n print(\"Moved images into: train\")\n copy_list_to_dir(train_masks, \"train\")\n print(\"Moved masks into: train\")\n copy_list_to_dir(val_imgs, \"val\")\n print(\"Moved images into: val\")\n copy_list_to_dir(val_masks, \"val\")\n print(\"Moved masks into: val\")\n copy_list_to_dir(test_imgs, \"test\")\n print(\"Moved images into: test\")\n copy_list_to_dir(test_masks, \"test\")\n print(\"Moved masks into: test\")", "def load_data(self):\n # make sure preprocessing is same as preprocessing as the network\n # reduce mean, and divide by a value to do scaling\n self.train_datagen = ImageDataGenerator(\n rescale=1./ 255,\n shear_range=0.05,\n rotation_range=20, # randomly rotate images in the range (degrees, 0 to 180)\n zoom_range=[0.9, 1.1], # Randomly zoom image\n width_shift_range=0.1, # randomly shift images horizontally (fraction of total width)\n height_shift_range=0.1, # randomly shift images vertically (fraction of total height)\n horizontal_flip=True, # randomly flip images\n brightness_range=[0.8, 1.2],\n fill_mode='reflect',\n validation_split=0.2)\n\n self.test_datagen = ImageDataGenerator(rescale=1. / 255)\n\n self.train_generator = self.train_datagen.flow_from_directory(\n self.train_dir,\n target_size=(224, 224),\n shuffle=True,\n batch_size=self.batchsize,\n class_mode='categorical',\n subset=\"training\")\n\n self.validation_generator = self.train_datagen.flow_from_directory(\n self.train_dir,\n target_size=(224, 224),\n shuffle=True,\n batch_size=self.batchsize,\n class_mode='categorical',\n subset=\"validation\")\n\n self.test_generator = self.test_datagen.flow_from_directory(\n self.test_dir,\n target_size=(224, 224),\n shuffle=False,\n batch_size=1,\n class_mode='categorical')", "def image_network_train(learn_data_path):\n\n # data selector ----------\n use_da_data = False\n increase_val = False\n print( \"\\nmode: Use Augmented data: {} | increase validation data: {}\".format(use_da_data, increase_val) )\n\n # First define original train_data only as train_dir\n train_dir = os.path.join(data_dir, \"train\")\n if (use_da_data == True) and (increase_val == False):\n # with_augmented data (no validation increase)\n train_dir = os.path.join(data_dir, \"train_with_aug\")\n validation_dir = os.path.join(data_dir, \"val\") # original validation data\n\n # pair of decreaced train_data and increased validation data\n if (increase_val == True):\n train_dir = os.path.join(data_dir, \"red_train\")\n if (use_da_data == True):\n train_dir = os.path.join(data_dir, \"red_train_with_aug\")\n validation_dir = os.path.join(data_dir, \"validation\")\n\n test_dir = os.path.join(data_dir, \"test\")\n\n print(\"\\ntrain_dir: \", train_dir)\n print(\"validation_dir: \", validation_dir)\n\n\n # calcucate the num of category\n num_category = 0\n for dirpath, dirnames, filenames in os.walk(train_dir):\n for dirname in dirnames:\n num_category += 1\n\n # All images will be resized to 299x299\n image_size = 299\n batch_size = 16\n\n # Rescale all images by 1./255 and apply image augmentation\n train_datagen = keras.preprocessing.image.ImageDataGenerator(rescale=1./255)\n validation_datagen = keras.preprocessing.image.ImageDataGenerator(rescale=1./255)\n test_datagen = keras.preprocessing.image.ImageDataGenerator(rescale=1./255)\n\n # Flow training images in batches of using train_datagen generator\n train_generator = train_datagen.flow_from_directory(\n train_dir, # Source directory for the training images\n target_size=(image_size, image_size),\n batch_size=batch_size,\n class_mode='categorical')\n\n # Flow validation images in batches of 20 using validation_datagen generator\n validation_generator = validation_datagen.flow_from_directory(\n validation_dir, # Source directory for the validation images\n target_size=(image_size, image_size),\n batch_size=batch_size,\n class_mode='categorical')\n\n # Flow validation images in batches of 20 using test_datagen generator\n test_generator = test_datagen.flow_from_directory(\n test_dir, # Source directory for the test images\n target_size=(image_size, image_size),\n batch_size=batch_size,\n class_mode='categorical')\n\n # Create the base model from the pre-trained convnets\n IMG_SHAPE = (image_size, image_size, 3)\n\n # Create the base model from the pre-trained model MobileNet V2\n base_model = keras.applications.xception.Xception(input_shape=IMG_SHAPE, include_top=False, weights='imagenet')\n\n # Freeze the convolutional base\n base_model.trainable = False\n\n # モデル\n model = keras.Sequential([\n base_model,\n keras.layers.GlobalAveragePooling2D(),\n keras.layers.Dense(num_category, activation='softmax')\n ])\n\n # Compile the model\n model.compile(optimizer=keras.optimizers.Adam(lr=0.0001),\n loss='categorical_crossentropy',\n metrics=['accuracy'])\n\n # early stopping\n es = keras.callbacks.EarlyStopping(monitor='val_loss', patience=5, restore_best_weights=True)\n\n model.summary()\n\n # 更新される重みの数\n print('after', len(model.trainable_weights))\n\n # Train the model\n epochs = 30\n steps_per_epoch = train_generator.n // batch_size\n validation_steps = validation_generator.n // batch_size\n test_steps = test_generator.n // batch_size\n\n history = model.fit_generator(train_generator,\n steps_per_epoch = steps_per_epoch,\n epochs=epochs,\n workers=4,\n validation_data=validation_generator,\n validation_steps=validation_steps,\n callbacks=[es],\n class_weight={0:1.0, 1:0.4})\n\n loss, acc = model.evaluate_generator(validation_generator, steps=validation_steps)\n print('val loss: {}, val acc: {}'.format(loss, acc))\n\n # Fine tuning\n # Un-freeze the top layers of the model\n base_model.trainable = True\n\n # The nums of layers are in the base model\n print(\"Number of layers in the base model: \", len(base_model.layers))\n\n # Fine tune from this layer onwards\n fine_tune_at = 108\n\n # Freeze all the layers before the `fine_tune_at` layer\n for layer in base_model.layers[:fine_tune_at]:\n layer.trainable = False\n\n # Compile the model using a much-lower training rate\n model.compile(optimizer = keras.optimizers.Adam(lr=2e-5),\n loss='categorical_crossentropy',\n metrics=['accuracy'])\n\n model.summary()\n\n # 更新される重みの数\n print('after Fine tune', len(model.trainable_weights))\n\n # Continue Train the model\n history_fine = model.fit_generator(train_generator,\n steps_per_epoch = steps_per_epoch,\n epochs=epochs,\n workers=4,\n validation_data=validation_generator,\n validation_steps=validation_steps,\n callbacks=[es],\n class_weight={0:1.0, 1:0.4})\n\n\n # print(history_fine.history)\n model_val_acc = history_fine.history['val_accuracy'][-1]\n print('val_acc: ', model_val_acc)\n\n # save model into hdf5 file ----------\n model.save(learn_data_path + '/shen_model.h5')\n\n loss, acc = model.evaluate_generator(validation_generator, steps=validation_steps)\n print('val loss: {}, val acc: {}'.format(loss, acc))\n\n loss, acc = model.evaluate_generator(test_generator, steps=test_steps)\n print('Test loss: {}, Test acc: {}'.format(loss, acc))", "def __init__(self, t_train_data_dir, t_test_data_dir, t_batch_size):\n\n self.classes = ['A', 'B', 'C', 'D', \"del\", 'E', 'F', 'G', 'H', 'I', 'J']\n self.classes = self.classes + ['K', 'L', 'M', 'N', \"nothing\", 'O', 'P', 'Q', 'R']\n self.classes = self.classes + ['S', \"space\", 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']\n\n self.image_height, self.image_width = 64,64\n self.batch_size = t_batch_size\n self.test_data_dir = t_test_data_dir\n self.train_data_dir = t_train_data_dir\n\n # Data generators, to choose from either non-transformed or transformed data respectively\n self.regular_data_generator = keras.preprocessing.image.ImageDataGenerator(samplewise_center=True,\n samplewise_std_normalization=True, validation_split=0.1)\n self.transformed_data_generator = keras.preprocessing.image.ImageDataGenerator(samplewise_center=True,\n samplewise_std_normalization=True, validation_split=0.1, rotation_range=40,\n width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2, zoom_range=0.5,\n horizontal_flip=True, fill_mode=\"nearest\")\n\n # Data sets\n self.training_data = self.transformed_data_generator.flow_from_directory(self.train_data_dir,\n target_size=(self.image_height, self.image_width), batch_size=64, shuffle=True,\n classes=self.classes, class_mode=\"categorical\", color_mode=\"rgb\", seed=42, subset=\"training\")\n self.validation_data = self.transformed_data_generator.flow_from_directory(self.train_data_dir,\n target_size=(self.image_height, self.image_width), batch_size=64, shuffle=True,\n classes=self.classes, class_mode=\"categorical\", color_mode=\"rgb\", seed=42, subset=\"validation\")\n self.testing_data = self.regular_data_generator.flow_from_directory(self.test_data_dir,\n target_size=(self.image_height, self.image_width), shuffle=False, batch_size=1)\n print(\"Finished processing data\")", "def persist_resized_test_image_and_label(self, answer_path):\n print('writing files on new data')\n n_partition = 3\n # read the images\n images_all, names_all = self.scale_images(self.input_root_dir, image_name_flag=True)\n nb_images = len(images_all)\n # read the answer file to a dict\n answer_map = map(str.split, open(answer_path))\n name_label_dict = dict()\n for i in range(1, len(answer_map)):\n name_label_dict[answer_map[i][0]] = answer_map[i][1]\n\n images = []\n labels = []\n for name in name_label_dict.keys():\n if name in names_all:\n idx = names_all.index(name)\n images.append(images_all[idx])\n labels.append(int(name_label_dict[name]))\n\n data = zip(images, labels)\n random.shuffle(data)\n train_data, validation_data = train_test_split(data, test_size=0.1, random_state=35)\n train_images, train_labels = zip(*train_data)\n validation_images, validation_labels = zip(*validation_data)\n# train_images = images\n# train_labels = labels\n train_batch_length = len(train_images) / n_partition\n validation_batch_length = len(validation_images) / n_partition\n \n \n# while 1:\n# i = random.randint(0, len(labels)-1)\n# plt.imshow(images[i])\n# plt.title(self.reverse_label_map[labels[i]])\n n_shift = 30\n for partition_idx in range(n_partition):\n if(partition_idx < n_partition - 1):\n write_data(os.path.join(self.output_root_dir, ('%s_cropped_224_224_ndarray_%d.pkl') % ('train', partition_idx + n_shift)), \n [train_images[partition_idx * train_batch_length : (partition_idx + 1) * train_batch_length], \n train_labels[partition_idx * train_batch_length : (partition_idx + 1) * train_batch_length]])\n write_data(os.path.join(self.output_root_dir, ('%s_cropped_224_224_ndarray_%d.pkl') % ('validation', partition_idx + n_shift)), \n [validation_images[partition_idx * validation_batch_length : (partition_idx + 1) * validation_batch_length], \n validation_labels[partition_idx * validation_batch_length : (partition_idx + 1) * validation_batch_length]])\n else:\n print('last partition')\n write_data(os.path.join(self.output_root_dir, ('%s_cropped_224_224_ndarray_%d.pkl') % ('train', partition_idx + n_shift)), \n [train_images[partition_idx * train_batch_length:], \n train_labels[partition_idx * train_batch_length:]])\n write_data(os.path.join(self.output_root_dir, ('%s_cropped_224_224_ndarray_%d.pkl') % ('validation', partition_idx + n_shift)), \n [validation_images[partition_idx * validation_batch_length:], \n validation_labels[partition_idx * validation_batch_length:]])" ]
[ "0.68580747", "0.68126184", "0.6661624", "0.6622211", "0.6482098", "0.6411102", "0.64000064", "0.6395083", "0.6322259", "0.62958413", "0.62045133", "0.61812246", "0.6141117", "0.61333716", "0.6103867", "0.60934895", "0.6093341", "0.60870826", "0.6078162", "0.60575724", "0.6049152", "0.6021651", "0.6013856", "0.5991702", "0.5949336", "0.5945865", "0.59323436", "0.593075", "0.5928614", "0.59282506" ]
0.7223868
0
Executes the Daikon binary. Raises ValueError If no filenames are provided as input. FileNotFoundError If a given input file cannot be found. RuntimeError If the image for the tool has not been installed.
def __call__(self, *filenames: str) -> str: if not self.is_installed(): message = f'image for tool is not installed [{self.IMAGE}]' raise RuntimeError(message) logger.debug(f"running Daikon on files: {', '.join(filenames)}") if not filenames: raise ValueError('expected one or more filenames as input') # ensure that all paths are absolute filenames = tuple(os.path.abspath(filename) for filename in filenames) for filename in filenames: if not os.path.isfile(filename): raise FileNotFoundError(filename) ctr_dir = '/tmp/.specminers' host_to_ctr_fn = {fn: os.path.join(ctr_dir, os.path.basename(fn)) for fn in filenames} ctr_filenames = [fn for fn in host_to_ctr_fn.values()] volumes = {fn_host: {'bind': fn_ctr, 'mode': 'ro'} for fn_host, fn_ctr in host_to_ctr_fn.items()} # launch container with contextlib.ExitStack() as stack: container = self.client.provision(self.IMAGE, volumes=volumes) shell = container.shell('/bin/sh') stack.callback(container.remove) # generate invariants command = ('java daikon.Daikon ' '--no_show_progress --no_text_output --noversion ' '-o /tmp/mined.inv.tgz ' f"{' '.join(shlex.quote(f) for f in ctr_filenames)}") shell.check_call(command) # read invariants command = 'java daikon.PrintInvariants /tmp/mined.inv.tgz' output = shell.check_output(command) logger.debug(f"daikon output:\n{output}") return output
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def main():\n parser = argparse.ArgumentParser()\n parser.add_argument('-d', '--debug', action='store_true',\n help='Start debugging. Image MUST be an ELF file.')\n parser.add_argument('-t', '--toolchain', type=is_valid_path,\n help='Tool chain installation path.')\n parser.set_defaults(addr='addr_x86')\n group = parser.add_mutually_exclusive_group()\n group.add_argument('-s', '--sensor', action='store_const',\n dest='addr', const='addr_arc',\n help='Sensor Subsystem Application \\\n (only valid for Quark SE).')\n group.add_argument('-r', '--rom', action='store_const',\n dest='addr', const='addr_rom',\n help='Flash ROM (Bootloader - 1st stage).')\n group.add_argument('-u', '--rom-2nd', action='store_const',\n dest='addr', const='addr_rom_2nd',\n help='Flash 2nd Stage ROM ' \\\n '(Bootloader - 2nd stage, Quark SE only).')\n parser.add_argument('board', metavar='BOARD',\n choices=['d2000_dev', 'quarkse_dev'],\n help='Board name (d2000_dev or quarkse_dev).')\n parser.add_argument('inputfile', type=is_valid_file, metavar='INFILE',\n help='Image name')\n args = parser.parse_args()\n\n # Start looking for the tool chain path.\n tool_chain = get_tool_chain_path(args.toolchain)\n # From the tool chain retrieve common paths.\n common_paths = get_common_paths(tool_chain)\n\n if args.debug:\n cpu = get_cpu(args.board, args.addr)\n run_debug(cpu, common_paths, tool_chain, args.inputfile)\n else:\n run_flash(args.board, args.addr, common_paths, args.inputfile)", "def execute():\n args = parse()\n \n image = args.image\n \n # Switch on the options\n if args.test:\n unittest()\n elif args.grade:\n grade(image)\n elif args.encode:\n encode(image)\n else:\n launchgui(image)", "def main(argv=sys.argv[1:]): # pylint: disable=dangerous-default-value\n parser = argparse.ArgumentParser()\n image = argparse.ArgumentParser()\n parser.add_argument(\"action\", choices=[\"image\", \"sources\"])\n\n image.add_argument('-d', '--download',\n help='Download the result to a file.',\n default=False, action=\"store_true\")\n image.add_argument('-f', '--file',\n help=\"Filename to download to.\",\n default=lambda x: x.split(\"/\")[-1])\n image.add_argument('source', help=\"Image source to use.\")\n image.add_argument('query', help=\"Tags to use during search.\",\n default='', nargs=\"*\")\n\n args = parser.parse_args(argv)\n\n if args.action == \"sources\":\n sources = \"\\n\".join(\"\\n\".join(v for v in source) for source in\n nsfw_dl.SOURCES.values())\n print(sources)\n\n else:\n args = image.parse_args(argv[1:])\n download(args.source, args.query, args.file, args.download)", "def run_built_executable(self, name, *args, **kw):\n raise NotImplementedError", "def execute(args, **kwargs):\n p = set_options()\n a = p.parse_args(args)\n # logging.info(str(a))\n\n ifiles = ImageFiles(a)\n\n if a.info:\n ifiles.describe()\n else:\n ifiles.write()", "def execute_tool(description, *args):\n command_line = list(args) + files_and_directories\n click.echo(f\"{description}: {' '.join(command_line)}\")\n rv = call(command_line)\n if rv != 0:\n exit(rv)", "def exec_from_inputfile(args):\n args.path = os.path.abspath(args.path)\n if not check(args.path, 'e'):\n clean_up(args.debug, args.folder, args.action, 1)\n\n logger.info(\"You are using the inputfile. All parameters other than folder, API key and debug will be ignored\")\n try:\n startargs = readconfig(args.path)\n makeconfig(*startargs[:13], date=args.today, folder=args.folder)\n\n r = Run('n', args.folder, args.debug)\n r.start()\n\n except TypeError:\n logger.critical(\"Wrong data format. Check the documentation\")\n clean_up(args.debug, args.folder, args.action, 1)", "def main(args):\n args = parse_args(args)\n setup_logging(args.loglevel)\n _logger.debug(\"Starting crazy calculations...\")\n createlookuptable(args.imagefolder)\n _logger.info(\"Script ends here\")", "def run(pyi_args=None, pyi_config=None):\n check_requirements()\n\n import PyInstaller.building.makespec\n import PyInstaller.building.build_main\n import PyInstaller.log\n\n try:\n parser = argparse.ArgumentParser(formatter_class=_SmartFormatter)\n __add_options(parser)\n PyInstaller.building.makespec.__add_options(parser)\n PyInstaller.building.build_main.__add_options(parser)\n PyInstaller.log.__add_options(parser)\n parser.add_argument('filenames', metavar='scriptname', nargs='+',\n help=(\"name of scriptfiles to be processed or \"\n \"exactly one .spec-file. If a .spec-file is \"\n \"specified, most options are unnecessary \"\n \"and are ignored.\"))\n\n args = parser.parse_args(pyi_args)\n PyInstaller.log.__process_options(parser, args)\n\n # Print PyInstaller version, Python version and platform\n # as the first line to stdout.\n # This helps identify PyInstaller, Python and platform version\n # when users report issues.\n logger.info('PyInstaller: %s' % __version__)\n logger.info('Python: %s%s', platform.python_version(),\n \" (conda)\" if is_conda else \"\")\n logger.info('Platform: %s' % platform.platform())\n\n # Skip creating .spec when .spec file is supplied\n if args.filenames[0].endswith('.spec'):\n spec_file = args.filenames[0]\n else:\n spec_file = run_makespec(**vars(args))\n\n run_build(pyi_config, spec_file, **vars(args))\n\n except KeyboardInterrupt:\n raise SystemExit(\"Aborted by user request.\")\n except RecursionError:\n from . import _recursion_to_deep_message\n _recursion_to_deep_message.raise_with_msg()", "def __main__() :\n try :\n poly = Polyhedre(sys.argv[1])\n \n name = sys.argv[2]\n \n createAllFiles(poly, name)\n\n createAllImageFiles(poly, name)\n \n except FileNotFoundError :\n print(\"Use an existing file\")", "def run_file(self, user_input):\n # Extract the important information\n self.path, self.name = self.extractor.extract_program_information(user_input)\n\n # Determine what language the program is\n program_type = self.determine_program_type(path, name)\n\n # If the file is python, run it the specific way\n # @TODO: Make it work without shell=True\n if program_type == \"python\":\n subprocess.Popen(\"python \" + self.path + self.name, shell=True)", "def __instructions_runfile(self):\n\n pkg = os.path.basename(self.__runfile)\n\n install_cmds = [\n 'sh ./{} --nox11 -- -noprompt -targetpath={}'.format(\n pkg, self.__prefix)\n ]\n\n # Commands needed to predeploy target-specific files. When\n # connecting through the GUI on another machine to the\n # container, this removes the need to copy the files over.\n install_cmds += [\n 'mkdir -p /tmp/var/target',\n 'ln -sf {}/target/* /tmp/var/target'.format(self.__prefix),\n 'ln -sf {}/sections /tmp/var/'.format(self.__prefix),\n 'chmod -R a+w /tmp/var'\n ]\n\n kwargs = {}\n if self.__runfile.strip().startswith(('http://', 'https://')):\n kwargs['url'] = self.__runfile\n else:\n kwargs['package'] = self.__runfile\n\n self.__bb = generic_build(\n annotations={'runfile': pkg},\n base_annotation=self.__class__.__name__,\n comment = False,\n devel_environment={'PATH': '{}:$PATH'.format(self.__prefix)},\n directory=self.__wd,\n install=install_cmds,\n unpack=False,\n wd=self.__wd,\n **kwargs\n )\n\n self += comment('NVIDIA Nsight Compute {}'.format(pkg), reformat=False)\n self += packages(ospackages=self.__ospackages)\n self += self.__bb\n self += environment(variables=self.environment_variables)", "def do_create_dot_file(self, arg):\n try:\n\n # name = input(\"Enter diagram image name: \")\n self.runner.make_dot_file()\n except ImportError as e:\n print(e)\n except():\n print(\"Error!!\")", "def main(self):\n try:\n config_provider = ConfigurationProvider(MaskReplacer(), DirectorySelector())\n parser = CommandParser(\n config_provider,\n RubyRipperCdRipper(config_provider),\n DiscogsMetadataService(),\n GenreSelector())\n commands = parser.from_args(self._get_arguments())\n for command in commands:\n command.validate()\n command.execute()\n return 0\n except Exception as ex:\n # This will be replaced with proper logging output.\n sys.stderr.write('{0}\\n'.format(ex.message))\n sys.stderr.write('{0}\\n'.format(traceback.format_exc()))\n return 255", "def do_exec(self, arg):\n self.run_file(arg['path'])", "def main():\n\n args = _parse_arguments()\n path = _get_dragons_input_test_path()\n create_test_folder_if_does_not_exist(path)\n download_non_existing_test_files(path, args.list_of_files)", "def run(self, name, image, entrypoint, command):\n return 0, ''", "def executable():\n\n if len(sys.argv) == 1:\n arguments.get_help()\n sys.exit('\\nGive me something to do and I will do it\\n')\n else:\n # Parse the Arguments that have been provided\n args = arguments.get_args()\n\n # Load The System Logger\n log = logger.load_in(log_level=args.get('log_level', 'info'))\n log.debug('Used Arguments %s', args)\n const(log_method=log)\n\n # Begin Work\n start(set_args=args)", "def main(self):\n try:\n self.parse_args()\n self.run()\n return 0\n except AnalysisBackendError as e:\n L.error(e)\n return 1", "def runTool(self, filename, expected_out, args):\n\n input_path = os.path.join(self.inputs_dir, filename)\n return_value, actual_output = create_subprocess(self.executable_binary, args + [input_path] + ['--'])\n actual_output = actual_output.decode('utf-8')\n\n self.assertEqual(return_value, 0)\n self.evaluate(expected_out, actual_output, command=f'{[self.executable_binary] + args} {filename}')", "def main():\n usage = \"usage: %prog [options] input: BioC File (args[0]); Output Directory for the (picture) .svg file.\"\n parser = OptionParser(version='%prog 0.99', usage=usage)\n\n parser.add_option('-l', '--logfile', dest='logfilename',\n help='write log to FILE', metavar='FILE')\n parser.add_option('-q', '--quiet',\n action='store_true', dest='quiet', default=False,\n help='do not print status messages to stderr')\n parser.add_option('-d', '--debug',\n action='store_true', dest='debug', default=False,\n help='print debug information')\n\n\n\n (options, args) = parser.parse_args()\n\n if options.debug: print >> sys.stderr, '# Starting processing'\n\n process(options=options,args=args)\n\n\n\n\n sys.exit(0) # Everything went ok!", "def main():\n\n parser = argparse.ArgumentParser(prog='Build', description='Python script for building apps for Pyinstaller')\n # Flag arguments\n parser.add_argument('--version', action='version', version='%(prog)s 1.0.0')\n parser.add_argument('--clean', '-c', action='store_true', default=False, help='Clean build before re-building.')\n parser.add_argument('--portable', '-p', action='store_true', default=False, help='Build with portable python (windows)')\n parser.add_argument('name', default=None, help='Name of app')\n inputs = parser.parse_args()\n if _PLATFORM == \"osx\":\n args = Args(\"Rummage.py\", inputs.name, True, inputs.clean, \".app\", abspath(\"_icons/rummage.icns\"))\n elif _PLATFORM == \"windows\":\n args = Args(\"Rummage.py\", inputs.name, True, inputs.clean, \".exe\", abspath(\"_icons\\\\rummage.ico\"), inputs.portable)\n else:\n args = Args(\n \"Rummage.py\", inputs.name, True, inputs.clean, \"\",\n imports=[\n \"gobject\", \"glib\", \"glib._glib\", \"glib.option\", \"object.constants\",\n \"gobject._gobject\", \"gobject.propertyhelper\", \"gtk\", \"gtk._gtk\"\n ]\n )\n\n # Parse options\n build_params = BuildParams()\n err = parse_options(args, build_params)\n\n # Build executable\n if not err:\n err = build(build_params)\n\n return err", "def run(self, args: List[str], outputs: List[PipelineOutput]=[], inputs: List[PipelineInput]=[]) -> Tuple[PipelineOutput]:\n\n preopen_directories=set()\n for index, input_ in enumerate(inputs):\n if input_.type == InterfaceTypes.TextFile or input_.type == InterfaceTypes.BinaryFile:\n preopen_directories.add(str(PurePosixPath(input_.data.path).parent))\n for index, output in enumerate(outputs):\n if output.type == InterfaceTypes.TextFile or output.type == InterfaceTypes.BinaryFile:\n preopen_directories.add(str(PurePosixPath(output.data.path).parent))\n preopen_directories = list(preopen_directories)\n\n ri = RunInstance(self.engine, self.linker, self.module, args, preopen_directories)\n\n for index, input_ in enumerate(inputs):\n if input_.type == InterfaceTypes.TextStream:\n data_array = input_.data.data.encode()\n array_ptr = ri.set_input_array(data_array, index, 0)\n data_json = { \"size\": len(data_array), \"data\": f\"data:application/vnd.itk.address,0:{array_ptr}\" }\n ri.set_input_json(data_json, index)\n elif input_.type == InterfaceTypes.BinaryStream:\n data_array = input_.data.data\n array_ptr = ri.set_input_array(data_array, index, 0)\n data_json = { \"size\": len(data_array), \"data\": f\"data:application/vnd.itk.address,0:{array_ptr}\" }\n ri.set_input_json(data_json, index)\n elif input_.type == InterfaceTypes.TextFile:\n pass\n elif input_.type == InterfaceTypes.BinaryFile:\n pass\n elif input_.type == InterfaceTypes.Image:\n image = input_.data\n mv = bytes(image.data.data)\n data_ptr = ri.set_input_array(mv, index, 0)\n dv = bytes(image.direction.data)\n direction_ptr = ri.set_input_array(dv, index, 1)\n image_json = {\n \"imageType\": asdict(image.imageType),\n \"name\": image.name,\n \"origin\": image.origin,\n \"spacing\": image.spacing,\n \"direction\": f\"data:application/vnd.itk.address,0:{direction_ptr}\",\n \"size\": image.size,\n \"data\": f\"data:application/vnd.itk.address,0:{data_ptr}\"\n }\n ri.set_input_json(image_json, index)\n elif input_.type == InterfaceTypes.Mesh:\n mesh = input_.data\n if mesh.numberOfPoints:\n pv = bytes(mesh.points)\n else:\n pv = bytes([])\n points_ptr = ri.set_input_array(pv, index, 0)\n if mesh.numberOfCells:\n cv = bytes(mesh.cells)\n else:\n cv = bytes([])\n cells_ptr = ri.set_input_array(cv, index, 1)\n if mesh.numberOfPointPixels:\n pdv = bytes(mesh.pointData)\n else:\n pdv = bytes([])\n point_data_ptr = ri.set_input_array(pdv, index, 2)\n if mesh.numberOfCellPixels:\n cdv = bytes(mesh.cellData)\n else:\n cdv = bytes([])\n cell_data_ptr = ri.set_input_array(cdv, index, 3)\n mesh_json = {\n \"meshType\": asdict(mesh.meshType),\n \"name\": mesh.name,\n\n \"numberOfPoints\": mesh.numberOfPoints,\n \"points\": f\"data:application/vnd.itk.address,0:{points_ptr}\",\n\n \"numberOfCells\": mesh.numberOfCells,\n \"cells\": f\"data:application/vnd.itk.address,0:{cells_ptr}\",\n \"cellBufferSize\": mesh.cellBufferSize,\n\n \"numberOfPointPixels\": mesh.numberOfPointPixels,\n \"pointData\": f\"data:application/vnd.itk.address,0:{point_data_ptr}\",\n\n \"numberOfCellPixels\": mesh.numberOfCellPixels,\n \"cellData\": f\"data:application/vnd.itk.address,0:{cell_data_ptr}\",\n }\n ri.set_input_json(mesh_json, index)\n elif input_.type == InterfaceTypes.PolyData:\n polydata = input_.data\n if polydata.numberOfPoints:\n pv = bytes(polydata.points)\n else:\n pv = bytes([])\n points_ptr = ri.set_input_array(pv, index, 0)\n\n if polydata.verticesBufferSize:\n pv = bytes(polydata.vertices)\n else:\n pv = bytes([])\n vertices_ptr = ri.set_input_array(pv, index, 1)\n\n if polydata.linesBufferSize:\n pv = bytes(polydata.lines)\n else:\n pv = bytes([])\n lines_ptr = ri.set_input_array(pv, index, 2)\n\n if polydata.polygonsBufferSize:\n pv = bytes(polydata.polygons)\n else:\n pv = bytes([])\n polygons_ptr = ri.set_input_array(pv, index, 3)\n\n if polydata.triangleStripsBufferSize:\n pv = bytes(polydata.triangleStrips)\n else:\n pv = bytes([])\n triangleStrips_ptr = ri.set_input_array(pv, index, 4)\n\n if polydata.numberOfPointPixels:\n pv = bytes(polydata.pointData)\n else:\n pv = bytes([])\n pointData_ptr = ri.set_input_array(pv, index, 5)\n\n if polydata.numberOfCellPixels:\n pv = bytes(polydata.cellData)\n else:\n pv = bytes([])\n cellData_ptr = ri.set_input_array(pv, index, 6)\n\n polydata_json = {\n \"polyDataType\": asdict(polydata.polyDataType),\n \"name\": polydata.name,\n\n \"numberOfPoints\": polydata.numberOfPoints,\n \"points\": f\"data:application/vnd.itk.address,0:{points_ptr}\",\n\n \"verticesBufferSize\": polydata.verticesBufferSize,\n \"vertices\": f\"data:application/vnd.itk.address,0:{vertices_ptr}\",\n\n \"linesBufferSize\": polydata.linesBufferSize,\n \"lines\": f\"data:application/vnd.itk.address,0:{lines_ptr}\",\n\n \"polygonsBufferSize\": polydata.polygonsBufferSize,\n \"polygons\": f\"data:application/vnd.itk.address,0:{polygons_ptr}\",\n\n \"triangleStripsBufferSize\": polydata.triangleStripsBufferSize,\n \"triangleStrips\": f\"data:application/vnd.itk.address,0:{triangleStrips_ptr}\",\n\n \"numberOfPointPixels\": polydata.numberOfPointPixels,\n \"pointData\": f\"data:application/vnd.itk.address,0:{pointData_ptr}\",\n\n \"numberOfCellPixels\": polydata.numberOfCellPixels,\n \"cellData\": f\"data:application/vnd.itk.address,0:{cellData_ptr}\"\n }\n ri.set_input_json(polydata_json, index)\n elif input_.type == InterfaceTypes.JsonCompatible:\n data_array = json.dumps(input_.data).encode()\n array_ptr = ri.set_input_array(data_array, index, 0)\n data_json = { \"size\": len(data_array), \"data\": f\"data:application/vnd.itk.address,0:{array_ptr}\" }\n ri.set_input_json(data_json, index)\n else:\n raise ValueError(f'Unexpected/not yet supported input.type {input_.type}')\n\n return_code = ri.delayed_start()\n\n populated_outputs: List[PipelineOutput] = []\n if len(outputs) and return_code == 0:\n for index, output in enumerate(outputs):\n output_data = None\n if output.type == InterfaceTypes.TextStream:\n data_ptr = ri.get_output_array_address(0, index, 0)\n data_size = ri.get_output_array_size(0, index, 0)\n data_array = ri.wasmtime_lift(data_ptr, data_size)\n output_data = PipelineOutput(InterfaceTypes.TextStream, TextStream(data_array.decode()))\n elif output.type == InterfaceTypes.BinaryStream:\n data_ptr = ri.get_output_array_address(0, index, 0)\n data_size = ri.get_output_array_size(0, index, 0)\n data_array = ri.wasmtime_lift(data_ptr, data_size)\n output_data = PipelineOutput(InterfaceTypes.BinaryStream, BinaryStream(data_array))\n elif output.type == InterfaceTypes.TextFile:\n output_data = PipelineOutput(InterfaceTypes.TextFile, TextFile(output.data.path))\n elif output.type == InterfaceTypes.BinaryFile:\n output_data = PipelineOutput(InterfaceTypes.BinaryFile, BinaryFile(output.data.path))\n elif output.type == InterfaceTypes.Image:\n image_json = ri.get_output_json(index)\n\n image = Image(**image_json)\n\n data_ptr = ri.get_output_array_address(0, index, 0)\n data_size = ri.get_output_array_size(0, index, 0)\n data_array = _to_numpy_array(image.imageType.componentType, ri.wasmtime_lift(data_ptr, data_size))\n shape = list(image.size)[::-1]\n if image.imageType.components > 1:\n shape.append(image.imageType.components)\n image.data = data_array.reshape(tuple(shape))\n\n direction_ptr = ri.get_output_array_address(0, index, 1)\n direction_size = ri.get_output_array_size(0, index, 1)\n direction_array = _to_numpy_array(FloatTypes.Float64, ri.wasmtime_lift(direction_ptr, direction_size))\n dimension = image.imageType.dimension\n direction_array.shape = (dimension, dimension)\n image.direction = direction_array\n\n output_data = PipelineOutput(InterfaceTypes.Image, image)\n elif output.type == InterfaceTypes.Mesh:\n mesh_json = ri.get_output_json(index)\n mesh = Mesh(**mesh_json)\n\n if mesh.numberOfPoints > 0:\n data_ptr = ri.get_output_array_address(0, index, 0)\n data_size = ri.get_output_array_size(0, index, 0)\n mesh.points = _to_numpy_array(mesh.meshType.pointComponentType, ri.wasmtime_lift(data_ptr, data_size))\n else:\n mesh.points = _to_numpy_array(mesh.meshType.pointComponentType, bytes([]))\n\n if mesh.numberOfCells > 0:\n data_ptr = ri.get_output_array_address(0, index, 1)\n data_size = ri.get_output_array_size(0, index, 1)\n mesh.cells = _to_numpy_array(mesh.meshType.cellComponentType, ri.wasmtime_lift(data_ptr, data_size))\n else:\n mesh.cells = _to_numpy_array(mesh.meshType.cellComponentType, bytes([]))\n if mesh.numberOfPointPixels > 0:\n data_ptr = ri.get_output_array_address(0, index, 2)\n data_size = ri.get_output_array_size(0, index, 2)\n mesh.pointData = _to_numpy_array(mesh.meshType.pointPixelComponentType, ri.wasmtime_lift(data_ptr, data_size))\n else:\n mesh.pointData = _to_numpy_array(mesh.meshType.pointPixelComponentType, bytes([]))\n\n if mesh.numberOfCellPixels > 0:\n data_ptr = ri.get_output_array_address(0, index, 3)\n data_size = ri.get_output_array_size(0, index, 3)\n mesh.cellData = _to_numpy_array(mesh.meshType.cellPixelComponentType, ri.wasmtime_lift(data_ptr, data_size))\n else:\n mesh.cellData = _to_numpy_array(mesh.meshType.cellPixelComponentType, bytes([]))\n\n output_data = PipelineOutput(InterfaceTypes.Mesh, mesh)\n elif output.type == InterfaceTypes.PolyData:\n polydata_json = ri.get_output_json(index)\n polydata = PolyData(**polydata_json)\n\n if polydata.numberOfPoints > 0:\n data_ptr = ri.get_output_array_address(0, index, 0)\n data_size = ri.get_output_array_size(0, index, 0)\n polydata.points = _to_numpy_array(FloatTypes.Float32, ri.wasmtime_lift(data_ptr, data_size))\n else:\n polydata.points = _to_numpy_array(FloatTypes.Float32, bytes([]))\n\n if polydata.verticesBufferSize > 0:\n data_ptr = ri.get_output_array_address(0, index, 1)\n data_size = ri.get_output_array_size(0, index, 1)\n polydata.vertices = _to_numpy_array(IntTypes.UInt32, ri.wasmtime_lift(data_ptr, data_size))\n else:\n polydata.vertices = _to_numpy_array(IntTypes.UInt32, bytes([]))\n\n if polydata.linesBufferSize > 0:\n data_ptr = ri.get_output_array_address(0, index, 2)\n data_size = ri.get_output_array_size(0, index, 2)\n polydata.lines = _to_numpy_array(IntTypes.UInt32, ri.wasmtime_lift(data_ptr, data_size))\n else:\n polydata.lines = _to_numpy_array(IntTypes.UInt32, bytes([]))\n\n if polydata.polygonsBufferSize > 0:\n data_ptr = ri.get_output_array_address(0, index, 3)\n data_size = ri.get_output_array_size(0, index, 3)\n polydata.polygons = _to_numpy_array(IntTypes.UInt32, ri.wasmtime_lift(data_ptr, data_size))\n else:\n polydata.polygons = _to_numpy_array(IntTypes.UInt32, bytes([]))\n\n if polydata.triangleStripsBufferSize > 0:\n data_ptr = ri.get_output_array_address(0, index, 4)\n data_size = ri.get_output_array_size(0, index, 4)\n polydata.triangleStrips = _to_numpy_array(IntTypes.UInt32, ri.wasmtime_lift(data_ptr, data_size))\n else:\n polydata.triangleStrips = _to_numpy_array(IntTypes.UInt32, bytes([]))\n\n if polydata.numberOfPointPixels > 0:\n data_ptr = ri.get_output_array_address(0, index, 5)\n data_size = ri.get_output_array_size(0, index, 5)\n polydata.pointData = _to_numpy_array(polydata.polyDataType.pointPixelComponentType, ri.wasmtime_lift(data_ptr, data_size))\n else:\n polydata.triangleStrips = _to_numpy_array(polydata.polyDataType.pointPixelComponentType, bytes([]))\n\n if polydata.numberOfCellPixels > 0:\n data_ptr = ri.get_output_array_address(0, index, 6)\n data_size = ri.get_output_array_size(0, index, 6)\n polydata.cellData = _to_numpy_array(polydata.polyDataType.cellPixelComponentType, ri.wasmtime_lift(data_ptr, data_size))\n else:\n polydata.triangleStrips = _to_numpy_array(polydata.polyDataType.cellPixelComponentType, bytes([]))\n\n output_data = PipelineOutput(InterfaceTypes.PolyData, polydata)\n elif output.type == InterfaceTypes.JsonCompatible:\n data_ptr = ri.get_output_array_address(0, index, 0)\n data_size = ri.get_output_array_size(0, index, 0)\n data_array = ri.wasmtime_lift(data_ptr, data_size)\n output_data = PipelineOutput(InterfaceTypes.JsonCompatible, json.loads(data_array.decode()))\n else:\n raise ValueError(f'Unexpected/not yet supported output.type {output.type}')\n\n populated_outputs.append(output_data)\n\n ri.delayed_exit(return_code)\n\n # Should we be returning the return_code?\n return tuple(populated_outputs)", "def execute_live(args):\n logger.debug('Starting analysis...')\n # create the working directory\n setup()\n # create a layer object to bundle package metadata into\n layer = ImageLayer(\"\")\n # see if there is an os-release file at the mount point\n layer.os_guess = single_layer.find_os_release(args.live)\n # create a Prereqs object to store requirements to inventory\n prereqs = core.Prereqs()\n prereqs.host_path = os.path.abspath(args.live)\n # Find a shell that may exist in the layer\n prereqs.fs_shell = dcom.find_shell(prereqs.host_path)\n # Find the host's shell\n prereqs.host_shell = host.check_shell()\n # collect metadata into the layer object\n fill_packages(layer, prereqs)\n # report out the packages\n report.report_layer(layer, args)", "def run(filename, verbose, debug):\n pass", "def main():\n file_requested = obtain_filename()\n process_command(file_requested)", "def main(args):\n # Generate detectron2 config from command line arguments.\n cfg = get_cfg()\n cfg.merge_from_file(args.config_file)\n cfg.merge_from_list(args.opts)\n\n # The configuration file should not contain any datasets. They are configured\n # from command line arguments instead.\n if len(cfg.DATASETS.TRAIN) > 0 or len(cfg.DATASETS.TEST) > 0:\n logging.error(\"Please set DATASETS.TRAIN = () and DATASETS.TEST = ().\")\n sys.exit(1)\n cfg.DATASETS.TRAIN = (TRAIN_SPLIT_NAME, )\n cfg.DATASETS.TEST = (VALID_SPLIT_NAME, )\n\n cfg.freeze()\n default_setup(cfg, args)\n\n # Register synthetic sign datasets.\n if args.image_width is not None or args.image_height is not None:\n if args.image_width is None or args.image_height is None:\n logging.error(\n \"Please specify both, image-width and image-height (or none).\")\n sys.exit(1)\n image_shape = args.image_height, args.image_width\n else:\n image_shape = None\n\n register_synthetic_signs(args.train_csv,\n args.label_map,\n cfg,\n name=TRAIN_SPLIT_NAME,\n image_shape=image_shape)\n if args.valid_csv is not None:\n register_synthetic_signs(args.valid_csv,\n args.label_map,\n cfg,\n name=VALID_SPLIT_NAME,\n image_shape=image_shape)\n\n # Run training or evaluation.\n if args.eval_only:\n model = Trainer.build_model(cfg)\n DetectionCheckpointer(model, save_dir=cfg.OUTPUT_DIR).resume_or_load(\n cfg.MODEL.WEIGHTS, resume=args.resume)\n res = Trainer.test(cfg, model)\n if comm.is_main_process():\n verify_results(cfg, res)\n return res\n\n trainer = Trainer(cfg)\n trainer.resume_or_load(resume=args.resume)\n return trainer.train()", "def main() -> None:\n args = docopt.docopt(__doc__, version=__version__)\n # Set up logging\n log_level = args[\"--log-level\"]\n try:\n logging.basicConfig(\n format=\"%(asctime)-15s %(levelname)s %(message)s\", level=log_level.upper()\n )\n except ValueError:\n logging.critical(\n '\"%s\" is not a valid logging level. Possible values '\n \"are debug, info, warning, and error.\",\n log_level,\n )\n sys.exit(1)\n\n # see if the user is providing any external hash blob data\n hashblob = None\n if args[\"--stdin\"] is True:\n logging.debug(\"Reading hashes from stdin\")\n hashblob = sys.stdin.read()\n elif args[\"--file\"] is not None:\n logging.debug(\"Reading hashes from %s\", args[\"--file\"])\n with open(args[\"--file\"]) as f:\n hashblob = f.read()\n\n exit_code = ioc_scanner.ioc_search(hashblob, args[\"--target\"])\n\n # Stop logging and clean up\n logging.shutdown()\n\n if exit_code:\n sys.exit(exit_code)", "def evaluate_input(args):\n\n def call_loader(path, logger):\n try:\n # Python2 support\n if os.path.isfile(path):\n dc = DataContainer.load(path)\n if hasattr(dc, \"data_container_version\") and \\\n dc.data_container_version == \"2.0\":\n return dc\n else:\n logger.error(\"Error: This type of data container is not \\\n supported (data_container_version not found or < 2.0)\")\n DMRenderExit(logger)\n else:\n logger.error(\"FileNotFoundError: No such file or directory: '\\\n {}'\".format(path))\n DMRenderExit(logger)\n except IOError as e:\n logger.error(\"IOError: {}\".format(str(e)))\n DMRenderExit(logger)\n\n except UnicodeDecodeError as e:\n logger.error(\"UnicodeDecodeError: {}\\n\".format(str(e)))\n DMRenderExit(logger)\n\n logger = logging.getLogger('DMlog')\n DM_list = list()\n # Case 1: text file containing one path per line\n if args.input.endswith('.txt'):\n logger.debug(\"Input of type 1 detected\")\n input_type = 1\n if os.path.isfile(args.input):\n with open(args.input) as f:\n fp_list = f.read().splitlines()\n else:\n logger.error(\"FileNotFoundError: No such file or directory: '{}'\\\n \".format(args.input))\n DMRenderExit(logger)\n\n for dm_file_path in fp_list:\n label = dm_file_path\n # We handle a potential label provided\n if ':' in dm_file_path:\n dm_file_path, label = dm_file_path.rsplit(':', 1)\n\n dm_obj = call_loader(dm_file_path, logger)\n dm_obj.path = dm_file_path\n dm_obj.label = label if dm_obj.label is None else dm_obj.label\n dm_obj.show_label = True\n DM_list.append(dm_obj)\n\n # Case 2: One dm pickled file\n elif args.input.endswith('.dm'):\n logger.debug(\"Input of type 2 detected\")\n input_type = 2\n dm_obj = call_loader(args.input, logger)\n dm_obj.path = args.input\n dm_obj.label = args.input if dm_obj.label is None else dm_obj.label\n dm_obj.show_label = True\n DM_list = [dm_obj]\n\n # Case 3: String containing a list of input with their metadata\n elif args.input.startswith('[[') and args.input.endswith(']]'):\n logger.debug(\"Input of type 3 detected\")\n input_type = 3\n try:\n input_list = literal_eval(args.input)\n for dm_data, dm_opts in input_list:\n logger.debug(\"dm_data: {}\".format(dm_data))\n logger.debug(\"dm_opts: {}\".format(dm_opts))\n dm_file_path = dm_data['path']\n dm_obj = call_loader(dm_file_path, logger)\n dm_obj.path = dm_file_path\n dm_obj.label = dm_data['label'] if dm_data['label'] is not \\\n None else dm_obj.label\n dm_obj.show_label = dm_data['show_label']\n dm_obj.line_options = dm_opts\n dm_obj.line_options['label'] = dm_obj.label\n DM_list.append(dm_obj)\n\n except ValueError as e:\n if not all([len(x) == 2 for x in input_list]):\n logger.error(\"ValueError: Invalid input format. All sub-lists \\\n must be a pair of two dictionaries.\\n-> {}\".format(str(e)))\n else:\n logger.error(\"ValueError: {}\".format(str(e)))\n DMRenderExit(logger)\n\n except SyntaxError as e:\n logger.error(\"SyntaxError: The input provided is invalid.\\n-> {}\\\n \".format(str(e)))\n DMRenderExit(logger)\n\n else:\n logger.error(\"The input type does not match any of the following \\\n inputs:\\n- .txt file containing one file path per line\\n- .dm file\\\n \\n- a list of pair [{'path':'path/to/dm_file','label':str,'\\\n show_label':bool}, **{any matplotlib.lines.Line2D properties}].\\n\")\n DMRenderExit(logger)\n\n # Assertions: All the fa_labels and fn_labels MUST by unique\n fa_label = set([x.fa_label for x in DM_list])\n fn_label = set([x.fn_label for x in DM_list])\n assert (len(fa_label) == 1), \"Error: DM files have mixed FA_labels {}\\\n \".format(fa_label)\n assert (len(fn_label) == 1), \"Error: DM files have mixed FN_labels {}\\\n \".format(fn_label)\n\n if (args.aggregate is not None):\n logger.debug(\"Creating aggregated Line\")\n try:\n dm_data, dm_opts = literal_eval(args.aggregate)\n dm_obj = DataContainer.aggregate(\n DM_list, output_label=\"TFA_mean_byfa\", average_resolution=500)\n dm_obj.label = dm_data['label'] if dm_data['label'] is not None \\\n else dm_obj.label\n dm_obj.activity = dm_obj.label\n dm_obj.fa_label = fa_label.pop()\n dm_obj.fn_label = fn_label.pop()\n dm_obj.show_label = dm_data['show_label']\n dm_obj.line_options = dm_opts\n dm_obj.line_options['label'] = dm_obj.label\n DM_list.append(dm_obj)\n\n if dm_data['path'] is not None:\n fname = \"{}/{}\".format(args.outputFolder, dm_data['path'])\n logger.debug(\"Writing aggregated Line to {}\".format(fname))\n dm_obj.dump(fname)\n\n except ValueError as e:\n logger.error(\"ValueError: The aggrgate option had a value error {}\\\n \".format(str(e)))\n DMRenderExit(logger)\n\n except SyntaxError as e:\n logger.error(\"SyntaxError: The aggregate option provided is \\\n invalid.\\n-> {}\".format(str(e)))\n DMRenderExit(logger)\n\n # *-* Options Processing *-*\n\n # General plot options\n if not args.plotOptionJsonFile:\n logger.info(\"Generating the default plot options...\")\n plot_opts = Render.gen_default_plot_options(\n args.plotType, DM_list[0].fa_label, DM_list[0].fn_label,\n plot_title=args.plotTitle)\n\n else:\n logger.info(\"Loading of the plot options from the json config file...\")\n if os.path.isfile(args.plotOptionJsonFile):\n with open(args.plotOptionJsonFile, 'r') as f:\n plot_opts = json.load(f)\n validate_plot_options(plot_opts)\n else:\n logger.error(\"FileNotFoundError: No such file or directory: '{}'\\\n \".format(args.plotOptionJsonFile))\n DMRenderExit(logger)\n\n # line options\n if args.lineOptionJsonFile and input_type != 3:\n logger.info(\"Loading of the lines options from the json config file \\\n and overriding data container line settings...\")\n if os.path.isfile(args.lineOptionJsonFile):\n\n with open(args.lineOptionJsonFile, 'r') as f:\n opts_list = json.load(f)\n\n if len(opts_list) != len(DM_list):\n print(\"ERROR: the number of the line options is different \\\n with the number of the DM objects: ({} < {})\".format(\n len(opts_list), len(DM_list)))\n DMRenderExit(logger)\n else:\n for dm, line_options in zip(DM_list, opts_list):\n dm.line_options = line_options\n else:\n logger.error(\"FileNotFoundError: No such file or directory: '{}'\\\n \".format(args.lineOptionJsonFile))\n DMRenderExit(logger)\n\n if args.confidenceInterval:\n plot_opts['confidence_interval'] = True\n\n return DM_list, plot_opts", "def execute_file(self, files, **kw):\n\n mode = kw['mode'] if 'mode' in kw else 0\n\n # ranger can act as a file chooser when running with --choosefile=...\n if mode == 0 and 'label' not in kw:\n if ranger.args.choosefile:\n open(ranger.args.choosefile, 'w').write(self.fm.thisfile.path)\n\n if ranger.args.choosefiles:\n paths = []\n for hist in self.fm.thistab.history:\n for fobj in hist.files:\n if fobj.marked and fobj.path not in paths:\n paths += [fobj.path]\n paths += [f.path for f in self.fm.thistab.get_selection() if f.path not in paths]\n\n with open(ranger.args.choosefiles, 'w') as fobj:\n fobj.write('\\n'.join(paths) + '\\n')\n\n if ranger.args.choosefile or ranger.args.choosefiles:\n raise SystemExit\n\n if isinstance(files, set):\n files = list(files)\n elif not isinstance(files, (list, tuple)):\n files = [files]\n\n flags = kw.get('flags', '')\n if 'c' in squash_flags(flags):\n files = [self.fm.thisfile]\n\n self.signal_emit('execute.before', keywords=kw)\n filenames = [f.path for f in files]\n label = kw.get('label', kw.get('app', None))\n try:\n return self.rifle.execute(filenames, mode, label, flags, None)\n finally:\n self.signal_emit('execute.after')" ]
[ "0.61953026", "0.6166626", "0.5958938", "0.59363645", "0.5926071", "0.58944595", "0.56989646", "0.5695022", "0.5689529", "0.56718326", "0.5646995", "0.56252486", "0.56227446", "0.5597798", "0.5588111", "0.55471885", "0.5533798", "0.5513449", "0.54699075", "0.54589504", "0.5458741", "0.543988", "0.5420617", "0.5416856", "0.54080474", "0.53732497", "0.536794", "0.5361753", "0.53526545", "0.53408134" ]
0.7537991
0
Compute the probability of observing at least d disks failure for a special configuration.
def probability_at_least_d_fail(disks, d, chunk_count, reliability): #print(disks, d, chunk_count, reliability) return sum([disk_loss_probability(disks, reliability, k) for k in range(d, chunk_count + 1)]) # return sum([disk_loss_probability(k) for k in range(recovery_threshold, chunk_count + 1)])
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def probability_at_least_d_fail_matrix(disks, d, chunk_count, reliability):\n failure_threshold = chunk_count - d + 1\n \n transfer_matrices = [transfer_matrix(reliability[disk], failure_threshold)\n for disk in reversed(disks)]\n \n return np.sum(reduce(np.dot, transfer_matrices), axis=1)[0]", "def probability_file_loss(disks, chunk_count, spread_factor, d, disk_reliability):\n # First we calculate the probability that a configuration is selected.\n probability_configuration = (1.0*(factorial(spread_factor - chunk_count + 1)*factorial(chunk_count - 1))\n / (len(disks)*factorial(spread_factor)))\n \n # Then, we generate the list of all feasible configurations as a function of \n # the number of disks, disk_count, the number of chunks, chunk_count and the spread factor.\n #configurations = list(map(lambda t: map(lambda e: e + 1, t),\n # feasible_configurations(disk_count, chunk_count, spread_factor)))\n \n configurations = feasible_configurations(len(disks), chunk_count, spread_factor)\n\n # Finally, for each feasible configuration where chunks are stored, we calculate the probabi-\n # lity the file is lost.\n \n # first we consider there is no redondancy\n if len(disks) >= 2*(spread_factor + 1) - chunk_count:\n return probability_configuration * sum([probability_at_least_d_fail(config, d, chunk_count, disk_reliability)\n for config in configurations])\n # This condition cover the case with redondancies\n else:\n return probability_configuration * sum([frequency(config, len(disks), spread_factor)*probability_at_least_d_fail(config, d, chunk_count, disk_reliability)\n for config in configurations])", "def probability_at_least_d_fail_equal_reliability(d, chunk_count, reliability):\n \n return sum([loss_probability(reliability, k, chunk_count) for k in range(d, chunk_count + 1)])", "def probability_file_loss_matrix(disks, chunk_count, spread_factor, d, reliability):\n \n # First we calculate the probability that a configuration is selected.\n probability_configuration = (1.0*factorial(spread_factor - chunk_count + 1) * factorial(chunk_count - 1) /\n (len(disks) * factorial(spread_factor)))\n \n # Then, we generate the list of all feasible configurations as a function of \n # the number of disks, disk_count, the number of chunks, chunk_count and the spread factor.\n configurations = feasible_configurations(len(disks), chunk_count, spread_factor)\n \n # Finally, for each feasible configuration where chunks are stored, we calculate the probabi-\n # lity the file is lost.\n \n # first we consider there is no redundancy\n if len(disks) >= 2*(spread_factor + 1) - chunk_count:\n return probability_configuration * sum([probability_at_least_d_fail_matrix(config, d, chunk_count, reliability)\n for config in configurations])\n # This condition cover the case with redundancies\n else:\n return probability_configuration * sum([frequency(config, len(disks), spread_factor) *\n probability_at_least_d_fail_matrix(config, d, chunk_count, reliability)\n for config in configurations])", "def prob(throw, n, d=6, type='classical'):\n count = 0\n table = throw_table(n, d, type)\n for t in table:\n if sum(t) == throw:\n count += 1\n \n return float(count)/len(table)", "def discretization_error(hmsm, descendant_level, parent_level):\n if descendant_level==0:\n pi_dict = hmsm.get_full_stationary_distribution()\n # pi is an np array of the probabilities, sorted by their ids:\n pi = np.array(list(pi_dict.values())) #just the distribution\n pi = pi[np.argsort(list(pi_dict.keys()))] # sort by the ids\n else:\n T, ids = hmsm.get_level_T(descendant_level, 1)\n pi = stationary_distribution(T)\n pi = pi[np.argsort(ids)]\n\n induced_pi, ids = induced_distribution(hmsm, descendant_level, parent_level)\n induced_pi = induced_pi[np.argsort(ids)]\n\n return D_KL(pi, induced_pi)", "def deviation(delta, mean_reliability, experiment, disks, chunk_count, spread_factor, threshold_recovery):\n \n # Approximated file loss probability\n reliability_mean_value = probability_at_least_d_fail_equal_reliability(threshold_recovery, chunk_count, mean_reliability)\n \n\n # Exact probability\n reliabilities = [element for element in \n file_loss_delta_matrix(delta, mean_reliability, experiment, disks, chunk_count, spread_factor, \n threshold_recovery)]\n \n return abs(mean(reliabilities) - reliability_mean_value)/abs(mean(reliabilities))", "def file_loss_delta(delta, mean_reliability, experiments, disks, chunk_count, spread_factor, d):\n \n for e in experiments:\n # First we generate the list of disk reliability between mean_reliability-0.5*delta and mean_reliability-0.5*delta.\n \n lower_bound = mean_reliability - 0.5 * delta\n upper_bound = mean_reliability + 0.5 * delta\n\n reliability = dict(zip(disks, uniform(low=lower_bound, high=upper_bound, size=len(disks))))\n reliability[disks[-1]] = len(disks) * mean_reliability - sum([reliability[disk] for disk in disks[:-1]])\n \n # Then we calculate the probability of file loss for the reliability list \n yield probability_file_loss(disks, chunk_count, spread_factor, d, reliability)", "def drinking_error_rate(individual, test_data, truth_data, name=None):\r\n test_data = np.array(test_data)\r\n truth_data = np.array(truth_data)\r\n total = 0\r\n num_wrong = 0\r\n for test_point, truth_point in zip(test_data, truth_data):\r\n # Two represents a drinking event, Three is eating, One is Chewing\r\n if (truth_point == 2):\r\n if np.isnan(test_point) or test_point <= 1.5 or test_point > 2.5:\r\n num_wrong += 1\r\n total += 1\r\n #if num_wrong == 0:\r\n # # Perfection implies overtraining\r\n # return 1.0\r\n #else:\r\n return float(num_wrong)/float(total)", "def test_probabilities_are_ok(self, seed):\n bins = defaultdict(int)\n probs = (0.1, 0.2, 0.3, 0.4)\n categories = (\"asdfa\", \"2\", \"3\", \"4\")\n categories = OrderedDict(zip(categories, probs))\n dim = Categorical(\"yolo\", categories)\n for _ in range(500):\n sample = dim.sample(seed=seed)[0]\n bins[sample] += 1\n for keys in bins.keys():\n bins[keys] /= float(500)\n for key, value in categories.items():\n assert abs(bins[key] - value) < 0.01", "def fairness_discrepancy(props, n_classes, norm=0):\n # unique, freq = np.unique(data, return_counts=True)\n # props = freq / len(data) #Proportion of data that belongs to that data\n \n # #------------------Modification to correct the zero support problem------------------------------------------------\n # temp=np.zeros(n_classes)\n # temp[unique]=props\n # props=temp\n # #------------------------------------------------------------------------------\n \n # print (freq)\n truth = 1./n_classes\n\n\n # L2 and L1=================================================================================================\n #(Remove Normalisation)\n l2_fair_d = np.sqrt(((props - truth)**2).sum())\n l1_fair_d = abs(props - truth).sum()\n\n # q = props, p = truth\n # kl_fair_d = (props * (np.log(props) - np.log(truth))).sum()\n\n #Cross entropy\n p=np.ones(n_classes) \n # ce=cross_entropy(p,props,n_classes)-cross_entropy(p,p,n_classes)\n \n #information specificity=====================================================================================\n rank=np.linspace(1,n_classes-1,n_classes-1)\n rank[::-1].sort() #Descending order\n perc=np.array([i/np.sum(rank) for i in rank])\n \n \n props[::-1].sort()\n alpha=props[1:]\n specificity=abs(props[0]-np.sum(alpha*perc))\n info_spec=(l1_fair_d+specificity)/2\n \n #Wasstertein Distance\n wd=wasserstein_distance(props,np.ones(len(props))*truth)\n \n #Wassertein Specificity\n wds=(wd+specificity)/2\n if norm==0:\n return l2_fair_d, l1_fair_d,info_spec,specificity,wd,wds\n # return l2_fair_d, l1_fair_d,info_spec,specificity\n else:\n return l2_fair_d/metric_max(n_classes,\"L2\"), l1_fair_d/metric_max(n_classes,\"L1\"),info_spec/metric_max(n_classes,\"Is\"),specificity,wd/metric_max(n_classes,\"Wd\")\n # return l2_fair_d/metric_max(n_classes,\"l2\"), l1_fair_d/metric_max(n_classes,\"l1\"),info_spec/metric_max(n_classes,\"is\"),specificity", "def get_failure_prob(self, t1, t2):\n return (self.get_failure_cdf(t2) / (1 - self.get_failure_cdf(t1)))", "def test_ppt_distinguishability_four_bell_states():\n rho_1 = bell(0) * bell(0).conj().T\n rho_2 = bell(1) * bell(1).conj().T\n rho_3 = bell(2) * bell(2).conj().T\n rho_4 = bell(3) * bell(3).conj().T\n\n e_0, e_1 = basis(2, 0), basis(2, 1)\n e_00 = np.kron(e_0, e_0)\n e_11 = np.kron(e_1, e_1)\n\n eps = 0.5\n resource_state = np.sqrt((1 + eps) / 2) * e_00 + np.sqrt((1 - eps) / 2) * e_11\n resource_state = resource_state * resource_state.conj().T\n\n states = [\n np.kron(rho_1, resource_state),\n np.kron(rho_2, resource_state),\n np.kron(rho_3, resource_state),\n np.kron(rho_4, resource_state),\n ]\n probs = [1 / 4, 1 / 4, 1 / 4, 1 / 4]\n\n exp_res = 1 / 2 * (1 + np.sqrt(1 - eps**2))\n\n primal_res = ppt_distinguishability(states, probs=probs, dist_method=\"min-error\", strategy=True)\n dual_res = ppt_distinguishability(states, probs=probs, dist_method=\"min-error\", strategy=False)\n\n np.testing.assert_equal(np.isclose(primal_res, exp_res, atol=0.001), True)\n np.testing.assert_equal(np.isclose(dual_res, exp_res, atol=0.001), True)", "def prob4():\n\n\n N = 500000\n random_draws = np.random.multivariate_normal(mean = [-1,1], cov =[[1,0],[0,1]], size = N)\n\n h = lambda x: x[0] < -1 and x[1] > 1\n f = lambda x: stats.multivariate_normal(mean = [ 0, 0]).pdf(x)\n g = lambda x: stats.multivariate_normal(mean = [-1, 1]).pdf(x)\n\n probability = [h(random_draws[i]) * f(random_draws[i]) / g(random_draws[i]) for i in range(N)]\n\n return 1./N * np.sum(probability)", "def expected_error(noise_param, states):\n\n from math import comb\n import preferences\n\n comparison_errors = [\n preferences.comparison_error(\n state / states,\n noise_param\n )\n for state in range(1, states)\n ]\n\n n_choose_2 = comb(states, 2)\n\n expected_error = 0.0\n for i, p in enumerate([(states - x)/n_choose_2 for x in range(1, states)]):\n expected_error += p * comparison_errors[i]\n\n return round(expected_error, 3)", "def realistic_error_rate(predictions, labels, predicted_hardness):\n # # print (predicted_hardness)\n # predicted_hardness = predicted_hardness / np.sum(predicted_hardness)\n # # print (np.argmax(predictions, 1) == labels)\n # # print (np.multiply(np.argmax(predictions, 1) == labels, np.squeeze(predicted_hardness)))\n # return 100.0 - 100 * np.sum(np.multiply(np.argmax(predictions, 1) == labels, np.squeeze(predicted_hardness)))\n # # return 100.0 - (\n # # 100.0 *\n # # np.sum(np.argmax(predictions, 1) == labels) /\n # # predictions.shape[0])\n print (np.sum(predicted_hardness))\n return 100.0 - 100 * (np.sum(np.multiply(np.argmax(predictions, 1) == labels, np.squeeze(predicted_hardness))) / np.sum(predicted_hardness))", "def test_probability_of_all_successes():\n\n assert(probability_of_all_successes(1/2,1,2) == 0.25)\n assert(are_close(probability_of_all_successes(1/6,1,2), 1/36, 0.001))\n assert(are_close(probability_of_all_successes(1/2,2,2), 7/16, 0.001))", "def prob1(n):\n\n # create a giant draw from a normal distribution\n random_draws = np.random.normal(loc= 0, scale = 1, size = n)\n\n # mask the values\n mask = random_draws > 3\n\n return np.sum(mask)/float(n)", "def loss_probability(reliability, k, chunk_count):\n return (factorial(chunk_count)/(factorial(chunk_count-k)*factorial(k))\n * pow(1 - reliability,k)*pow(reliability,chunk_count-k))", "def calculate_probability(self):\n return 0", "def _compute_model_prob(self, per_list_logodds):\n with tf.compat.v1.name_scope(name='compute_model_prob'):\n return tf.stop_gradient(\n tf.exp(-self._alpha *\n (per_list_logodds -\n tf.reduce_min(per_list_logodds, axis=2, keepdims=True))))", "def prob1(n):\n#raise NotImplementedError(\"Problem 1 Incomplete\")\n if n == 0 :\n raise ValueError(\"Sampling 0 points is not defined.\")\n total = 0\n for i in xrange(n) :\n if np.random.normal() > 3 :\n total += 1\n return float(total)/n", "def __D_loss(self, D, real, fake):\n loss = 0.5 * (tf.reduce_mean(tf.squared_difference(D(real), 1.0)) + \\\n tf.reduce_mean(tf.square(D(fake))))\n\n return loss", "def test_dc():\n signal = np.zeros(100)\n pe = permutation_entropy(signal, 2)\n\n assert pe == 0", "def _calc_freeze_probability(self, num_iterations, final_fraction):\n return 1.0 - (final_fraction ** (1.0 / num_iterations))", "def p_EPR(d, N):\n return sum(\n d ** -N * (weyl(d, alpha) * specht(alpha) * N) / (alpha[0] + d)\n for alpha in Partitions(n=N - 1, max_length=d)\n )", "def random_policy(self, pc):\n if list(self.state.P_k.keys()) or list(self.state.D_k):\n return random.choice(list(self.state.P_k.keys())+list(self.state.D_k))\n elif not(list(self.state.P_k.keys()) and list(self.state.D_k)):\n return 0\n else:\n raise ValueError('Check jobs remaining to be done.')", "def compute_expected_return_(domain, N, policy, p_init, s_init):\r\n pos = p_init\r\n speed = s_init\r\n expected_return = 0\r\n\r\n for i in range(N):\r\n if domain.terminalState(pos, speed):\r\n break\r\n action = policy((pos, speed))\r\n if isinstance(action,str):\r\n action = domain.getAction(action)\r\n new_pos, new_speed = domain.getNextState(pos, speed, action)\r\n r = domain.getReward(pos, speed, action, new_pos, new_speed)\r\n expected_return += ((domain.discount_factor)**i)*r\r\n pos = new_pos\r\n speed = new_speed\r\n \r\n return expected_return", "def precomp_threshold(dof, len_sim=1e5, beta=.75):\n for d in dof:\n cdt = GaussianCusum(arl=None, beta=beta)\n cdt.fit(x=np.zeros((1, d)), estimate_threshold=True, len_simulation=len_sim,\n verbose=True, precompute_thresholds=True)", "def precomp_threshold(dof, len_sim=1e5, beta=.75):\n for d in dof:\n cdt = GaussianCusum(arl=None, beta=beta)\n cdt.fit(x=np.zeros((1, d)), estimate_threshold=True, len_simulation=len_sim,\n verbose=True, precompute_thresholds=True)" ]
[ "0.72341484", "0.7218013", "0.68280166", "0.6411059", "0.62288916", "0.5944703", "0.5901955", "0.5817657", "0.5722958", "0.5694554", "0.5596", "0.55757535", "0.5557571", "0.5555904", "0.5533613", "0.5527104", "0.5523611", "0.5508688", "0.5491621", "0.5454803", "0.5433317", "0.54295665", "0.5420549", "0.53874004", "0.53672224", "0.53649205", "0.53646845", "0.534775", "0.53411394", "0.53411394" ]
0.8210371
0
Construct square transfer matrix with (1 reliability) on the diagonal and reliability on the upper diagonal and 0 otherwise.
def transfer_matrix(reliability, size): return ((1.0 - reliability) * np.eye(size, k=0, dtype=float) + reliability * np.eye(size, k=1, dtype=float))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def init_needleman_wunsch_matrix(self):\r\n empty_matrix = self.empty_matrix() # Building on the previous definition, this will give you an empty matrix\r\n for i in range(len(self.s2)+1):\r\n for j in range(len(self.s1)+1):\r\n empty_matrix[0][i] = -i\r\n empty_matrix[j][0] = -j\r\n return empty_matrix", "def generate_s_matrix(number: int):\n matrix_zero = np.ones((number, number))\n matrix_zero[1:-1, 1:-1] = 0\n return matrix_zero", "def _build_adjacency_matrix_1(self):\n\n from scipy import sparse as sparse\n \n down_neighbour = np.empty(self.tri.npoints)\n\n for node in range (0,self.tri.npoints):\n down_neighbour[node] = self.neighbour_array_lo_hi[node][0]\n\n # Build a matrix of downhill-ness - one entry per node ! \n \n size = self.tri.npoints\n row_array = np.empty(size)\n col_array = np.empty(size)\n down_array = np.ones(size)\n\n # Catch cases where node is local low point (i.e. it is its own low neighbour)\n\n for row in range(0, self.tri.npoints): \n row_array[row] = row\n col_array[row] = down_neighbour[row]\n if row == down_neighbour[row]:\n down_array[row] = 0.0\n \n\n downMCOO = sparse.coo_matrix( (down_array, (row_array, col_array)), shape=(size,size) ).T \n\n self.adjacency1 = downMCOO.tocsr() \n\n # Catch pathological cases - sometimes if there is a flat spot on the boundary, then \n # the filling method above will produce a non-square matrix. This is caused by\n # repetition of values in the COO list which are summed on conversion.\n\n if downMCOO.shape[0] != downMCOO.shape[1]:\n # This approach works but is a lot slower\n\n print \"\"\"\n Warning: the downhill matrices require a slow build method. This is probably\n Because there are degeneracies in the slope - particularly at the boundaries\n A small random perturbation is usually enough to fix this problem\n \"\"\"\n downMat = sparse.lil_matrix((size, size))\n\n for row in range(0, self.tri.npoints): \n downMat[down_neighbour[row],row] = 1.0\n\n for row in range(0, self.tri.npoints): \n if down_neighbour[row] == row:\n downMat[row,row] = 0.0\n \n self.adjacency1 = downMat.T.tocsr() \n \n return", "def _build_adjacency_matrix_2(self):\n\n from scipy import sparse as sparse\n \n down_neighbour = np.empty(self.tri.npoints)\n down_neighbour1 = np.empty(self.tri.npoints)\n\n for node in range (0,self.tri.npoints):\n down_neighbour[node] = self.neighbour_array_lo_hi[node][0]\n down_neighbour1[node] = self.neighbour_array_lo_hi[node][1]\n\n # Build a matrix of downhill-ness - one entry per node ! \n \n size = self.tri.npoints\n row_array = np.empty(size)\n col_array = np.empty(size)\n down_array = np.ones(size)\n\n # Catch cases where node is local low point (i.e. it is its own low neighbour)\n for row in range(0, self.tri.npoints): \n row_array[row] = row\n col_array[row] = down_neighbour1[row]\n if row == down_neighbour[row]:\n down_array[row] = 0.0 \n if row == down_neighbour1[row]:\n col_array[row] = down_neighbour[row]\n\n\n downMCOO = sparse.coo_matrix( (down_array, (row_array, col_array)), shape=(size,size) ).T \n self.adjacency2 = downMCOO.tocsr() \n\n # Catch pathological cases - sometimes if there is a flat spot on the boundary, then \n # the filling method above will produce a non-square matrix. This is caused by\n # repetition of values in the COO list which are summed on conversion.\n\n if downMCOO.shape[0] != downMCOO.shape[1]:\n # This approach works but is a lot slower\n\n print \"\"\"\n Warning: the downhill matrices require a slow build method. This is probably\n Because there are degeneracies in the slope - particularly at the boundaries\n A small random perturbation is usually enough to fix this problem\n \"\"\"\n downMat = sparse.lil_matrix((size, size))\n\n for row in range(0, self.tri.npoints): \n downMat[down_neighbour[row],row] = 1.0\n\n for row in range(0, self.tri.npoints): \n if row == down_neighbour[row] or row == down_neighbour1[row]:\n downMat[row,row] = 0.0\n \n self.adjacency2 = downMat.T.tocsr() \n\n return", "def __neg__(self):\n #\n # TODO - your code here\n #\n matrix_neg = []\n for i in range(self.h):\n row = []\n for j in range(self.w):\n row.append(0-self.g[i][j])\n matrix_neg.append(row)\n return Matrix(matrix_neg)\n # TODO - your code here", "def create_full_availability_matrix(space_size: float, square_subdivision_length: float = 10) -> np.ndarray:\n\t\tsquares_number = int(space_size // square_subdivision_length)\n\t\treturn np.ones((squares_number, squares_number))", "def Controlled2(U):\n '''Generalized controlled unitary tensor construction\n Parameters:\n -----------\n U: input tensor which is assumed to be a square Matrix\n\n Returns:\n --------\n Controlled unitary\n\n '''\n shp = U.shape\n new_ten = scipy.linalg.block_diag(np.eye(*shp), U)\n return new_ten.reshape(2, shp[0], 2, shp[1], 2, shp[2])", "def get_cost_matrix(self, gains = np.ones(3)):\n\n # gain matrix for cost optimization\n R = np.diag(gains)\n\n return R", "def fill_diagonal(self):\n if not self.is_square():\n raise Exception(u\"Not a square matrix\")\n\n mat = clone_matrix(self.coefficients)\n size = self.get_size()[0]\n permut = list(range(size))\n\n for col in range(size):\n cur_line = col\n best_line = col\n best_value = 0\n for line in range(col, size):\n cur_value = mat[line][col]\n if abs(cur_value) > best_value:\n best_line = line\n best_value = cur_value\n if best_value == 0:\n raise Exception(u\"Singular matrix\")\n permut[cur_line], permut[best_line] = permut[best_line], permut[cur_line]\n for idx in range(size):\n mat[cur_line][idx], mat[best_line][idx] = mat[best_line][idx], mat[cur_line][idx]\n\n return Matrix(mat), permut", "def square_matrix(triangular_matrix):\n length = len(triangular_matrix)\n zero = [0.0]\n\n for item in triangular_matrix:\n item.extend(zero * (length - len(item)))\n\n return triangular_matrix", "def __neg__(self):\n # \n # TODO - your code here\n #\n result = [];\n for row in self.g:\n result.append([-1*n for n in row]);\n \n return Matrix(result);", "def RWTransitionMatrix(g):\n row = []\n col = []\n data = []\n if g.is_weighted():\n D = g.strength(mode='out', weights=g.es[\"weight\"])\n for edge in g.es():\n s,t = edge.tuple\n row.append(t)\n col.append(s)\n tmp = edge[\"weight\"] / D[s]\n if tmp <0 or tmp > 1:\n tn.Log.add('Encountered transition probability outside [0,1] range.', Severity.ERROR)\n raise ValueError()\n data.append( tmp )\n else:\n D = g.degree(mode='out')\n for edge in g.es():\n s,t = edge.tuple\n row.append(t)\n col.append(s)\n tmp = 1. / D[s]\n if tmp <0 or tmp > 1:\n tn.Log.add('Encountered transition probability outside [0,1] range.', Severity.ERROR)\n raise ValueError()\n data.append( tmp )\n \n # TODO: find out why data is some times of type (N, 1)\n # TODO: and sometimes of type (N,). The latter is desired\n # TODO: otherwise scipy.coo will raise a ValueError\n data = np.array(data)\n data = data.reshape(data.size,)\n\n return sparse.coo_matrix((data, (row, col)), shape=(len(g.vs), len(g.vs))).tocsr()", "def empty_matrix(self):\r\n\r\n return [[0 for i in range(len(self.s2)+1)] for j in range(len(self.s1)+1)]", "def compute_matrix(self):\n\n fac = self.a / self.dx ** 2\n\n diagonal = np.ones(self.nx) * 2 * fac\n lower = np.ones(self.nx - 1) * -fac\n upper = np.ones(self.nx - 1) * -fac\n\n matrix = sp.diags(\n diagonals=[diagonal, lower, upper],\n offsets=[0, -1, 1], shape=(self.nx, self.nx),\n format='csr')\n\n return matrix", "def createTransitionMatrix(self):\n transitionMatrix = np.zeros((1, self.n*self.m))\n\n for i in self.board:\n x1, y1 = i\n line = []\n\n if self.walls[x1][y1] is True:\n line = np.zeros((1, self.n*self.m))\n tmp = np.vstack((transitionMatrix, line.reshape((1, -1))))\n transitionMatrix = tmp\n continue\n\n count = 0\n left = self.walls[x1 - 1][y1]\n right = self.walls[x1 + 1][y1]\n down = self.walls[x1][y1 - 1]\n up = self.walls[x1][y1 + 1]\n list = [left, right, down, up]\n for near in list:\n if near is False:\n count = count + 1\n\n p = self.p\n\n if count == 0:\n line = np.zeros((1, self.n*self.m))\n tmp = np.vstack((transitionMatrix, line.reshape((1, -1))))\n transitionMatrix = tmp\n continue\n\n cmp = (1 - p)/count\n\n for j in self.board:\n x2, y2 = j\n walls = self.walls[x2][y2] is False\n\n if self.walls[x1 + 1][y1] is False:\n \"\"\"\n If East is a legal action\n \"\"\"\n if x2 == x1 + 1 and y2 == y1:\n line.append(p + cmp)\n\n elif x2 == x1 - 1 and y2 == y1 and walls:\n line.append(cmp)\n\n elif x2 == x1 and y2 == y1 + 1 and walls:\n line.append(cmp)\n\n elif x2 == x1 and y2 == y1 - 1 and walls:\n line.append(cmp)\n\n else:\n line.append(0)\n\n else:\n \"\"\"\n If East is not a legal action\n \"\"\"\n if x2 == x1 - 1 and y2 == y1 and walls:\n line.append(1/count)\n\n elif x2 == x1 and y2 == y1 + 1 and walls:\n line.append(1/count)\n\n elif x2 == x1 and y2 == y1 - 1 and walls:\n line.append(1/count)\n\n else:\n line.append(0)\n\n line = np.array(line)\n tmp = np.vstack((transitionMatrix, line.reshape((1, -1))))\n transitionMatrix = tmp\n\n return transitionMatrix[1:, :]", "def test_matrix_structure(self):\n k = [2, 3, 4, 5, 6]\n model = self.create_chain_model(k)\n\n model.create_matrices()\n\n for edge, i in model.message_index.items():\n from_index = model.var_index[edge[0]]\n to_index = model.var_index[edge[1]]\n assert model.message_from[i] == from_index, \"Message sender index is wrong\"\n assert model.message_to[i] == to_index, \"Message receiver index is wrong\"\n model.message_to_map.getrow(i).getcol(to_index), \"Message receiver matrix map is wrong\"\n\n assert np.all(np.sum(model.message_to_map.todense(), axis=1) == 1), \\\n \"Message sender map has a row that doesn't sum to 1.0\"", "def fill_matrix(self):\n\n print(\"Creating Needleman-Wunsch matrix..\")\n\n for i in range(self.matrix.shape[0]):\n for j in range(self.matrix.shape[1]):\n\n if i < len(self.seq_2) and j < len(self.seq_1):\n self.matrix[0, i + 2] = self.seq_2[i]\n self.matrix[j + 2, 0] = self.seq_1[j]\n\n if i > 1 and j > 1:\n self.matrix[1, j] = self.matrix[1, j - 1] + self.GAP\n self.matrix[i, 1] = self.matrix[i - 1, 1] + self.GAP\n\n diag = (self.matrix[i - 1, j - 1] + self.compare(self.matrix[0, j], self.matrix[i, 0]))\n up = (self.matrix[i, j - 1] + self.GAP)\n left = (self.matrix[i - 1, j] + self.GAP)\n\n selected = max(diag, up, left)\n\n self.add_arrow(i, j, diag, up, left, selected)\n\n self.matrix[i, j] = selected", "def connection(self, sampleseq, num):\n self.Adjmatrix = np.zeros((self.nodenum, self.nodenum), dtype = int)\n \n for i in range(self.supplynum):\n minindex = np.array(sf.minimumk(self.Dismatrix[self.supplyseries[i], self.trandemandseries], sampleseq[self.supplyseries[i]]))\n self.Adjmatrix[self.supplyseries[i], self.trandemandseries[minindex]] = 1\n# self.Adjmatrix[minindex, self.supplyseries[i]] = 1\n \n for i in range(self.trannum):\n if(np.sum(self.Adjmatrix[self.supplyseries, self.transeries[i]]) == 0):\n minindex = np.array(sf.minimumk(self.Dismatrix[self.supplyseries, self.transeries[i]], num))\n self.Adjmatrix[minindex, self.transeries[i]] = 1\n# self.Adjmatrix[self.transeries[i], minindex] = 1\n \n \n# for i in range(self.supplynum):\n# minindex = np.array(sf.minimumk(self.Dismatrix[self.supplyseries[i], self.supplyseries], num))\n# self.Adjmatrix[self.supplyseries[i], minindex] = 1\n# self.Adjmatrix[minindex, self.supplyseries[i]] = 1\n \n# for i in range(self.trannum):\n# if(np.sum(self.Adjmatrix[self.supplyseries, self.transeries[i]]) != 0):\n# continue\n# minindex = np.array(sf.minimumk(self.Dismatrix[self.supplyseries, self.transeries[i]], num))\n# self.Adjmatrix[minindex, self.transeries[i]] = 1\n## self.Adjmatrix[self.transeries[i], minindex] = 1\n# \n for i in range(self.trannum):\n minindex = np.array(sf.minimumk(self.Dismatrix[self.transeries[i], self.demandseries], min(sampleseq[self.transeries[i]], self.demandnum))) + self.supplynum + self.trannum\n self.Adjmatrix[self.transeries[i], minindex] = 1\n# self.Adjmatrix[minindex, self.transeries[i]] = 1\n \n# for i in range(self.demandnum):\n# if(np.sum(self.Adjmatrix[self.transeries, self.demandseries[i]]) == 0):\n# minindex = np.array(sf.minimumk(self.Dismatrix[self.transeries, self.demandseries[i]], 1)) + self.supplynum\n# self.Adjmatrix[minindex, self.demandseries[i]] = 1\n \n# for i in range(self.trannum):\n# minindex = np.array(sf.minimumk(self.Dismatrix[self.transeries[i], self.transeries], num)) + self.supplynum\n# self.Adjmatrix[self.transeries[i], minindex] = 1\n \n for i in range(self.demandnum):\n if(np.sum(self.Adjmatrix[self.transeries, self.demandseries[i]]) == 0):\n minindex = np.array(sf.minimumk(self.Dismatrix[self.transeries, self.demandseries[i]], num)) + self.supplynum\n self.Adjmatrix[minindex, self.demandseries[i]] = 1\n# self.Adjmatrix[self.demandseries[i], minindex] = 1\n \n for i in range(self.demandnum):\n minindex = np.array(sf.minimumk(self.Dismatrix[self.demandseries[i], self.demandseries], min(sampleseq[self.demandseries[i]] + 1, self.demandnum))) + self.supplynum + self.trannum\n minindex = minindex[1:-1]\n for j in range(len(minindex)):\n if(self.Adjmatrix[self.demandseries[i], minindex[j]] == 1 or self.Adjmatrix[minindex[j], self.demandseries[i]] == 1):\n continue\n self.Adjmatrix[self.demandseries[i], minindex[j]] = 1", "def zeros_matrix(self, rows, cols):\r\n M = []\r\n while len(M) < rows:\r\n M.append([])\r\n while len(M[-1]) < cols:\r\n M[-1].append(0.0)\r\n\r\n return M", "def createboard(rows,columns):\n row_size = ''\n for rows in range(rows):\n if rows == 0:\n row_size = row_size + '0'\n else:\n row_size = row_size + ',0'\n fullmatrix = ''\n for cols in range(columns):\n if cols == 0:\n fullmatrix = fullmatrix + row_size\n else:\n fullmatrix = fullmatrix + '; ' + row_size\n return fullmatrix", "def zeroMatrix(width, height):\n returnvalue = Matrix()\n for i in range(width):\n newrow = [0] * height\n returnvalue.addRow(*newrow)\n return returnvalue", "def gen_square_subsequent_mask(sz: int) -> torch.Tensor:\n return torch.triu(torch.ones(sz, sz) * float('-inf'), diagonal=1)", "def test_to_matrix(self):\n v = np.copy(zero)\n with self.assertRaises(ZeroDivisionError):\n rowan.to_matrix(v)\n\n v = 2 * np.ones(4)\n with self.assertRaises(ValueError):\n rowan.to_matrix(v)\n\n v = np.copy(one)\n self.assertTrue(np.all(rowan.to_matrix(v) == np.eye(3)))\n\n v = np.copy(half)\n self.assertTrue(\n np.allclose(rowan.to_matrix(v), np.array([[0, 0, 1], [1, 0, 0], [0, 1, 0]]))\n )\n\n v[3] *= -1\n self.assertTrue(\n np.allclose(\n rowan.to_matrix(v), np.array([[0, 1, 0], [0, 0, -1], [-1, 0, 0]])\n )\n )", "def computeTransitionMatrix(self, mu = False):\n\n available_strategies = self.getAvailableStrategies()\n t_matrix = np.matrix([[0. for strategy in available_strategies] for strategy in available_strategies])\n\n for i, resident in enumerate(available_strategies):\n for j, invader in enumerate(available_strategies):\n if (i != j):\n fixation_proba = self.rho(resident, invader)\n if(mu):\n fixation_proba *= self.getExplorationRate()\n t_matrix[i, j] = 1./(len(available_strategies) - 1) * fixation_proba\n\n # calculate diagonal elements\n for i in range(len(available_strategies)):\n t_matrix[i, i] = 1 - t_matrix[i].sum(axis = 1)\n\n return t_matrix", "def to_matrix(self):\n return numpy.array([[1, 1],\n [1, -1]], dtype=complex) / numpy.sqrt(2)", "def generate_square_subsequent_mask(dim1: int, dim2: int) -> Tensor:\n return torch.triu(torch.ones(dim1, dim2) * float('-inf'), diagonal=1)", "def to_s_matrix(w,v):\n pass", "def test_get_routing_matrix_example_1():\n assert np.allclose(\n get_routing_matrix(\n lambda_2=1,\n lambda_1_1=1,\n lambda_1_2=1,\n mu_1=1,\n mu_2=1,\n num_of_servers_1=3,\n num_of_servers_2=3,\n system_capacity_1=3,\n system_capacity_2=3,\n buffer_capacity_1=2,\n buffer_capacity_2=2,\n alpha=0.5,\n ),\n np.array([[0.5, 0.0, 0.0], [1.0, 0.5, 0.0], [1.0, 1.0, 0.5]]),\n )", "def Controlled(U):\n shp = U.shape\n new_ten = scipy.linalg.block_diag(np.eye(*shp), U)\n return new_ten.reshape(2, shp[0], 2, shp[1])", "def get_transition_matrix(self):\n # Transition matrix\n P_trans = np.zeros((self.n_states, self.n_states))\n\n # Fill\n for s_num in range(2, (2**self.depth)):\n P_trans[(s_num - 1), (s_num//2 - 1)] = 1.0\n\n return P_trans" ]
[ "0.59489757", "0.5683399", "0.5654888", "0.5520674", "0.548017", "0.5421887", "0.54167813", "0.53991044", "0.53987265", "0.5383925", "0.53728986", "0.535879", "0.5345927", "0.533925", "0.533635", "0.5328171", "0.532013", "0.5295986", "0.5263911", "0.52635425", "0.5260293", "0.52560997", "0.52492315", "0.5225385", "0.5222258", "0.52206326", "0.5215481", "0.52080005", "0.5185598", "0.51813394" ]
0.74330145
0
Compute the probability of observing at least d disks failure for a special configuration using matrix formulation.
def probability_at_least_d_fail_matrix(disks, d, chunk_count, reliability): failure_threshold = chunk_count - d + 1 transfer_matrices = [transfer_matrix(reliability[disk], failure_threshold) for disk in reversed(disks)] return np.sum(reduce(np.dot, transfer_matrices), axis=1)[0]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def probability_at_least_d_fail(disks, d, chunk_count, reliability):\n #print(disks, d, chunk_count, reliability)\n \n return sum([disk_loss_probability(disks, reliability, k) for k in range(d, chunk_count + 1)])\n # return sum([disk_loss_probability(k) for k in range(recovery_threshold, chunk_count + 1)])", "def probability_file_loss_matrix(disks, chunk_count, spread_factor, d, reliability):\n \n # First we calculate the probability that a configuration is selected.\n probability_configuration = (1.0*factorial(spread_factor - chunk_count + 1) * factorial(chunk_count - 1) /\n (len(disks) * factorial(spread_factor)))\n \n # Then, we generate the list of all feasible configurations as a function of \n # the number of disks, disk_count, the number of chunks, chunk_count and the spread factor.\n configurations = feasible_configurations(len(disks), chunk_count, spread_factor)\n \n # Finally, for each feasible configuration where chunks are stored, we calculate the probabi-\n # lity the file is lost.\n \n # first we consider there is no redundancy\n if len(disks) >= 2*(spread_factor + 1) - chunk_count:\n return probability_configuration * sum([probability_at_least_d_fail_matrix(config, d, chunk_count, reliability)\n for config in configurations])\n # This condition cover the case with redundancies\n else:\n return probability_configuration * sum([frequency(config, len(disks), spread_factor) *\n probability_at_least_d_fail_matrix(config, d, chunk_count, reliability)\n for config in configurations])", "def probability_file_loss(disks, chunk_count, spread_factor, d, disk_reliability):\n # First we calculate the probability that a configuration is selected.\n probability_configuration = (1.0*(factorial(spread_factor - chunk_count + 1)*factorial(chunk_count - 1))\n / (len(disks)*factorial(spread_factor)))\n \n # Then, we generate the list of all feasible configurations as a function of \n # the number of disks, disk_count, the number of chunks, chunk_count and the spread factor.\n #configurations = list(map(lambda t: map(lambda e: e + 1, t),\n # feasible_configurations(disk_count, chunk_count, spread_factor)))\n \n configurations = feasible_configurations(len(disks), chunk_count, spread_factor)\n\n # Finally, for each feasible configuration where chunks are stored, we calculate the probabi-\n # lity the file is lost.\n \n # first we consider there is no redondancy\n if len(disks) >= 2*(spread_factor + 1) - chunk_count:\n return probability_configuration * sum([probability_at_least_d_fail(config, d, chunk_count, disk_reliability)\n for config in configurations])\n # This condition cover the case with redondancies\n else:\n return probability_configuration * sum([frequency(config, len(disks), spread_factor)*probability_at_least_d_fail(config, d, chunk_count, disk_reliability)\n for config in configurations])", "def file_loss_delta_matrix(delta, mean_reliability, experiments, disks, chunk_count, spread_factor, d):\n \n for e in experiments:\n # First we generate the list of disk reliability between mean_reliability-0.5*delta and mean_reliability-0.5*delta.\n\n lower_bound = mean_reliability - 0.5 * delta\n upper_bound = mean_reliability + 0.5 * delta\n\n reliability = dict(zip(disks, uniform(low=lower_bound, high=upper_bound , size=len(disks))))\n reliability[disks[-1]] = len(disks) * mean_reliability - sum([reliability[disk] for disk in disks[:-1]])\n \n # Then we calculate the probability of file loss for the reliability list \n yield probability_file_loss_matrix(disks, chunk_count, spread_factor, d, reliability)", "def matFail(dim):\n bst = dim[0]\n tst = dim[1]\n tsk = dim[2]\n\n Et = (Esk * tsk) + (Est * ((bst * tst) / bsk))\n Nmat = Et*maxstrain # Critical Load\n rsf = Nmat/Nx\n return rsf - 1.1 # Using a target Reserve Factor of >=1.1", "def test_ppt_distinguishability_yyd_density_matrices():\n psi_0 = bell(0)\n psi_1 = bell(2)\n psi_2 = bell(3)\n psi_3 = bell(1)\n\n x_1 = np.kron(psi_0, psi_0)\n x_2 = np.kron(psi_1, psi_3)\n x_3 = np.kron(psi_2, psi_3)\n x_4 = np.kron(psi_3, psi_3)\n\n rho_1 = x_1 * x_1.conj().T\n rho_2 = x_2 * x_2.conj().T\n rho_3 = x_3 * x_3.conj().T\n rho_4 = x_4 * x_4.conj().T\n\n states = [rho_1, rho_2, rho_3, rho_4]\n probs = [1 / 4, 1 / 4, 1 / 4, 1 / 4]\n\n # Min-error tests:\n primal_res = ppt_distinguishability(states, probs=probs, dist_method=\"min-error\", strategy=True)\n dual_res = ppt_distinguishability(states, probs=probs, dist_method=\"min-error\", strategy=False)\n\n np.testing.assert_equal(np.isclose(primal_res, 7 / 8, atol=0.001), True)\n np.testing.assert_equal(np.isclose(dual_res, 7 / 8, atol=0.001), True)\n\n primal_res = ppt_distinguishability(\n states, probs=probs, dist_method=\"unambiguous\", strategy=True\n )\n dual_res = ppt_distinguishability(\n states, probs=probs, dist_method=\"unambiguous\", strategy=False\n )\n\n np.testing.assert_equal(np.isclose(primal_res, 3 / 4, atol=0.001), True)\n np.testing.assert_equal(np.isclose(dual_res, 3 / 4, atol=0.001), True)", "def probability_at_least_d_fail_equal_reliability(d, chunk_count, reliability):\n \n return sum([loss_probability(reliability, k, chunk_count) for k in range(d, chunk_count + 1)])", "def discretization_error(hmsm, descendant_level, parent_level):\n if descendant_level==0:\n pi_dict = hmsm.get_full_stationary_distribution()\n # pi is an np array of the probabilities, sorted by their ids:\n pi = np.array(list(pi_dict.values())) #just the distribution\n pi = pi[np.argsort(list(pi_dict.keys()))] # sort by the ids\n else:\n T, ids = hmsm.get_level_T(descendant_level, 1)\n pi = stationary_distribution(T)\n pi = pi[np.argsort(ids)]\n\n induced_pi, ids = induced_distribution(hmsm, descendant_level, parent_level)\n induced_pi = induced_pi[np.argsort(ids)]\n\n return D_KL(pi, induced_pi)", "def prob4():\n\n\n N = 500000\n random_draws = np.random.multivariate_normal(mean = [-1,1], cov =[[1,0],[0,1]], size = N)\n\n h = lambda x: x[0] < -1 and x[1] > 1\n f = lambda x: stats.multivariate_normal(mean = [ 0, 0]).pdf(x)\n g = lambda x: stats.multivariate_normal(mean = [-1, 1]).pdf(x)\n\n probability = [h(random_draws[i]) * f(random_draws[i]) / g(random_draws[i]) for i in range(N)]\n\n return 1./N * np.sum(probability)", "def prob(throw, n, d=6, type='classical'):\n count = 0\n table = throw_table(n, d, type)\n for t in table:\n if sum(t) == throw:\n count += 1\n \n return float(count)/len(table)", "def Failure_Simulation(Num):\n #Define selected hurricanes\n Hurricanes = list()\n #Hcd.Hnum = 1\n TXpower.single_perform = np.empty([Hcd.Hnum, Num], dtype = object)\n length = np.zeros([Hcd.Hnum, Num]) #adjust the length of different performance list\n TX_TP.fail_history_final = np.empty(Hcd.Hnum, dtype = object)\n TX_TP.fail_history = np.empty(Hcd.Hnum, dtype = object)\n for i in range(Hcd.Hnum):\n TX_TP.fail_history_final[i] = []\n TX_TP.fail_history[i] = []\n \n #Monte Carlo Simulation to calculate the performance\n for i in range(Hcd.Hnum):\n Hurricanes.append(Hurricane(Hcd.Hurricane_name[i], TXpower, Hcd.Latitude[i], Hcd.Longitude[i], Hcd.color[i]))\n Hurricanes[-1].verticexy(Hcd.Data[i], filelocation = Hcd.Data_Location, Type = 'local')\n Hurricanes[-1].trajectory_plot(townlat = 29.3013, townlon = -94.7977)\n Hurricanes[-1].Failprob(mu = 304, sigma = 1, a = 0.5, b = 1)\n# if(i == 0): #Since fail probability is nearly the same among all hurricane sceneria, we need to add some noise\n# Hurricanes[-1].failprob -= 0.3\n \n for j in range(Num):\n TX_TP.fail_simu(Hurricanes[-1])\n TX_TP.Cascading_failure(pd.up_bound, pd.low_bound)\n TX_TP.fail_history[i].append(TX_TP.failsequence)\n TX_TP.fail_history_final[i].append(TX_TP.failsequence[-1]) ##Track down the final stable state for later use to calculate the conditional probability\n TXpower.single_perform[i, j] = TXpower.fperformance\n length[i, j] = len(TXpower.fperformance)\n \n return length, Hurricanes", "def prob4():\n #get Omega, F, and initialize\n Omega = np.array([[-3/2,3/4],[0,1],[0,1/2],[0,1]])\n f = lambda x: np.exp(np.sum(-x**2/2,axis=0))/(2*np.pi)**(2)\n means, cov = np.zeros(4), np.eye(4)\n truth = scipy.stats.mvn.mvnun(list(Omega[:,0]),list(Omega[:,1]), means, cov)[0]\n domain = np.logspace(1,5,20)\n approxs = []\n error = []\n for N in domain:\n #calculate approx for various sizes of samples\n approx = mc_integrate(f,Omega[:,0],Omega[:,1],N)\n approxs.append(approx)\n #calculate relative err.\n error.append(np.abs((truth-approx)/truth))\n #PLOT it all\n plt.title(\"Error vs Sample Size\")\n plt.plot(domain,1/np.sqrt(domain),label = \"1/sqrt(N)\")\n plt.plot(domain,error,label = \"Error\")\n plt.loglog()\n plt.xlabel(\"N\")\n plt.ylabel(\"Relative Error\")\n plt.legend()\n plt.show()", "def prob4():\n#raise NotImplementedError(\"Problem 4 Incomplete\")\n h = lambda x : x[0] < -1 and x[1] > 1\n f = lambda x : stats.multivariate_normal.pdf(x,mean=np.array([0,0]),cov=np.eye(2))\n g = lambda x : stats.multivariate_normal.pdf(x,mean=np.array([-1,1]),cov=np.eye(2))\n X = np.random.multivariate_normal(mean=np.array([-1,1]),cov=np.eye(2),size=10000)\n return 1./10000*np.sum(np.apply_along_axis(h,1,X)*np.apply_along_axis(f,1,X)/np.apply_along_axis(g,1,X))", "def part_2(R):\n # initialize variables\n l, m, size, noise = 10, 20, 50000, False\n samples, loops = size / 10, 20\n lrs = [1.5, 0.25, 0.03, 0.005, 0.001]\n alphas = [1.1, 1.01, 1.005, 1.0005, 1.0001]\n gammas = [2.0, 0.3, 0.04, 0.006, 0.001]\n error_p, error_pm, error_w, error_wm, error_a = [], [], [], [], []\n\n # loop for n\n for n in range(40, 240, 40):\n print 'n = {}'.format(n)\n # divide dataset: 10% - training, 10% - test. (fixed random seed)\n (y, x) = gen(l, m, n, size, noise)\n random.seed(1)\n left, right = random.sample(range(10),2)\n x_train, x_test = x[left*samples:(left+1)*samples], x[right*samples:(right+1)*samples]\n y_train, y_test = y[left*samples:(left+1)*samples], y[right*samples:(right+1)*samples]\n \n # build online learning algorithms, and count mistakes made\n perceptron = Perceptron(R, x_train, x_test, y_train, y_test, n, samples, size)\n error_p.append(perceptron.mistakes)\n # [517, 607, 605, 595, 611]\n perceptron_margin = Perceptron_Margin(R, x, x_train, x_test, y, y_train, y_test, n, samples, size, loops, lrs)\n error_pm.append(perceptron_margin.mistakes)\n # [737, 684, 640, 699, 603]\n winnon = Winnon(R, x, x_train, x_test, y, y_train, y_test, n, samples, size, loops, alphas)\n error_w.append(winnon.mistakes)\n # [118, 235, 300, 352, 378]\n winnon_margin = Winnon_Margin(R, x, x_train, x_test, y, y_train, y_test, n, samples, size, loops, alphas, gammas)\n error_wm.append(winnon_margin.mistakes)\n # [559, 615, 305, 349, 374]\n adagrad = AdaGrad(R, x, x_train, x_test, y, y_train, y_test, n, samples, size, loops, lrs)\n error_a.append(adagrad.mistakes)\n # [583, 543, 527, 548, 601]\n\n # draw plots\n draw_2(l, m, R, error_p, error_pm, error_w, error_wm, error_a)", "def _compute_model_prob(self, per_list_logodds):\n with tf.compat.v1.name_scope(name='compute_model_prob'):\n return tf.stop_gradient(\n tf.exp(-self._alpha *\n (per_list_logodds -\n tf.reduce_min(per_list_logodds, axis=2, keepdims=True))))", "def test_ppt_distinguishability_four_bell_states():\n rho_1 = bell(0) * bell(0).conj().T\n rho_2 = bell(1) * bell(1).conj().T\n rho_3 = bell(2) * bell(2).conj().T\n rho_4 = bell(3) * bell(3).conj().T\n\n e_0, e_1 = basis(2, 0), basis(2, 1)\n e_00 = np.kron(e_0, e_0)\n e_11 = np.kron(e_1, e_1)\n\n eps = 0.5\n resource_state = np.sqrt((1 + eps) / 2) * e_00 + np.sqrt((1 - eps) / 2) * e_11\n resource_state = resource_state * resource_state.conj().T\n\n states = [\n np.kron(rho_1, resource_state),\n np.kron(rho_2, resource_state),\n np.kron(rho_3, resource_state),\n np.kron(rho_4, resource_state),\n ]\n probs = [1 / 4, 1 / 4, 1 / 4, 1 / 4]\n\n exp_res = 1 / 2 * (1 + np.sqrt(1 - eps**2))\n\n primal_res = ppt_distinguishability(states, probs=probs, dist_method=\"min-error\", strategy=True)\n dual_res = ppt_distinguishability(states, probs=probs, dist_method=\"min-error\", strategy=False)\n\n np.testing.assert_equal(np.isclose(primal_res, exp_res, atol=0.001), True)\n np.testing.assert_equal(np.isclose(dual_res, exp_res, atol=0.001), True)", "def precomp_threshold(dof, len_sim=1e5, beta=.75):\n for d in dof:\n cdt = GaussianCusum(arl=None, beta=beta)\n cdt.fit(x=np.zeros((1, d)), estimate_threshold=True, len_simulation=len_sim,\n verbose=True, precompute_thresholds=True)", "def precomp_threshold(dof, len_sim=1e5, beta=.75):\n for d in dof:\n cdt = GaussianCusum(arl=None, beta=beta)\n cdt.fit(x=np.zeros((1, d)), estimate_threshold=True, len_simulation=len_sim,\n verbose=True, precompute_thresholds=True)", "def prob4(d = 500): \n #import the plane data\n planeData = np.load(\"plane.npy\")\n \n tplane = planeData[:,0]\n alpha = np.deg2rad(planeData[:,1])\n beta = np.deg2rad(planeData[:,2])\n \n l = len(tplane)\n \n #define x and y functions\n def x(n):\n# Gives x position\n return d * np.tan(beta[n]) / (np.tan(beta[n]) - np.tan(alpha[n]))\n def y(n):\n# Gives y position\n return d * np.tan(beta[n]) * np.tan(alpha[n]) / (np.tan(beta[n]) - np.tan(alpha[n]))\n \n #define x and y prime as we will see them\n def xprime(n):\n# Gives the approximate derivative of x\n if n == 0:\n return fdq1(x, n, h = 1)\n elif n == l-1:\n return bdq1(x, n, h = 1)\n elif n > 0 and n < l:\n return cdq2(x, n, h = 1)\n else:\n return 0\n \n def yprime(n):\n# Gives the approximate derivative of y\n if n == 0:\n return fdq1(y, n, h = 1)\n elif n == l-1:\n return bdq1(y, n, h = 1)\n elif n > 0 and n < l:\n return cdq2(y, n, h = 1)\n else:\n return 0\n \n #define speed from x and y prime\n def speed(n):\n# print(\"speed(n) where n = \" + str(n))\n return np.sqrt((xprime(n))**2 + (yprime(n))**2)\n \n #Finally get the speed from the information we have\n spd = []\n X = []\n Y = []\n for i in range(0, l):\n spd.append(speed(i))\n X.append(x(i))\n Y.append(y(i))\n \n return spd\n \n raise NotImplementedError(\"Problem 4 Incomplete\")", "def simulated_dph(grbdir,typ,t_src,alpha,beta,E0,A):\n\tfilenames = glob.glob(grbdir + \"/MM_out/*\")\n\tbadpixfile = glob.glob(grbdir + \"/*badpix.fits\")[0]\n\tfilenames.sort()\n\tpix_cnts = np.zeros((16384,len(filenames)))\n\terr_pix_cnts = np.zeros((16384,len(filenames)))\n\ten = np.arange(5, 261., .5)\n\tsel = (en>=100) & (en <= 150)\n\ten_range = np.zeros(len(filenames))\n\tfor f in range(len(filenames)):\n\t\ten_range[f] = filenames[f][20:26]\n\terr_100_500 = (100.0 <= en_range.astype(np.float)) & (en_range.astype(np.float) <= 500.0)\n\terr_500_1000 = (500.0 < en_range.astype(np.float)) & (en_range.astype(np.float) <= 1000.0)\n\terr_1000_2000 = (1000.0 < en_range.astype(np.float)) & (en_range.astype(np.float) <= 2000.0)\n\texist_1000_2000 = np.where(err_1000_2000 == True)\n\tE = np.array([])\n\t\n\tprint \"Indices where energy is in between 1000 and 2000 :\",exist_1000_2000[0]\n\t\n\tfor i,f in enumerate(filenames):\n\t\t\tdata = fits.getdata(f + \"/SingleEventFile.fits\")\n\t\t\tE = np.append(E, float(f[20:26]))\n\t\t\terror = np.sqrt(data) \n\t\t\tdata[:,~sel] = 0.\n\t\t\terror[:,~sel] = 0.\n\t\t\tpix_cnts[:,i] = data.sum(1)*model(E[i], alpha, beta, E0, A,typ)/55.5\n\t\t\terr_pix_cnts[:,i] = np.sqrt(((error*model(E[i], alpha, beta, E0, A,typ)/55.5)**2).sum(1))\t\t\n\t\t\t\n\tpix_cnts_total = np.zeros((16384,))\n\terr_100_500_total = np.sqrt((err_pix_cnts[:,err_100_500]**2).sum(1))*(E[err_100_500][1]-E[err_100_500][0])\n\terr_500_1000_total = np.sqrt((err_pix_cnts[:,err_500_1000]**2).sum(1))*(E[err_500_1000][1]-E[err_500_1000][0])\n\n\tif (len(exist_1000_2000[0]) != 0):\n\t\terr_1000_2000_total = np.sqrt((err_pix_cnts[:,err_1000_2000]**2).sum(1))*(E[err_1000_2000][1]-E[err_1000_2000][0])\n\telse :\n\t\terr_1000_2000_total = 0\n\t\n\terr_pix_cnts_total = np.sqrt(err_100_500_total**2 + err_500_1000_total**2 + err_1000_2000_total**2) # dE is 5 from 100-500, 10 from 500-1000, 20 from 1000-2000\n\n\tfor i in range(16384):\n\t\t\tpix_cnts_total[i] = simps(pix_cnts[i,:], E)\t\t\t\n\n\tquad0pix = pix_cnts_total[:4096]\n\tquad1pix = pix_cnts_total[4096:2*4096]\n\tquad2pix = pix_cnts_total[2*4096:3*4096]\n\tquad3pix = pix_cnts_total[3*4096:]\n\t\t\n\terr_quad0pix = err_pix_cnts_total[:4096]\n\terr_quad1pix = err_pix_cnts_total[4096:2*4096]\n\terr_quad2pix = err_pix_cnts_total[2*4096:3*4096]\n\terr_quad3pix = err_pix_cnts_total[3*4096:]\n\t\n\tquad0 = np.reshape(quad0pix, (64,64), 'F')\n\tquad1 = np.reshape(quad1pix, (64,64), 'F')\n\tquad2 = np.reshape(quad2pix, (64,64), 'F')\n\tquad3 = np.reshape(quad3pix, (64,64), 'F')\n\t\t\n\terr_quad0 = np.reshape(err_quad0pix, (64,64), 'F')\n\terr_quad1 = np.reshape(err_quad1pix, (64,64), 'F')\n\terr_quad2 = np.reshape(err_quad2pix, (64,64), 'F')\n\terr_quad3 = np.reshape(err_quad3pix, (64,64), 'F')\n\t\n\tsim_DPH = np.zeros((128,128), float)\n\tsim_err_DPH = np.zeros((128,128), float)\n\t\n\tsim_DPH[:64,:64] = np.flip(quad0, 0)\n\tsim_DPH[:64,64:] = np.flip(quad1, 0)\n\tsim_DPH[64:,64:] = np.flip(quad2, 0)\n\tsim_DPH[64:,:64] = np.flip(quad3, 0)\n\t\n\tsim_err_DPH[:64,:64] = np.flip(err_quad0, 0)\n\tsim_err_DPH[:64,64:] = np.flip(err_quad1, 0)\n\tsim_err_DPH[64:,64:] = np.flip(err_quad2, 0)\n\tsim_err_DPH[64:,:64] = np.flip(err_quad3, 0)\n\n\tbadpix = fits.open(badpixfile)\n\tdphmask = np.ones((128,128))\n\t\n\tbadq0 = badpix[1].data # Quadrant 0\n\tbadpixmask = (badq0['PIX_FLAG']!=0)\n\tdphmask[(63 - badq0['PixY'][badpixmask]) ,badq0['PixX'][badpixmask]] = 0\n\n\tbadq1 = badpix[2].data # Quadrant 1\n\tbadpixmask = (badq1['PIX_FLAG']!=0)\n\tdphmask[(63 - badq1['PixY'][badpixmask]), (badq1['PixX'][badpixmask]+64)] = 0\n\n\tbadq2 = badpix[3].data # Quadrant 2\n\tbadpixmask = (badq2['PIX_FLAG']!=0)\n\tdphmask[(127 - badq2['PixY'][badpixmask]), (badq2['PixX'][badpixmask]+64)] = 0\n\n\tbadq3 = badpix[4].data # Quadrant 3\n\tbadpixmask = (badq3['PIX_FLAG']!=0)\n\tdphmask[(127 - badq3['PixY'][badpixmask]), badq3['PixX'][badpixmask]] = 0\n\t\t\t\n\toneD_sim = (sim_DPH*dphmask).flatten()\n\n\treturn oneD_sim*t_src,sim_DPH*t_src,dphmask,sim_err_DPH*t_src", "def probability(N_dr, L_opmin, L_opmax, L_min, L_max, L_d):\n opening_nomullignas = []\n opening_withmullignas = []\n sum_nomulligans = 0\n sum_withmulligans = 0\n mulligan_coeff = 0\n\n for i in range(L_opmin, min(L_opmax + 1, 8)): # first make a list of tuples of the form:\n # (number_of_lands_in_opening_hand, probability_of_drawing_such_a_hand)\n a = hypergeom(i, 7, 60, L_d)\n opening_nomullignas.append((i, a))\n mulligan_coeff = mulligan_coeff + a # this will be used later for calculating the probability of\n # taking the mulligan and is used as a coefficient before the mulligan sum\n for (x, y) in opening_nomullignas: # use the list of tuples to calculate the first part of equation 5\n partial_nomulligans = 0\n for j in range(L_min - x, L_max - x + 1):\n partial_nomulligans = partial_nomulligans + hypergeom(j, N_dr, 53, L_d - x)\n sum_nomulligans = sum_nomulligans + partial_nomulligans * y\n\n mulligan_coeff = 1 - mulligan_coeff # probability of mulliganing\n for i in range(L_opmin, min(L_opmax + 1, 7)): # doing the same thing as before, but drawing 6 instead of 7 cards\n a = hypergeom(i, 6, 60, L_d)\n opening_withmullignas.append((i, a))\n\n for (x, y) in opening_withmullignas:\n partial_withmulligans = 0\n for j in range(L_min - x, L_max - x + 1):\n partial_withmulligans = partial_withmulligans + hypergeom(j, N_dr, 54, L_d - x)\n sum_withmulligans = sum_withmulligans + partial_withmulligans * y\n total_withmulligans = mulligan_coeff * sum_withmulligans\n\n return total_withmulligans + sum_nomulligans", "def compare():\n eb = 1\n p = 0.5\n R = 0.5\n N = 150 # set the error count to reach\n\n domain = np.linspace(0, 10, 11)\n hard_domain = np.linspace(0, 8, 9)\n soft_domain = np.linspace(0, 6, 7)\n hard_decibels = 10 ** (hard_domain / 10)\n soft_decibels = 10 ** (soft_domain / 10)\n\n # get results for hard decoding\n nos = eb / hard_decibels\n hard_results = []\n for no in nos:\n print(np.where(nos == no)[0][0])\n experiment = ViterbiHard(eb, no / R)\n bit_count = 0\n error_count = 0\n for output in experiment.run():\n bit_count += 1\n if output[0] != output[1]:\n error_count += 1\n if error_count == N:\n hard_results.append(error_count / bit_count)\n break\n\n # get results for soft decoding\n nos = eb / soft_decibels\n soft_results = []\n for no in nos:\n print(np.where(nos == no)[0][0])\n experiment = ViterbiSoft(eb, no / R)\n bit_count = 0\n error_count = 0\n for output in experiment.run():\n bit_count += 1\n if output[0] != output[1]:\n error_count += 1\n if error_count == N:\n soft_results.append(error_count / bit_count)\n break\n\n decibels = 10 ** (domain / 10)\n nos = eb / decibels\n taus = nos / 4 / np.sqrt(eb) * np.log((1 - p) / p)\n plt.semilogy(hard_domain, np.array(hard_results), label='Hard-decision')\n plt.semilogy(soft_domain, np.array(soft_results), label='Soft-decision')\n plt.semilogy(domain, norm.sf((taus + np.sqrt(eb)) / np.sqrt(nos / 2)) * (1 - p) +\n norm.sf((np.sqrt(eb) - taus) / np.sqrt(nos / 2)) * p, label='Expectation ($p=0.5$)')\n plt.xlabel('$E_b/N_0$ (dB)')\n plt.ylabel('Probability of bit error')\n plt.legend(loc='lower left')\n plt.show()", "def main():\n N = 201 # Amount of gridpoints, odd number to include 0\n L = 10 # Size of the system\n k = 50 # Amount of energies and states calculated\n x = y = np.linspace(-L/2,L/2,N) # Gridpoints\n h = x[1]-x[0] # Spacing of gridpoints\n\n # Solve the system with and without perturbation\n E,psi,E_p,psi_p = fdm_2d(N,L,x,y,h,k)\n\n # Print the first two energies and the absolute error of the energies\n print('Energies of the two lowest states:')\n print('E_00 = %.4f' % E[0])\n print('E_01 = %.4f' % E[1], '\\n')\n print('Absolute error for E_00: %.4e' % np.abs(E[0]-1))\n print('Absolute error for E_01: %.4e' % np.abs(E[1]-2))\n\n print('\\nEnergies of the two lowest states after perturbation:')\n print('E_00 = %.4f' % E_p[0])\n print('E_01 = %.4f' % E_p[1])\n\n # Calculate the normalized densities of the states\n densities_norm = np.zeros((k,N,N))\n densities_norm_p = np.zeros((k,N,N))\n for i in range(k):\n # meshgrid form\n state = np.reshape(psi.T[i],(N,N))\n state_p = np.reshape(psi_p.T[i],(N,N))\n densities_norm[i] = normalized_density(state,x)\n densities_norm_p[i] = normalized_density(state_p,x)\n\n # Analytical solution of the ground state\n X,Y = np.meshgrid(x,y)\n psi00_exact = phi(X,0)*phi(Y,0)\n psi00_exact_density = normalized_density(psi00_exact,x)\n\n print('\\nMaximum absolute error of the normalized ground state densities of the unperturbated system:')\n print('errmax = {:.4e}'.format(np.max(np.abs(densities_norm[0]-psi00_exact_density))))\n\n # Plotting the ground state density of the unperturbated system\n fig1 = plt.figure(figsize=plt.figaspect(0.5))\n ax = fig1.add_subplot(1,2,1,projection='3d')\n surf1 = ax.plot_surface(X, Y, densities_norm[0], cmap=cm.coolwarm,\n linewidth=0, antialiased=False)\n ax.set_xlabel('X')\n ax.set_ylabel('Y')\n fig1.suptitle(r'Normalized ground state density $|\\psi|^2$ using FDM')\n ax = fig1.add_subplot(1,2,2)\n ax.imshow(densities_norm[0],extent=[-L/2,L/2,-L/2,L/2])\n plt.savefig(os.path.join(path,'FDM_psi00_unperturbated.png'))\n plt.close()\n\n\n fig2 = plt.figure(figsize=plt.figaspect(0.5))\n ax = fig2.add_subplot(1,2,1,projection='3d')\n surf2 = ax.plot_surface(X, Y, psi00_exact_density, cmap=cm.coolwarm,\n linewidth=0, antialiased=False)\n\n\n # Plotting the ground state density of the perturbated system\n fig1 = plt.figure(figsize=plt.figaspect(0.5))\n ax = fig1.add_subplot(1,2,1,projection='3d')\n surf1 = ax.plot_surface(X, Y, densities_norm_p[0], cmap=cm.coolwarm,\n linewidth=0, antialiased=False)\n ax.set_xlabel('X')\n ax.set_ylabel('Y')\n fig1.suptitle(r'Normalized ground state density $|\\psi|^2$ of the perturbated system using FDM')\n ax = fig1.add_subplot(1,2,2)\n ax.imshow(densities_norm_p[0],extent=[-L/2,L/2,-L/2,L/2])\n plt.savefig(os.path.join(path,'FDM_psi00_perturbated.png'))\n plt.close()\n\n fig2 = plt.figure(figsize=plt.figaspect(0.5))\n ax = fig2.add_subplot(1,2,1,projection='3d')\n surf2 = ax.plot_surface(X, Y, psi00_exact_density, cmap=cm.coolwarm,\n linewidth=0, antialiased=False)\n\n # Plotting the analytic ground state density\n fig1 = plt.figure(figsize=plt.figaspect(0.5))\n ax = fig1.add_subplot(1,2,1,projection='3d')\n surf1 = ax.plot_surface(X, Y, psi00_exact_density, cmap=cm.coolwarm,\n linewidth=0, antialiased=False)\n ax.set_xlabel('X')\n ax.set_ylabel('Y')\n fig1.suptitle(r'Analytical normalized ground state density $|\\psi|^2$')\n ax = fig1.add_subplot(1,2,2)\n ax.imshow(psi00_exact_density,extent=[-L/2,L/2,-L/2,L/2])\n plt.savefig(os.path.join(path,'exact_psi00.png'))\n plt.close()\n\n # Plot some of the other densities and save them as pdf\n for i in range(1,20):\n density = densities_norm[i]\n fig = plt.figure(figsize=plt.figaspect(0.5))\n plt.imshow(density,extent=[-L/2,L/2,-L/2,L/2])\n plt.title('n={}'.format(i))\n plt.savefig(os.path.join(path,'FDM_unperturbated{}.png'.format(i)))\n plt.close()\n\n density_p = densities_norm_p[i]\n fig = plt.figure(figsize=plt.figaspect(0.5))\n plt.imshow(density_p,extent=[-L/2,L/2,-L/2,L/2])\n plt.title('n={}'.format(i))\n plt.savefig(os.path.join(path,'FDM_perturbated{}.png'.format(i)))\n plt.close() \n\n # Plot analytical states until nx,ny = 5\n for nx in range(6):\n for ny in range(6):\n state = phi(X,nx)*phi(Y,ny)\n density = normalized_density(state,x)\n plt.figure()\n plt.imshow(density,extent=[-L/2,L/2,-L/2,L/2])\n plt.title('$n_x={}, n_y={}$'.format(nx,ny))\n plt.savefig(os.path.join(path,'analytical_state_{}_{}.png'.format(nx,ny)))\n plt.close()\n\n # Get analytical energies from nx,ny = 0 to 10\n n = 10\n energies = analytical_energies(n)\n\n # Plot k analytical and the FDM energies\n index = np.arange(k)\n plt.figure()\n plt.plot(index,energies[0:k],label='Analytical energies')\n plt.plot(index,E,label='Unperturbated energies')\n plt.plot(index,E_p,label='Perturbated energies')\n plt.legend()\n plt.xlabel('n')\n plt.ylabel(r'$\\tilde{E} = \\frac{E}{\\hbar\\omega}$')\n plt.title('Energies')\n plt.savefig(os.path.join(path,'energies.png'))\n plt.close()", "def run_test(d):\n\n ######### Problem Specification\n\n # Data generation parameters\n prior_mu_z = np.zeros(d, dtype=np.float32) # Prior mean\n prior_sigma_z = np.eye(d, dtype=np.float32) # Prior covariance matrix\n\n # True model parameters\n num_range = np.arange(-(d-1)/2, (d+1)/2, dtype=np.float32)\n\n t_delta = num_range / 5 \n\n if d == 1:\n t_sigma = np.ones(1)\n else: \n # Allow sigma to range from 0.1 to 1\n t_sigma = 36/(10*(d-1)**2) * num_range**2 + 0.1 \n\n ######### Variable Initialization\n\n # Initial model parameters - same across all methods\n init_delta = prior_mu_z.copy()\n init_log_sigma = 3 * np.ones(d)\n\n # Initial HVAE variational parameters\n init_T = 5.\n init_eps = 0.005 * np.ones(d)\n max_eps = params['max_eps'] * np.ones(d)\n init_logit_eps = np.log(init_eps/(max_eps - init_eps))\n init_log_T_0 = np.log(init_T - 1)\n\n # Initial NF variational parameters\n init_u_pre_reparam = scipy.stats.truncnorm.rvs(-2, 2, scale=0.1, size=d)\n init_w = scipy.stats.truncnorm.rvs(-2, 2, scale=0.1, size=d)\n init_b = 0.1\n\n # Initial VAE parameters\n init_mu_z = prior_mu_z.copy()\n init_log_sigma_z = np.ones(d)\n\n ######### Set up models\n\n HVAE_model_1 = HVAE(\n ['delta', 'log_sigma', 'logit_eps', 'log_T_0'],\n [init_delta, init_log_sigma, init_logit_eps, init_log_T_0], \n 'HVAE_1', d, params['HVAE_K_1'])\n HVAE_model_2 = HVAE(\n ['delta', 'log_sigma', 'logit_eps', 'log_T_0'],\n [init_delta, init_log_sigma, init_logit_eps, init_log_T_0], \n 'HVAE_2', d, params['HVAE_K_2'])\n\n HVAE_model_notemp_1 = HVAE(\n ['delta', 'log_sigma', 'logit_eps'],\n [init_delta, init_log_sigma, init_logit_eps], \n 'HVAE_notemp_1', d, params['HVAE_K_1'])\n HVAE_model_notemp_2 = HVAE(\n ['delta', 'log_sigma', 'logit_eps'], \n [init_delta, init_log_sigma, init_logit_eps],\n 'HVAE_notemp_2', d, params['HVAE_K_2'])\n\n NF_model_1 = NF(\n ['delta', 'log_sigma', 'u_pre_reparam', 'w', 'b'],\n [init_delta, init_log_sigma, init_u_pre_reparam, init_w, init_b],\n 'NF_1', d, params['NF_K_1'])\n NF_model_2 = NF(\n ['delta', 'log_sigma', 'u_pre_reparam', 'w', 'b'],\n [init_delta, init_log_sigma, init_u_pre_reparam, init_w, init_b],\n 'NF_2', d, params['NF_K_2'])\n\n VB_model = VB(['delta', 'log_sigma', 'mu_z', 'log_sigma_z'], \n [init_delta, init_log_sigma, init_mu_z, init_log_sigma_z], 'VB', d)\n\n model_list = [HVAE_model_1, HVAE_model_2, HVAE_model_notemp_1, \n HVAE_model_notemp_2, NF_model_1, NF_model_2, VB_model]\n \n ######### Generate Training Data & Save - One for each test\n\n train_data_list = []\n\n for i in range(params['n_tests']):\n z = np.random.multivariate_normal(prior_mu_z, prior_sigma_z)\n x = np.random.multivariate_normal(z + t_delta, np.diag(t_sigma**2), \n size=params['n_data'])\n train_data_list.append(x)\n\n # Folder should have already been created in the initializations\n data_path = os.path.join('save', str(d), 'train_data.p')\n pickle.dump(train_data_list, open(data_path, 'wb')) \n\n ######### Train models\n\n sess = tf.Session()\n sess.run(tf.global_variables_initializer())\n\n # Store the final parameter values for all test runs in this dictionary\n final_params = {}\n\n for m in model_list:\n\n final_values = []\n\n for i in range(params['n_tests']):\n (delta, sigma) = m.train(sess, train_data_list[i], i)\n final_values.append((delta, sigma))\n\n final_params[m.model_name] = final_values.copy()\n\n ######### Test models using difference between parameters\n\n param_diffs = {}\n\n for m in model_list:\n\n diffs = []\n\n for i in range(params['n_tests']):\n delta = final_params[m.model_name][i][0]\n sigma = final_params[m.model_name][i][1]\n\n delta_diff = np.sum((delta - t_delta)**2)\n sigma_diff = np.sum((sigma - t_sigma)**2)\n\n diffs.append((delta_diff, sigma_diff))\n\n param_diffs[m.model_name] = diffs.copy()\n\n # Save parameter differences in a pickle file\n diff_path = os.path.join('save', str(d), 'all_diffs.p')\n pickle.dump(param_diffs, open(diff_path, 'wb'))", "def test_densities():\n\n actual, r, wt = GridGenerator.make_grid(400)\n grid = 4*pi*r**2*wt\n\n data = AtomData()\n\n print(\"\\nINTEGRATED DENSITY TEST\")\n print(\"=======================\")\n for a in list(data.nuclear_charge.keys()):\n atom = Atom(a)\n Nel = data.electron_count[a]\n d0, d1, g0, g1, t0, t1, l0, l1 = atom.get_densities(r)\n\n # Count electrons per spin channel\n s_occ = AtomData.s_occ.get(a, [0, 0])\n p_occ = AtomData.p_occ.get(a, [0, 0])\n d_occ = AtomData.d_occ.get(a, [0, 0])\n f_occ = AtomData.f_occ.get(a, [0, 0])\n nela = np.sum(s_occ[0])+np.sum(p_occ[0])+np.sum(d_occ[0])+np.sum(f_occ[0])\n nelb = np.sum(s_occ[1])+np.sum(p_occ[1])+np.sum(d_occ[1])+np.sum(f_occ[1])\n assert(nela+nelb == Nel)\n\n id0 = np.dot(d0, grid)\n id1 = np.dot(d1, grid)\n\n diff_0 = id0 - nela\n percent_diff_0 = 100*diff_0/nela\n\n # Check to catch for Hydrogen having no beta electrons\n if nelb > 0.0:\n diff_1 = id1 - nelb\n percent_diff_1 = 100*diff_1/nelb\n else:\n diff_1 = 0.0\n percent_diff_1 = 0.0\n\n print(\"{:>3} - N_0 = ({:4.1f}) {:+2.6e}%, N_1 = ({:4.1f}) {:+2.6e}%, {:}\".format(a, id0, percent_diff_0, id1, percent_diff_1, \"PASSED\" if max(abs(diff_0), abs(diff_1)) < 1e-4 else \"FAILED - \"))\n\n print(\"\\nINTEGRATED KINETIC TEST\")\n print(\"=======================\")\n for a in list(data.ke_test.keys()):\n atom = Atom(a)\n t_bm = data.ke_test[a]\n d0, d1, g0, g1, t0, t1, l0, l1 = atom.get_densities(r)\n\n it0 = np.dot(t0, grid)\n it1 = np.dot(t1, grid)\n itot = it0 + it1\n\n diff = itot - t_bm\n print(\"{:>3} - T = {:+.6e}%, {:}\".format(a, 100*diff/t_bm, \"PASSED\" if abs(100*diff/t_bm) < 1e-2 else \"FAILED - \"))\n\n\n # The integral of the Laplacian over all space should be 0. Check that.\n print(\"\\nINTEGRATED LAPLACIAN TEST\")\n print(\"=========================\")\n for a in list(AtomData.ke_test.keys()):\n atom = Atom(a)\n\n d0, d1, g0, g1, t0, t1, l0, l1 = atom.get_densities(r)\n\n il0 = np.dot(grid, l0)\n il1 = np.dot(grid, l1)\n print(\"{:>3} - L_0 = {:+.6e}, L_1 = {:+.6e}, {:}\".format(a, il0, il1, \"PASSED\" if max(abs(il0), abs(il1)) < 1e-6 else \"FAILED - \"))\n\n\n print(\"\\nFINITE DIFFERENCE GRADIENT TEST\")\n print(\"===============================\")\n print(\"Testing gradient evaluation function against finite difference estimate...\")\n ne = Atom(\"Ne\") # Let's use \"the guvnor\"\n # We only need to test a few points around the core\n fdh = 1e-8\n fdr = np.arange(0.9, 0.9+fdh*10, fdh)\n d0, d1, g0, g1, t0, t1, l0, l1 = ne.get_densities(fdr)\n\n # First the first central difference\n fdiff = (d0[2:]-d0[:-2])/(2*fdh) # Construct the central difference\n if np.allclose(fdiff, g0[1:-1], atol=1e-1): # finite difference is not perfect, so lenient tollerance\n print(\"Gradient: PASSED\")\n else:\n print(\"Gradient: FAILED -\")\n\n print(\"\\nELEMENT COLOR FUNCTIONS TEST\")\n print(\"===========================\")\n test_obj = [Atom(\"H\"), Atom(\"C\"), Atom(\"O\")]\n test_str = [\"H\", \"C\", \"O\"]\n ref = np.array([[1., 1., 1.], [0.565, 0.565, 0.565], [1. , 0.051, 0.051]])\n\n if np.allclose( np.array(get_colors_for_elements(test_obj)), ref):\n print(\"\\nColor from objects: PASSED\")\n else:\n print(\"\\nColor from objects: FAILED -\")\n\n if np.allclose( np.array(get_colors_for_elements(test_str)), ref):\n print(\"Color from strings: PASSED\")\n else:\n print(\"Color from strings: FAILED -\")\n\n if HAVE_LIBXC:\n test_functional='GGA_X_PBE'\n print(\"\\nATOMIC EXCHANGE ENERGIES WITH {}\".format(test_functional))\n print(\"============================================\")\n for a in list(data.ke_test.keys()):\n atom = Atom(a)\n nE, vrho, vsigma, vtau, vlapl = atom.libxc_eval(r, functional=test_functional, restricted=False)\n Exc = (np.dot(nE, grid)).item()\n print('{:3s} {:.10f}'.format(a, Exc))\n else:\n print(\"\\nNot doing energy calculations due to lack of libxc.\\n\")", "def deviation(delta, mean_reliability, experiment, disks, chunk_count, spread_factor, threshold_recovery):\n \n # Approximated file loss probability\n reliability_mean_value = probability_at_least_d_fail_equal_reliability(threshold_recovery, chunk_count, mean_reliability)\n \n\n # Exact probability\n reliabilities = [element for element in \n file_loss_delta_matrix(delta, mean_reliability, experiment, disks, chunk_count, spread_factor, \n threshold_recovery)]\n \n return abs(mean(reliabilities) - reliability_mean_value)/abs(mean(reliabilities))", "def Get_params(numparams, dt, D):\n # bounds from table 1 Kowalek et al 2020\n Nmin, Nmax = 30, 600\n Bmin, Bmax = 1, 6\n Rmin, Rmax = 1, 17\n alphamin, alphamax = 0.3, 0.7\n Qmin, Qmax = 1, 9\n\n # Gen parameters\n Q = np.random.uniform(Qmin, Qmax, size=numparams)\n Q1, Q2 = Q, Q\n\n NsND = np.random.randint(Nmin, Nmax + 1, size=numparams)\n NsAD = np.random.randint(Nmin, Nmax + 1, size=numparams)\n NsCD = np.random.randint(Nmin, Nmax + 1, size=numparams)\n NsDM = np.random.randint(Nmin, Nmax + 1, size=numparams)\n TDM = NsDM * dt\n\n B = np.random.uniform(Bmin, Bmax, size=numparams)\n r_c = np.sqrt(D * NsCD * dt / B) # solving for r_c in eq. 8 Kowalek\n\n R = np.random.uniform(Rmin, Rmax, size=numparams)\n v = np.sqrt(R * 4 * D / TDM) # solving for v in eq. 7 Kowalek\n\n alpha = np.random.uniform(alphamin, alphamax, size=numparams)\n\n # Compute sigma for ND, AD, CD from eq. 12 Kowalek\n sigmaND = np.sqrt(D * dt) / Q1\n sigmaAD = np.sqrt(D * dt) / Q1\n sigmaCD = np.sqrt(D * dt) / Q1\n\n # Compute sigma for DM from eq. 12 Kowalek\n sigmaDM = np.sqrt(D * dt + v ** 2 * dt ** 2) / Q2\n\n return np.array(\n [\n NsND,\n NsAD,\n NsCD,\n NsDM,\n D * np.ones(numparams),\n dt * np.ones(numparams),\n r_c,\n v,\n alpha,\n sigmaND,\n sigmaAD,\n sigmaCD,\n sigmaDM,\n ]\n ).T", "def conditionalDistribution(self, d, m, w):\r\n probabilities_ts = np.ones((self.numTopics, self.numSentiments))\r\n\r\n # firstfactor 수정\r\n firstFactor = (self.n_wkl[w, :, :] + self.beta) / \\\r\n (self.n_kl + self.n_wkl.shape[0] * self.beta) # dim(K x L)\r\n\r\n secondFactor = (self.ns_dk[d, :] + self.alpha) / \\\r\n (self.ns_d[d] + self.numTopics * self.alpha) # dim(K x 1)\r\n\r\n thirdFactor = (self.ns_dkl[d, :, :] + self.gamma) / \\\r\n (self.ns_dk[d] + self.numSentiments * self.gamma)[:, np.newaxis] # dim (K x L)\r\n\r\n probabilities_ts *= firstFactor * thirdFactor\r\n probabilities_ts *= secondFactor[:, np.newaxis]\r\n probabilities_ts /= np.sum(probabilities_ts)\r\n return probabilities_ts", "def eval_error_metric(predt, dtrain: xgb.DMatrix):\n label = dtrain.get_label()\n r = np.zeros(predt.shape)\n gt = predt > 0.5\n if predt.size == 0:\n return \"CustomErr\", 0\n r[gt] = 1 - label[gt]\n le = predt <= 0.5\n r[le] = label[le]\n return 'CustomErr', np.sum(r)", "def fairness_discrepancy(props, n_classes, norm=0):\n # unique, freq = np.unique(data, return_counts=True)\n # props = freq / len(data) #Proportion of data that belongs to that data\n \n # #------------------Modification to correct the zero support problem------------------------------------------------\n # temp=np.zeros(n_classes)\n # temp[unique]=props\n # props=temp\n # #------------------------------------------------------------------------------\n \n # print (freq)\n truth = 1./n_classes\n\n\n # L2 and L1=================================================================================================\n #(Remove Normalisation)\n l2_fair_d = np.sqrt(((props - truth)**2).sum())\n l1_fair_d = abs(props - truth).sum()\n\n # q = props, p = truth\n # kl_fair_d = (props * (np.log(props) - np.log(truth))).sum()\n\n #Cross entropy\n p=np.ones(n_classes) \n # ce=cross_entropy(p,props,n_classes)-cross_entropy(p,p,n_classes)\n \n #information specificity=====================================================================================\n rank=np.linspace(1,n_classes-1,n_classes-1)\n rank[::-1].sort() #Descending order\n perc=np.array([i/np.sum(rank) for i in rank])\n \n \n props[::-1].sort()\n alpha=props[1:]\n specificity=abs(props[0]-np.sum(alpha*perc))\n info_spec=(l1_fair_d+specificity)/2\n \n #Wasstertein Distance\n wd=wasserstein_distance(props,np.ones(len(props))*truth)\n \n #Wassertein Specificity\n wds=(wd+specificity)/2\n if norm==0:\n return l2_fair_d, l1_fair_d,info_spec,specificity,wd,wds\n # return l2_fair_d, l1_fair_d,info_spec,specificity\n else:\n return l2_fair_d/metric_max(n_classes,\"L2\"), l1_fair_d/metric_max(n_classes,\"L1\"),info_spec/metric_max(n_classes,\"Is\"),specificity,wd/metric_max(n_classes,\"Wd\")\n # return l2_fair_d/metric_max(n_classes,\"l2\"), l1_fair_d/metric_max(n_classes,\"l1\"),info_spec/metric_max(n_classes,\"is\"),specificity" ]
[ "0.7060361", "0.6983528", "0.6222328", "0.60808724", "0.60013914", "0.5823593", "0.5813156", "0.5641228", "0.55846107", "0.5578027", "0.5569787", "0.5560261", "0.5547611", "0.54837257", "0.54624325", "0.5458767", "0.5449614", "0.5449614", "0.5401801", "0.5400344", "0.5358333", "0.5328224", "0.53274393", "0.53152525", "0.5310864", "0.5285005", "0.5279291", "0.52772397", "0.52608734", "0.52573586" ]
0.76656
0
Compute the file loss probability for disks reliabilities between mean_reliability 0.5 delta and mean_reliability + 0.5 delta for a number of experiment.
def file_loss_delta(delta, mean_reliability, experiments, disks, chunk_count, spread_factor, d): for e in experiments: # First we generate the list of disk reliability between mean_reliability-0.5*delta and mean_reliability-0.5*delta. lower_bound = mean_reliability - 0.5 * delta upper_bound = mean_reliability + 0.5 * delta reliability = dict(zip(disks, uniform(low=lower_bound, high=upper_bound, size=len(disks)))) reliability[disks[-1]] = len(disks) * mean_reliability - sum([reliability[disk] for disk in disks[:-1]]) # Then we calculate the probability of file loss for the reliability list yield probability_file_loss(disks, chunk_count, spread_factor, d, reliability)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def deviation(delta, mean_reliability, experiment, disks, chunk_count, spread_factor, threshold_recovery):\n \n # Approximated file loss probability\n reliability_mean_value = probability_at_least_d_fail_equal_reliability(threshold_recovery, chunk_count, mean_reliability)\n \n\n # Exact probability\n reliabilities = [element for element in \n file_loss_delta_matrix(delta, mean_reliability, experiment, disks, chunk_count, spread_factor, \n threshold_recovery)]\n \n return abs(mean(reliabilities) - reliability_mean_value)/abs(mean(reliabilities))", "def file_loss_delta_matrix(delta, mean_reliability, experiments, disks, chunk_count, spread_factor, d):\n \n for e in experiments:\n # First we generate the list of disk reliability between mean_reliability-0.5*delta and mean_reliability-0.5*delta.\n\n lower_bound = mean_reliability - 0.5 * delta\n upper_bound = mean_reliability + 0.5 * delta\n\n reliability = dict(zip(disks, uniform(low=lower_bound, high=upper_bound , size=len(disks))))\n reliability[disks[-1]] = len(disks) * mean_reliability - sum([reliability[disk] for disk in disks[:-1]])\n \n # Then we calculate the probability of file loss for the reliability list \n yield probability_file_loss_matrix(disks, chunk_count, spread_factor, d, reliability)", "def std_vs_delta(delta, mean_reliability, experiment, disks, chunk_count, spread_factor, threshold_recovery):\n\n # Exact probability\n reliabilities = [element for element in \n file_loss_delta_matrix(delta, mean_reliability, experiment, disks, chunk_count, spread_factor, \n threshold_recovery)]\n\n return std(reliabilities)", "def probability_file_loss(disks, chunk_count, spread_factor, d, disk_reliability):\n # First we calculate the probability that a configuration is selected.\n probability_configuration = (1.0*(factorial(spread_factor - chunk_count + 1)*factorial(chunk_count - 1))\n / (len(disks)*factorial(spread_factor)))\n \n # Then, we generate the list of all feasible configurations as a function of \n # the number of disks, disk_count, the number of chunks, chunk_count and the spread factor.\n #configurations = list(map(lambda t: map(lambda e: e + 1, t),\n # feasible_configurations(disk_count, chunk_count, spread_factor)))\n \n configurations = feasible_configurations(len(disks), chunk_count, spread_factor)\n\n # Finally, for each feasible configuration where chunks are stored, we calculate the probabi-\n # lity the file is lost.\n \n # first we consider there is no redondancy\n if len(disks) >= 2*(spread_factor + 1) - chunk_count:\n return probability_configuration * sum([probability_at_least_d_fail(config, d, chunk_count, disk_reliability)\n for config in configurations])\n # This condition cover the case with redondancies\n else:\n return probability_configuration * sum([frequency(config, len(disks), spread_factor)*probability_at_least_d_fail(config, d, chunk_count, disk_reliability)\n for config in configurations])", "def launch_experiment(disks, chunk_count, threshold_recovery, spread_factor, experiment, delta, mean_reliability):\n\n # Approximated file loss probability\n reliability_mean_value = probability_at_least_d_fail_equal_reliability(threshold_recovery, chunk_count, mean_reliability)\n print(\"----------------------------------------------------------------------\")\n print(\" Approximated file loss probability \")\n print(reliability_mean_value)\n print(\"----------------------------------------------------------------------\")\n \n # Exact reliability dataframe\n print(\"----------------------------------------------------------------------\")\n print(\" Exact file loss probability \")\n reliabilities = DataFrame(file_loss_delta_matrix(delta, mean_reliability, experiment, disks, chunk_count, spread_factor, \n threshold_recovery)\n , columns=['Reliability'])\n \n # Histogram of reliabilities\n reliabilities.hist(bins=50)\n \n # Mean value and standard deviation of the dataframe reliabilities\n print \"Mean value of reliabilities : \",reliabilities.mean()\n print(\"\")\n print \"Standard deviation of reliabilities : \",reliabilities.std()\n\n # relative error\n relative_error_list = (reliabilities - reliability_mean_value) / reliabilities\n\n # relative error plot\n relative_error_list.plot(title='Relative errors plot')\n \n # relative error histogram\n relative_error_list.hist(bins=50)\n print(\"----------------------------------------------------------------------\")", "def probability_at_least_d_fail(disks, d, chunk_count, reliability):\n #print(disks, d, chunk_count, reliability)\n \n return sum([disk_loss_probability(disks, reliability, k) for k in range(d, chunk_count + 1)])\n # return sum([disk_loss_probability(k) for k in range(recovery_threshold, chunk_count + 1)])", "def loss_probability(reliability, k, chunk_count):\n return (factorial(chunk_count)/(factorial(chunk_count-k)*factorial(k))\n * pow(1 - reliability,k)*pow(reliability,chunk_count-k))", "def compute_loss(self, sample):\n observations_batch, actions_batch, return_batch, masks_batch, \\\n old_action_log_probs_batch, adv_targ = sample\n\n assert old_action_log_probs_batch.shape == (self.mini_batch_size, 1)\n assert adv_targ.shape == (self.mini_batch_size, 1)\n assert return_batch.shape == (self.mini_batch_size, 1)\n\n values, action_log_probs, dist_entropy = self.evaluate_actions(\n observations_batch, actions_batch)\n\n assert values.shape == (self.mini_batch_size, 1)\n assert action_log_probs.shape == (self.mini_batch_size, 1)\n assert values.requires_grad\n assert action_log_probs.requires_grad\n assert dist_entropy.requires_grad\n\n # [TODO] Implement policy loss\n ratio = torch.exp(action_log_probs - old_action_log_probs_batch)\n surr1 = ratio * adv_targ\n surr2 = torch.clamp(ratio, 1.0 - self.clip_param, 1.0 + self.clip_param) * adv_targ\n policy_loss = -torch.min(surr1, surr2).mean()\n\n # [TODO] Implement value loss\n value_loss = F.mse_loss(return_batch, values)\n\n # This is the total loss\n loss = policy_loss + self.config.value_loss_weight * value_loss - self.config.entropy_loss_weight * dist_entropy\n\n return loss, policy_loss, value_loss, dist_entropy", "def probability_file_loss_matrix(disks, chunk_count, spread_factor, d, reliability):\n \n # First we calculate the probability that a configuration is selected.\n probability_configuration = (1.0*factorial(spread_factor - chunk_count + 1) * factorial(chunk_count - 1) /\n (len(disks) * factorial(spread_factor)))\n \n # Then, we generate the list of all feasible configurations as a function of \n # the number of disks, disk_count, the number of chunks, chunk_count and the spread factor.\n configurations = feasible_configurations(len(disks), chunk_count, spread_factor)\n \n # Finally, for each feasible configuration where chunks are stored, we calculate the probabi-\n # lity the file is lost.\n \n # first we consider there is no redundancy\n if len(disks) >= 2*(spread_factor + 1) - chunk_count:\n return probability_configuration * sum([probability_at_least_d_fail_matrix(config, d, chunk_count, reliability)\n for config in configurations])\n # This condition cover the case with redundancies\n else:\n return probability_configuration * sum([frequency(config, len(disks), spread_factor) *\n probability_at_least_d_fail_matrix(config, d, chunk_count, reliability)\n for config in configurations])", "def calc_loss_rates(self, trial_name):\n base_path = self.base_path\n tx_path = '%s%s%s/*.p' % (base_path, 'tx/', trial_name)\n rx_path = '%s%s%s/*.p' % (base_path, 'rx/', trial_name)\n print('tx_path: ' + str(tx_path))\n print('rx_path: ' + str(rx_path))\n tx_files = glob.glob(tx_path)\n rx_files = glob.glob(rx_path)\n tx_dict = self._mk_tx_dict(tx_files)\n rx_dict = self._mk_rx_dict(rx_files)\n print('tx_dict: ' + str(tx_dict))\n print('rx_dict: ' + str(rx_dict))\n loss_dict = self._mk_loss_dict(tx_dict, rx_dict)\n \n return loss_dict", "def compute_loss(self, obs, returns):", "def policy_loss(sal_box_prob, oracle_action, sample_weights):\n loss = tf.nn.softmax_cross_entropy_with_logits(logits=sal_box_prob, labels=oracle_action)\n \n return tf.reduce_mean(loss) * (1.0 - sample_weights / 10.0)", "def compute_loss(self):\n self.prototypes = self.compute_prototypes()\n self.test_logits = self.compute_logits()\n loss = tf.nn.sparse_softmax_cross_entropy_with_logits(\n labels=self.episode.test_labels, logits=self.test_logits)\n cross_entropy_loss = tf.reduce_mean(loss)\n regularization = tf.reduce_sum(\n tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES))\n loss = cross_entropy_loss + self.weight_decay * regularization\n return loss", "def probability_at_least_d_fail_equal_reliability(d, chunk_count, reliability):\n \n return sum([loss_probability(reliability, k, chunk_count) for k in range(d, chunk_count + 1)])", "def envisaged_loss(self):\n loss = round(\n self.calcul_buy_nb_action() * self.stop_loss - self.investment_price(),\n 2,\n )\n percent_loss = round(loss * 100 / self.capital, 2)\n return loss, percent_loss", "def loss_fn(gr_truth, pred):\n return 100 * dice_loss(pred, gr_truth) + softmax_weighted_loss(pred, gr_truth)", "def profit_loss(self) -> float:\n return self.net_worth / self.initial_net_worth", "def calculate_reliability(data):\n\n\tsuccess_ratio = data['success'].sum() * 1.0 / len(data)\n\tprint \"Reliability: {}\".format(success_ratio)", "def get_loss(fidelity):\n\n return 1 - np.sqrt(fidelity)", "def _compute_loss(self):\n state, action, reward, next_state, done = self.replay_buffer.sample(self.batch_size)\n\n state = torch.FloatTensor(state)\n next_state = torch.FloatTensor(next_state)\n action = torch.LongTensor(action)\n reward = torch.FloatTensor(reward)\n done = torch.FloatTensor(done)\n\n q_values = self.dqn(state)\n q_value = q_values.gather(1, action.unsqueeze(1)).squeeze(1)\n\n next_q_values = self.target_dqn(next_state)\n next_q_value = next_q_values.max(1)[0]\n target = reward + self.discount_factor * next_q_value * (1 - done)\n\n # loss = F.smooth_l1_loss(q_value, target.detach())\n loss = F.mse_loss(q_value, target.detach())\n\n return loss", "def compute_em_probabilities(self, predictions, data, epsilon=1e-6):\n\t\tloss = data * predictions + (1 - data) * (1 - predictions)\n\n\t\t# sum loss over channels\n\t\tloss = torch.sum(loss, 4, keepdim=True)\n\n\t\tif epsilon > 0:\n\t\t\tloss += epsilon\n\t\treturn loss", "def get_probability_loss(self):\n return sum(self._loss)/len(self._loss)", "def _wil_compute(errors: Tensor, target_total: Tensor, preds_total: Tensor) ->Tensor:\n return 1 - errors / target_total * (errors / preds_total)", "def calculate_actor_loss(self, state_batch):\n action, (action_probabilities, log_action_probabilities), _ = self.produce_action_and_action_info(state_batch)\n qf1_pi = self.critic_local(state_batch)\n qf2_pi = self.critic_local_2(state_batch)\n min_qf_pi = torch.min(qf1_pi, qf2_pi)\n inside_term = self.alpha * log_action_probabilities - min_qf_pi\n policy_loss = (action_probabilities * inside_term).sum(dim=1).mean()\n log_action_probabilities = torch.sum(log_action_probabilities * action_probabilities, dim=1)\n return policy_loss, log_action_probabilities", "def penalty(self):\n assert len(self.weights) == len(self.means), \"Dimensions!\"\n out = np.exp(self.data['riskfree'] * self.data['maturity'])\n for weight, mean in zip(self.weights, self.means):\n out -= weight * np.exp(mean * self.data['maturity'])\n return (out**2).mean()**.5", "def _compute_losses(discriminator, d_real, d_fake, interpolated_x, interpolated_c):\n wasserstein_distance = tf.reduce_mean(d_real) - tf.reduce_mean(d_fake)\n\n gradient_penalty_x = wgan.compute_gradient_penalty(\n lambda interpolated: discriminator(interpolated, interpolated_c),\n interpolated_x\n )\n \n gradient_penalty_c = wgan.compute_gradient_penalty(\n lambda interpolated: discriminator(interpolated_x, interpolated),\n interpolated_c\n )\n\n g_loss = tf.reduce_mean(d_fake)\n d_loss = wasserstein_distance + (\n wgan.GRADIENT_PENALTY_LAMBDA * gradient_penalty_x +\n wgan.GRADIENT_PENALTY_LAMBDA * gradient_penalty_c\n )\n\n return g_loss, d_loss", "def compute_loss(\n action_probs: tf.Tensor, values: tf.Tensor, returns: tf.Tensor\n) -> tf.Tensor:\n\n advantage = returns - values\n td = tf.subtract(returns, values)\n\n # actor\n # action_log_probs = tf.math.log(action_probs)\n # actor_loss = -tf.math.reduce_sum(action_log_probs * advantage)\n action_log_probs = tf.math.log(action_probs)\n actor_loss = -tf.math.reduce_mean(action_log_probs * td)\n\n # critic\n # td = tf.subtract(returns, values)\n # critic_loss = tf.reduce_mean(tf.square(td))\n critic_loss = huber_loss(values, returns)\n\n tf.print(\"a_loss:\", actor_loss, \"c_loss:\", critic_loss)\n\n return actor_loss + critic_loss", "def compute_loss(self):", "def compute_loss(x, mask, regime, model, weights, biases, extra_params, intervention,\n intervention_type, intervention_knowledge, mean_std=False):\n # TODO: add param\n if intervention and intervention_type == \"perfect\" and intervention_knowledge ==\"known\":\n log_likelihood = model.compute_log_likelihood(x, weights, biases, extra_params)\n log_likelihood = torch.sum(log_likelihood * mask, dim=0) / mask.size(0)\n else:\n log_likelihood = model.compute_log_likelihood(x, weights, biases,\n extra_params, mask=mask,\n regime=regime)\n log_likelihood = torch.sum(log_likelihood, dim=0) / mask.size(0)\n loss = - torch.mean(log_likelihood)\n\n if not mean_std:\n return loss\n else:\n joint_log_likelihood = torch.mean(log_likelihood * mask, dim=1)\n return loss, torch.sqrt(torch.var(joint_log_likelihood) / joint_log_likelihood.size(0))", "def mse_loss(angles_gt, angles_gen):\n loss = (angles_gt - angles_gen)**2\n # loss = torch.sum(loss, dim=-1) # sum loss over dimensions\n loss = torch.mean(loss, dim=-1) # mean loss over images per task\n loss = torch.mean(loss, dim=-1) # mean loss over tasks\n return loss" ]
[ "0.7375282", "0.7129215", "0.690092", "0.6808733", "0.62738377", "0.62597007", "0.6112193", "0.60928214", "0.60235775", "0.58532465", "0.58407056", "0.5836605", "0.58347225", "0.58009577", "0.5767279", "0.57511526", "0.5729234", "0.57234436", "0.5690353", "0.5650997", "0.5623327", "0.56117064", "0.5576571", "0.55661947", "0.5555026", "0.55538213", "0.55495334", "0.55383974", "0.5521154", "0.5508382" ]
0.7915163
0
Compute the file loss probability for disks reliabilities between mean_reliability 0.5 delta and mean_reliability + 0.5 delta for a number of experiment using the matrix formulation.
def file_loss_delta_matrix(delta, mean_reliability, experiments, disks, chunk_count, spread_factor, d): for e in experiments: # First we generate the list of disk reliability between mean_reliability-0.5*delta and mean_reliability-0.5*delta. lower_bound = mean_reliability - 0.5 * delta upper_bound = mean_reliability + 0.5 * delta reliability = dict(zip(disks, uniform(low=lower_bound, high=upper_bound , size=len(disks)))) reliability[disks[-1]] = len(disks) * mean_reliability - sum([reliability[disk] for disk in disks[:-1]]) # Then we calculate the probability of file loss for the reliability list yield probability_file_loss_matrix(disks, chunk_count, spread_factor, d, reliability)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def file_loss_delta(delta, mean_reliability, experiments, disks, chunk_count, spread_factor, d):\n \n for e in experiments:\n # First we generate the list of disk reliability between mean_reliability-0.5*delta and mean_reliability-0.5*delta.\n \n lower_bound = mean_reliability - 0.5 * delta\n upper_bound = mean_reliability + 0.5 * delta\n\n reliability = dict(zip(disks, uniform(low=lower_bound, high=upper_bound, size=len(disks))))\n reliability[disks[-1]] = len(disks) * mean_reliability - sum([reliability[disk] for disk in disks[:-1]])\n \n # Then we calculate the probability of file loss for the reliability list \n yield probability_file_loss(disks, chunk_count, spread_factor, d, reliability)", "def deviation(delta, mean_reliability, experiment, disks, chunk_count, spread_factor, threshold_recovery):\n \n # Approximated file loss probability\n reliability_mean_value = probability_at_least_d_fail_equal_reliability(threshold_recovery, chunk_count, mean_reliability)\n \n\n # Exact probability\n reliabilities = [element for element in \n file_loss_delta_matrix(delta, mean_reliability, experiment, disks, chunk_count, spread_factor, \n threshold_recovery)]\n \n return abs(mean(reliabilities) - reliability_mean_value)/abs(mean(reliabilities))", "def probability_file_loss_matrix(disks, chunk_count, spread_factor, d, reliability):\n \n # First we calculate the probability that a configuration is selected.\n probability_configuration = (1.0*factorial(spread_factor - chunk_count + 1) * factorial(chunk_count - 1) /\n (len(disks) * factorial(spread_factor)))\n \n # Then, we generate the list of all feasible configurations as a function of \n # the number of disks, disk_count, the number of chunks, chunk_count and the spread factor.\n configurations = feasible_configurations(len(disks), chunk_count, spread_factor)\n \n # Finally, for each feasible configuration where chunks are stored, we calculate the probabi-\n # lity the file is lost.\n \n # first we consider there is no redundancy\n if len(disks) >= 2*(spread_factor + 1) - chunk_count:\n return probability_configuration * sum([probability_at_least_d_fail_matrix(config, d, chunk_count, reliability)\n for config in configurations])\n # This condition cover the case with redundancies\n else:\n return probability_configuration * sum([frequency(config, len(disks), spread_factor) *\n probability_at_least_d_fail_matrix(config, d, chunk_count, reliability)\n for config in configurations])", "def std_vs_delta(delta, mean_reliability, experiment, disks, chunk_count, spread_factor, threshold_recovery):\n\n # Exact probability\n reliabilities = [element for element in \n file_loss_delta_matrix(delta, mean_reliability, experiment, disks, chunk_count, spread_factor, \n threshold_recovery)]\n\n return std(reliabilities)", "def launch_experiment(disks, chunk_count, threshold_recovery, spread_factor, experiment, delta, mean_reliability):\n\n # Approximated file loss probability\n reliability_mean_value = probability_at_least_d_fail_equal_reliability(threshold_recovery, chunk_count, mean_reliability)\n print(\"----------------------------------------------------------------------\")\n print(\" Approximated file loss probability \")\n print(reliability_mean_value)\n print(\"----------------------------------------------------------------------\")\n \n # Exact reliability dataframe\n print(\"----------------------------------------------------------------------\")\n print(\" Exact file loss probability \")\n reliabilities = DataFrame(file_loss_delta_matrix(delta, mean_reliability, experiment, disks, chunk_count, spread_factor, \n threshold_recovery)\n , columns=['Reliability'])\n \n # Histogram of reliabilities\n reliabilities.hist(bins=50)\n \n # Mean value and standard deviation of the dataframe reliabilities\n print \"Mean value of reliabilities : \",reliabilities.mean()\n print(\"\")\n print \"Standard deviation of reliabilities : \",reliabilities.std()\n\n # relative error\n relative_error_list = (reliabilities - reliability_mean_value) / reliabilities\n\n # relative error plot\n relative_error_list.plot(title='Relative errors plot')\n \n # relative error histogram\n relative_error_list.hist(bins=50)\n print(\"----------------------------------------------------------------------\")", "def probability_file_loss(disks, chunk_count, spread_factor, d, disk_reliability):\n # First we calculate the probability that a configuration is selected.\n probability_configuration = (1.0*(factorial(spread_factor - chunk_count + 1)*factorial(chunk_count - 1))\n / (len(disks)*factorial(spread_factor)))\n \n # Then, we generate the list of all feasible configurations as a function of \n # the number of disks, disk_count, the number of chunks, chunk_count and the spread factor.\n #configurations = list(map(lambda t: map(lambda e: e + 1, t),\n # feasible_configurations(disk_count, chunk_count, spread_factor)))\n \n configurations = feasible_configurations(len(disks), chunk_count, spread_factor)\n\n # Finally, for each feasible configuration where chunks are stored, we calculate the probabi-\n # lity the file is lost.\n \n # first we consider there is no redondancy\n if len(disks) >= 2*(spread_factor + 1) - chunk_count:\n return probability_configuration * sum([probability_at_least_d_fail(config, d, chunk_count, disk_reliability)\n for config in configurations])\n # This condition cover the case with redondancies\n else:\n return probability_configuration * sum([frequency(config, len(disks), spread_factor)*probability_at_least_d_fail(config, d, chunk_count, disk_reliability)\n for config in configurations])", "def meta_amortized_loss(network, model_indices, params, sim_data):\n\n out_inference, out_evidence = network(model_indices, params, sim_data)\n if out_inference is not None:\n z, log_det_J = out_inference\n kl_loss = tf.reduce_mean(0.5 * tf.square(tf.norm(z, axis=-1)) - log_det_J)\n else:\n kl_loss = 0\n \n if out_evidence is not None:\n model_probs = out_evidence\n model_probs = tf.clip_by_value(model_probs, 1e-15, 1 - 1e-15)\n log_loss = -tf.reduce_mean(tf.reduce_sum(model_indices * tf.math.log(model_probs), axis=1))\n else:\n log_loss = 0\n return kl_loss + log_loss", "def compute_loss(self, sample):\n observations_batch, actions_batch, return_batch, masks_batch, \\\n old_action_log_probs_batch, adv_targ = sample\n\n assert old_action_log_probs_batch.shape == (self.mini_batch_size, 1)\n assert adv_targ.shape == (self.mini_batch_size, 1)\n assert return_batch.shape == (self.mini_batch_size, 1)\n\n values, action_log_probs, dist_entropy = self.evaluate_actions(\n observations_batch, actions_batch)\n\n assert values.shape == (self.mini_batch_size, 1)\n assert action_log_probs.shape == (self.mini_batch_size, 1)\n assert values.requires_grad\n assert action_log_probs.requires_grad\n assert dist_entropy.requires_grad\n\n # [TODO] Implement policy loss\n ratio = torch.exp(action_log_probs - old_action_log_probs_batch)\n surr1 = ratio * adv_targ\n surr2 = torch.clamp(ratio, 1.0 - self.clip_param, 1.0 + self.clip_param) * adv_targ\n policy_loss = -torch.min(surr1, surr2).mean()\n\n # [TODO] Implement value loss\n value_loss = F.mse_loss(return_batch, values)\n\n # This is the total loss\n loss = policy_loss + self.config.value_loss_weight * value_loss - self.config.entropy_loss_weight * dist_entropy\n\n return loss, policy_loss, value_loss, dist_entropy", "def compute_loss(self, vision_description, rotation_matrix_gt):\n probs = self.predict_probability(\n vision_description, rotation_matrix_gt, training=True)\n loss = -tf.reduce_mean(tf.math.log(probs))\n return loss", "def compute_loss(self, obs, returns):", "def compute_reprojection_loss(self, preds, targets, lambda_ssim=0.85):\n losses = []\n for pred, target in zip(preds, targets):\n abs_diff = torch.abs(target - pred)\n # l1_loss = abs_diff.mean()#(1, True)\n # ssim_loss = self.ssim(pred, target).mean()#(1, True)\n # reprojection_loss = 0.85 * ssim_loss + 0.15 * l1_loss\n\n l1_loss = (1-lambda_ssim) * abs_diff.mean()\n ssim_loss = (lambda_ssim * self.ssim(pred, target).mean()) if lambda_ssim > 0 else 0\n reprojection_loss = ssim_loss + l1_loss\n\n losses.append(reprojection_loss)\n\n return sum(losses)", "def loss_fn(self, recons, inputs, mu, log_var, **kwargs):\n# kld_weight = kwargs['M_N'] # Account for the minibatch samples from the dataset\n recons_loss = F.mse_loss(recons, inputs)\n# recons_loss = F.binary_cross_entropy(recons, inputs)\n KLD = torch.mean(-0.5 * torch.sum(1 + log_var - mu**2 - log_var.exp(), dim=1), dim=0)\n loss = recons_loss - KLD\n return loss, recons_loss, KLD", "def _auxiliary_loss(self, expert_mask, router_prob):\n # density_1's shape: (dp_group, self.expert_dim)\n density_1 = self.reduce_mean(expert_mask, 1)\n # density_1_proxy's shape: (dp_group, self.expert_dim)\n density_1_proxy = self.reduce_mean2(router_prob, 1)\n loss = self.mul(density_1, density_1_proxy)\n loss = self.reduce_mean3(loss)\n loss = self.mul3(self.mul2(loss, self.expert_dim), self.expert_dim)\n return loss", "def _compute_loss(self):\n state, action, reward, next_state, done = self.replay_buffer.sample(self.batch_size)\n\n state = torch.FloatTensor(state)\n next_state = torch.FloatTensor(next_state)\n action = torch.LongTensor(action)\n reward = torch.FloatTensor(reward)\n done = torch.FloatTensor(done)\n\n q_values = self.dqn(state)\n q_value = q_values.gather(1, action.unsqueeze(1)).squeeze(1)\n\n next_q_values = self.target_dqn(next_state)\n next_q_value = next_q_values.max(1)[0]\n target = reward + self.discount_factor * next_q_value * (1 - done)\n\n # loss = F.smooth_l1_loss(q_value, target.detach())\n loss = F.mse_loss(q_value, target.detach())\n\n return loss", "def compare_error_bounds( model_fname, log_fname, delta = 0.1 ):\n gmm = GaussianMixtureModel.from_file( model_fname )\n k, d, M, w = gmm.k, gmm.d, gmm.means, gmm.weights\n\n P, T = exact_moments( M, w )\n\n lg = sc.load( log_fname )\n\n # TODO: Use concentration bounds on aerr_P12\n n_M, sk_M = lg[\"norm_M_2\"], lg[\"s_k_M\"], \n e_P, e_T = lg[\"aerr_P_2\"], lg[\"aerr_T\"], \n n_P, sk_P, n_T = lg[\"norm_Pe_2\"], lg[\"s_k_P\"], lg[\"norm_Te\"]\n w_min = min(w)\n\n # TODO: Ah, not computing sigma2! \n\n # alpha_P and \\beta_P\n a_P = e_P/sk_P\n b_P = a_P/(1-a_P)\n\n e_Wb = 2/sqrt(sk_P) * b_P\n e_W = lg[\"aerr_W_2\"]\n\n e_Twb = 1/sqrt(sk_M * (1-a_P)) * e_T + n_T/sk_M * (1 + 1/sqrt(1-a_P) + 1/(1-a_P)) * e_W\n e_Tw = lg[\"aerr_Tw\"]\n\n e_Lb = e_Tw\n e_L = lg[\"aerr_lambda\"]\n\n D_M = column_sep( M )\n D_Tw = delta/(sqrt(sc.e) * k**2 * (1+sqrt(2 * log(k/delta)))) * D_M\n e_vb = 4 * sqrt(2) * e_Tw / D_Tw\n e_v = lg[\"aerr_v_col\"]\n\n e_Wtb = 2 * sqrt( n_P + e_P ) * b_P\n n_Wtb = sqrt( n_P + e_P )\n\n e_mub = e_Lb + (1+1/sqrt(w_min)) * n_Wtb * e_vb + e_Wtb\n e_mu = lg[\"aerr_M_col\"]\n\n print \"A\\t\\tbound\\t\\tactual\"\n print \"W\\t\\t%f\\t\\t%f\" % (e_Wb, e_W)\n print \"Tw\\t\\t%f\\t\\t%f\" % (e_Twb, e_Tw)\n print \"L\\t\\t%f\\t\\t%f\" % (e_Lb, e_L)\n print \"v\\t\\t%f\\t\\t%f\" % (e_vb, e_v)\n print \"mu\\t\\t%f\\t\\t%f\" % (e_mub, e_mu)\n return [(e_W/e_Wb), (e_Tw/e_Twb), (e_L / e_Lb), (e_v/e_vb), (e_mu / e_mub),]", "def _wil_compute(errors: Tensor, target_total: Tensor, preds_total: Tensor) ->Tensor:\n return 1 - errors / target_total * (errors / preds_total)", "def compute_loss(self):\n def calc_loss(inputs, outputs):\n reconstruction_loss = tf.metrics.binary_crossentropy(\n tf_flat(inputs), tf_flat(outputs))\n reconstruction_loss *= OUT_SIZE * OUT_SIZE\n kl_loss = -0.5 * tf.reduce_sum(1.0 + self.log_sigma - tf.square(\n self.mu) - tf.exp(self.log_sigma), 1)\n return tf.reduce_mean(reconstruction_loss + kl_loss)\n return calc_loss", "def penalty(self):\n assert len(self.weights) == len(self.means), \"Dimensions!\"\n out = np.exp(self.data['riskfree'] * self.data['maturity'])\n for weight, mean in zip(self.weights, self.means):\n out -= weight * np.exp(mean * self.data['maturity'])\n return (out**2).mean()**.5", "def compute_em_probabilities(self, predictions, data, epsilon=1e-6):\n\t\tloss = data * predictions + (1 - data) * (1 - predictions)\n\n\t\t# sum loss over channels\n\t\tloss = torch.sum(loss, 4, keepdim=True)\n\n\t\tif epsilon > 0:\n\t\t\tloss += epsilon\n\t\treturn loss", "def mse_loss(angles_gt, angles_gen):\n loss = (angles_gt - angles_gen)**2\n # loss = torch.sum(loss, dim=-1) # sum loss over dimensions\n loss = torch.mean(loss, dim=-1) # mean loss over images per task\n loss = torch.mean(loss, dim=-1) # mean loss over tasks\n return loss", "def compute_loss(self):", "def policy_loss(sal_box_prob, oracle_action, sample_weights):\n loss = tf.nn.softmax_cross_entropy_with_logits(logits=sal_box_prob, labels=oracle_action)\n \n return tf.reduce_mean(loss) * (1.0 - sample_weights / 10.0)", "def probability_at_least_d_fail_matrix(disks, d, chunk_count, reliability):\n failure_threshold = chunk_count - d + 1\n \n transfer_matrices = [transfer_matrix(reliability[disk], failure_threshold)\n for disk in reversed(disks)]\n \n return np.sum(reduce(np.dot, transfer_matrices), axis=1)[0]", "def get_error(deltas, sums, weights):\n \n print(deltas)\n print(sums)\n print(weights)\n print('===================================')\n \n # here goes your code\n A = weights.T.dot(deltas.T)\n print(A)\n B = sigmoid_prime(sums)\n print(B)\n \n print(A.shape)\n print(B.shape)\n C = A.T * B\n print(C)\n D = C.mean(axis=0)\n print(D)\n print(D.shape)\n \n return ((weights.T.dot(deltas.T)).T * sigmoid_prime(sums)).mean(axis=0)", "def probability_at_least_d_fail(disks, d, chunk_count, reliability):\n #print(disks, d, chunk_count, reliability)\n \n return sum([disk_loss_probability(disks, reliability, k) for k in range(d, chunk_count + 1)])\n # return sum([disk_loss_probability(k) for k in range(recovery_threshold, chunk_count + 1)])", "def error_function(prediction_dict, use_example_flags):\n\n predicted_flux_matrix_w_m02 = numpy.mean(\n prediction_dict[prediction_io.SCALAR_PREDICTIONS_KEY][\n use_example_flags, ...\n ],\n axis=-1\n )\n actual_flux_matrix_w_m02 = prediction_dict[\n prediction_io.SCALAR_TARGETS_KEY\n ][use_example_flags, :]\n\n predicted_net_flux_matrix_w_m02 = (\n predicted_flux_matrix_w_m02[:, 0] -\n predicted_flux_matrix_w_m02[:, 1]\n )\n actual_net_flux_matrix_w_m02 = (\n actual_flux_matrix_w_m02[:, 0] -\n actual_flux_matrix_w_m02[:, 1]\n )\n\n net_flux_sse_w2_m04 = numpy.sum(\n (predicted_net_flux_matrix_w_m02 - actual_net_flux_matrix_w_m02)\n ** 2\n )\n raw_flux_sse_w2_m04 = numpy.sum(\n (predicted_flux_matrix_w_m02 - actual_flux_matrix_w_m02) ** 2\n )\n\n num_examples = actual_flux_matrix_w_m02.shape[0]\n flux_mse_w_m02 = (\n (net_flux_sse_w2_m04 + raw_flux_sse_w2_m04) / (3 * num_examples)\n )\n\n predicted_hr_matrix_k_day01 = numpy.mean(\n prediction_dict[prediction_io.VECTOR_PREDICTIONS_KEY][\n use_example_flags, ...\n ],\n axis=-1\n )\n actual_hr_matrix_k_day01 = prediction_dict[\n prediction_io.VECTOR_TARGETS_KEY\n ][use_example_flags, ...]\n\n weight_matrix_k_day01 = numpy.maximum(\n numpy.absolute(predicted_hr_matrix_k_day01),\n numpy.absolute(actual_hr_matrix_k_day01)\n )\n heating_rate_dwmse_k3_day03 = numpy.mean(\n weight_matrix_k_day01 *\n (predicted_hr_matrix_k_day01 - actual_hr_matrix_k_day01) ** 2\n )\n\n return (\n scaling_factor_for_dwmse * heating_rate_dwmse_k3_day03 +\n scaling_factor_for_flux_mse * flux_mse_w_m02\n )", "def _compute_model_prob(self, per_list_logodds):\n with tf.compat.v1.name_scope(name='compute_model_prob'):\n return tf.stop_gradient(\n tf.exp(-self._alpha *\n (per_list_logodds -\n tf.reduce_min(per_list_logodds, axis=2, keepdims=True))))", "def compute_loss(self):\n self.prototypes = self.compute_prototypes()\n self.test_logits = self.compute_logits()\n loss = tf.nn.sparse_softmax_cross_entropy_with_logits(\n labels=self.episode.test_labels, logits=self.test_logits)\n cross_entropy_loss = tf.reduce_mean(loss)\n regularization = tf.reduce_sum(\n tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES))\n loss = cross_entropy_loss + self.weight_decay * regularization\n return loss", "def calculate_actor_loss(self, state_batch):\n action, (action_probabilities, log_action_probabilities), _ = self.produce_action_and_action_info(state_batch)\n qf1_pi = self.critic_local(state_batch)\n qf2_pi = self.critic_local_2(state_batch)\n min_qf_pi = torch.min(qf1_pi, qf2_pi)\n inside_term = self.alpha * log_action_probabilities - min_qf_pi\n policy_loss = (action_probabilities * inside_term).sum(dim=1).mean()\n log_action_probabilities = torch.sum(log_action_probabilities * action_probabilities, dim=1)\n return policy_loss, log_action_probabilities", "def calculate_reliability(data):\n\n\tsuccess_ratio = data['success'].sum() * 1.0 / len(data)\n\tprint \"Reliability: {}\".format(success_ratio)" ]
[ "0.72597986", "0.6986704", "0.657611", "0.6478273", "0.6222642", "0.6062159", "0.6027956", "0.5801296", "0.5749402", "0.5615564", "0.55568445", "0.5553681", "0.554003", "0.5538803", "0.5510115", "0.5508222", "0.5498864", "0.5498256", "0.5492621", "0.54915667", "0.5489747", "0.5455052", "0.54536426", "0.5430469", "0.54289484", "0.5428434", "0.54098225", "0.5394874", "0.5387449", "0.53769433" ]
0.77288026
0
Compute the deviation between the mean reliability and is approximate value for a special delta.
def deviation(delta, mean_reliability, experiment, disks, chunk_count, spread_factor, threshold_recovery): # Approximated file loss probability reliability_mean_value = probability_at_least_d_fail_equal_reliability(threshold_recovery, chunk_count, mean_reliability) # Exact probability reliabilities = [element for element in file_loss_delta_matrix(delta, mean_reliability, experiment, disks, chunk_count, spread_factor, threshold_recovery)] return abs(mean(reliabilities) - reliability_mean_value)/abs(mean(reliabilities))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def mean_deviation(self):\r\n\t\t_mean = sum(self.sample)/len(self.sample)\r\n\t\treturn sum(map(lambda x: abs(x - _mean), self.sample))/len(self.sample)", "def deviation(values, val):\n\tm = mean(values)\n\tdev = abs(val-m)\n\tsd = standard_deviation(values)\n\treturn float(dev)/sd if sd!=0 else 0.0", "def std_vs_delta(delta, mean_reliability, experiment, disks, chunk_count, spread_factor, threshold_recovery):\n\n # Exact probability\n reliabilities = [element for element in \n file_loss_delta_matrix(delta, mean_reliability, experiment, disks, chunk_count, spread_factor, \n threshold_recovery)]\n\n return std(reliabilities)", "def standard_deviation(self):\r\n\t\treturn self.variance()**(1/2)", "def deviation(xs):\n\ta = avg(xs)\n\treturn sqrt(sum([(x - a) ** 2 for x in xs]) / (len(xs) - 1))", "def deviationAvg(xs):\n\treturn deviation(xs) / sqrt(len(xs))", "def standard_deviation(xs: List[float]) -> float:\n return math.sqrt(variance(xs))", "def standard_deviation(xs: List[float]) -> float:\n return math.sqrt(variance(xs))", "def sd(vals):", "def gmean_diff(self) -> float:\n sim_log = np.log1p(self.predicted)\n obs_log = np.log1p(self.true)\n return float(np.exp(gmean(sim_log) - gmean(obs_log)))", "def std_mean(self):\n std = self.std\n if self.ddof != 0:\n # ddof correction, (need copy of std)\n std = std * np.sqrt(\n (self.sum_weights - self.ddof) / self.sum_weights\n )\n\n return std / np.sqrt(self.sum_weights - 1)", "def stddev_approx(self, name='stddev_approx'):\n with self._name_and_control_scope(name):\n return tf.math.sqrt(self.variance_approx())", "def stdev(values):\n mean = avg(values)\n diffs = [(value - mean) ** 2 for value in values]\n return avg(diffs) ** 0.5", "def relative_change_stdev(mean1, mean2, std1, std2):\n mean1, mean2 = float(mean1), float(mean2)\n quotient = mean2 / mean1\n first = std1 / mean1\n second = std2 / mean2\n std = quotient * math.sqrt(first * first + second * second)\n return (quotient - 1) * 100, std * 100", "def calc_standard_deviation(data: list) -> float:\n mean = calc_mean(data)\n acc = 0.0\n for n in data:\n acc += (n - mean) ** 2\n acc /= len(data) - 1\n return math.sqrt(acc)", "def em_std(self) -> float:\n if self.__total_pulls == 0:\n raise Exception('Number of pulls is 0. No empirical standard deviation.')\n return math.sqrt(\n (self.__sum_of_square_reward -\n self.__total_rewards**2 / self.__total_pulls) / self.__total_pulls)", "def avg_std_dev(positions):\n # print(\"len pos = \", len(positions))\n # print(positions)\n if sum(positions) == 0:\n the_mean = 0\n standard_dev = 0\n return the_mean, standard_dev \n try:\n the_mean = sum(positions) / float(len(positions))\n standard_dev = numpy.std(positions)\n except ValueError:\n the_mean = 0\n standard_dev = 0\n return the_mean, standard_dev", "def demeaned(self):\n return self.data - self.mean", "def DifferenceInMeans(weights, means, sigmas, average_delta = True):\n Q = len(means)\n delta = 0\n # Sort on frequency\n means.sort()\n\n # Multiply absolute difference in frequ\n\n for i in range(Q):\n delta += (np.abs((means[0,i])-(means[1,i]))\n + np.abs((weights[0,i])-(weights[1,i]))\n + np.abs((sigmas[0,i])-(sigmas[1,i])))\n #print('delta: ',delta, ' Q: ', Q)\n if average_delta:\n delta = delta/Q\n return delta", "def standard_dev(self):\n return self.variance()**0.5", "def precision_loss(data): #singular value\n start = np.std(data.head(round(len(data)/8)))\n end = np.std(data.tail(round(len(data)/8)))\n change = end/start\n return change", "def calculate_std(self) -> float:\n\n if self.data:\n return np.std(self.data)\n else:\n return self.sigma", "def meanMedianStd(self, diff_arr):\n\n mad_lst = [] # median absolute deviation\n mean = np.mean(diff_arr) # mean (average) of the set\n std_mean = np.std(diff_arr) # standard deviation from the mean\n median = np.median(diff_arr) # mdian of the set\n\n consis_const = 1.4826 # consistency constant for a normal distribution\n\n for point in diff_arr:\n mad_lst.append(abs(point - median))\n std_med = consis_const * np.median(mad_lst) # median absolute deviation*cosis_cons = standard deviation from the median of a set\n med_threshhold = (median - 2 * std_med, median + 2 * std_med)\n mean_threshhold = (mean - 2 * std_mean, mean + 2 * std_mean) # 95.4 confidence interval\n\n return mean_threshhold, med_threshhold", "def test_stdev_from_mean(self):\r\n x = [2.1, 4.2, 5.9, 8.4, 9.6]\r\n result = stdev_from_mean(x)\r\n self.assertFloatEqual(\r\n result,\r\n [-1.292463399014413,\r\n -0.60358696806764478,\r\n -0.045925095396451399,\r\n 0.77416589382589174,\r\n 1.1678095686526162])", "def calculate_std_deviation(value_arr):\n avg_balanced_acc = 0\n for value in value_arr:\n avg_balanced_acc += value\n avg_balanced_acc /= len(value_arr)\n\n balanced_accuracy_std_deviation = 0\n for value in value_arr:\n balanced_accuracy_std_deviation += pow(abs(value - avg_balanced_acc), 2)\n balanced_accuracy_std_deviation /= len(value_arr)\n return math.sqrt(balanced_accuracy_std_deviation)", "def rmdspe(self) -> float:\n return float(np.sqrt(np.median(np.square(self._percentage_error()))) * 100.0)", "def mdape(self) -> float:\n return float(np.median(np.abs(self._percentage_error())) * 100)", "def em_mean(self) -> float:\n if self.__total_pulls == 0:\n raise Exception('Number of pulls is 0. No empirical mean.')\n return self.__total_rewards / self.__total_pulls", "def _compute_delay_std(delays, min_spike_count):\n\n spike_count = delays.groupby('gid')['delay_in_window'].count()\n\n mask = spike_count >= min_spike_count\n\n stds = delays.groupby('gid')['delay_in_window'].std()\n\n return pd.Series(stds[mask]).rename('delstd')", "def gmae(self) -> float:\n return _geometric_mean(np.abs(self._error()))" ]
[ "0.7300405", "0.6970873", "0.6958749", "0.67380327", "0.6708342", "0.66694385", "0.665761", "0.665761", "0.6576224", "0.65494007", "0.65315175", "0.6526695", "0.6510533", "0.64498675", "0.6411879", "0.63829255", "0.63778174", "0.6377376", "0.6377318", "0.63548166", "0.6348803", "0.63474506", "0.6338283", "0.6324535", "0.6319504", "0.6313789", "0.62941694", "0.6261544", "0.6260782", "0.6257685" ]
0.7622046
0
Compute the standard for a special delta.
def std_vs_delta(delta, mean_reliability, experiment, disks, chunk_count, spread_factor, threshold_recovery): # Exact probability reliabilities = [element for element in file_loss_delta_matrix(delta, mean_reliability, experiment, disks, chunk_count, spread_factor, threshold_recovery)] return std(reliabilities)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _standardize(self):\n deviation = np.std(self.series)\n self.series = (self.series - np.mean(self.series)) / (deviation if deviation != 0 else 1)", "def _std_trans(self, std_pre):\r\n std = 1e-6 + P.Log()(P.Exp()(std_pre) + 1)\r\n return std", "def standard_deviation(self):\r\n\t\treturn self.variance()**(1/2)", "def __init__(self, initial_std=0.1, delta=0.1):\n self.initial_std = initial_std\n self.delta = delta\n # Initialize the current standard deviation\n self.cur_std = initial_std", "def unnormalize_deltas(deltas, mean, std):\n return deltas * std + mean", "def calculate_std(self) -> float:\n\n if self.data:\n return np.std(self.data)\n else:\n return self.sigma", "def standardize(ps,center=\"mean\"):\n if center == \"mean\":\n return (ps - ps.mean()) / ps.std()\n if center == \"median\":\n return (ps - ps.median()[0]) / ps.std()\n else:\n print \"unknown central point\"\n return ps", "def std(self):\n\t\treturn np.sqrt(0.6) #obtained by integrating 1.5x^4 from -1 to 1", "def em_std(self) -> float:\n if self.__total_pulls == 0:\n raise Exception('Number of pulls is 0. No empirical standard deviation.')\n return math.sqrt(\n (self.__sum_of_square_reward -\n self.__total_rewards**2 / self.__total_pulls) / self.__total_pulls)", "def precision_loss(data): #singular value\n start = np.std(data.head(round(len(data)/8)))\n end = np.std(data.tail(round(len(data)/8)))\n change = end/start\n return change", "def _std(self):\n\n\t\t#print opt.hess_inv.todense()\n\t\td = 1E-7\n\t\ttheta = self.theta\n\n\t\tTheta = np.copy(theta)\n\t\tTheta[0] = Theta[0] + d\n\t\taa1 = self.objfxn(tuple(Theta))\n\t\tTheta = np.copy(theta)\n\t\tTheta[0] = Theta[0] - d\n\t\taa2 = self.objfxn(tuple(Theta))\n\t\taa3 = self.objfxn(tuple(theta))\n\n\t\tself.stda = 1/np.sqrt((aa1 - 2*aa3 + aa2)/d**2)\n\n\t\tTheta = np.copy(theta)\n\t\tTheta[1] = Theta[1] + d\n\t\tbb1 = self.objfxn(tuple(Theta))\n\t\tTheta = np.copy(theta)\n\t\tTheta[1] = Theta[1] - d\n\t\tbb2 = self.objfxn(tuple(Theta))\n\t\tbb3 = self.objfxn(tuple(theta))\n\n\t\tself.stdb = 1/np.sqrt((bb1 - 2*bb3 + bb2)/d**2)\n\n\t\td = 1E-9\n\t\tTheta = np.copy(theta)\n\t\tTheta[2] = Theta[2] + d\n\t\tcc1 = self.objfxn(tuple(Theta))\n\t\tTheta = np.copy(theta)\n\t\tTheta[2] = Theta[2] - d\n\t\tcc2 = self.objfxn(tuple(Theta))\n\t\tcc3 = self.objfxn(tuple(theta))\n\n\t\tself.stdc = 1/np.sqrt((cc1 - 2*cc3 + cc2)/d**2)\n\n\t\treturn self", "def std(self):\n return self.std", "def standardize(self, inputData):\n\n return (inputData - self.mean) / self.std", "def SeriesStandard(series):\n mean = np.mean(series)\n variance = np.var(series)\n series = (series-mean)/variance\n return series", "def _get_std(self):\n return (0.229, 0.224, 0.225)", "def unstandardize(da: xr.DataArray, mean: xr.DataArray, std: xr.DataArray):\n return (std * da) + mean", "def standardize(data):\r\n mean = data.mean(axis=0)\r\n std = data.std(axis=0)\r\n return (data - mean)/std", "def std(self):\n return np.sqrt(self.alpha) / self.beta", "def epsilon_delta(self):", "def standardize(x, mean=None, std=None): \n \n mean = mean if mean is not None else x.mean(axis=0)\n std = std if std is not None else x.std(axis=0) \n \n return (x - mean) / std, mean, std", "def standard_deviation(self):\n clean, total = self._prepare_for_stats()\n if not total:\n return None\n\n return math.sqrt(clean.variance())", "def F_std_coeff(d):\n return (d ** 2 - 1) / 4", "def std(self) -> float:\n return self._data.std()", "def _calculate_std(self, lc):\n if self.std is None:\n std = np.mean(lc)**0.5\n elif isinstance(self.std, collections.Iterable):\n std = np.mean(self.std) # Iterable of numbers\n else: # Single float number\n std = self.std\n\n return std", "def calculate_std(self, _moves, s, att):\n # std = 0\n # for move in _moves:\n # std += move.__dict__[att].__dict__[s] ** 2\n # std -= self.mean_instance.__dict__[att].__dict__[s] ** 2\n # std /= len(_moves)\n # std = np.sqrt(std)\n move_array = []\n for move in _moves:\n move_array.append(move.__dict__[att].__dict__[s])\n move_array = np.array(move_array)\n std = move_array.std(axis=0)\n return std", "def standardize(data):\n stddev = data.std()\n #if stddev == 0.:\n # sys.exit(\"data.std() == 0. !\")\n if stddev != 0.:\n data = (data - data.mean()) / (data.std())\n\n return data", "def get_std(self):\n return self.serie.std()", "def _get_scaled_diff(self, prev_sigma, sigma):\n return np.linalg.norm(sigma - prev_sigma) / np.linalg.norm(sigma)", "def relative_change_stdev(mean1, mean2, std1, std2):\n mean1, mean2 = float(mean1), float(mean2)\n quotient = mean2 / mean1\n first = std1 / mean1\n second = std2 / mean2\n std = quotient * math.sqrt(first * first + second * second)\n return (quotient - 1) * 100, std * 100", "def _get_standard_deviation(intermediate_normalization_dict):\n\n num_values = float(intermediate_normalization_dict[NUM_VALUES_KEY])\n multiplier = num_values / (num_values - 1)\n\n return numpy.sqrt(multiplier * (\n intermediate_normalization_dict[MEAN_OF_SQUARES_KEY] -\n intermediate_normalization_dict[MEAN_VALUE_KEY] ** 2\n ))" ]
[ "0.6608726", "0.651359", "0.62992597", "0.6275137", "0.62542665", "0.6189788", "0.610386", "0.60896164", "0.6051591", "0.6049969", "0.60461015", "0.60223275", "0.5992256", "0.5965548", "0.5949857", "0.5942657", "0.58918095", "0.58868074", "0.58791757", "0.5878977", "0.5851065", "0.5842594", "0.58384526", "0.58293396", "0.5828765", "0.58262086", "0.58156645", "0.57828444", "0.57668597", "0.5764654" ]
0.66994005
0
Attach to a screen running the component. Returns True on success, False otherwise.
def attachToComponent(self, opts): screen = self.findScreen(opts.verbose) if screen == None: print("Did not find screen named %s for attach" % self._screenName) return False else: print("Found screen %s" % screen) execCmd("%s -x %s" % (self._screenPath, screen)) return True
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def startComponent(self, opts):\n screen = self.findScreen(opts.verbose)\n\n if screen != None:\n print(\"Screen session %s already started.\" % (screen), file=sys.stderr)\n return False\n\n chdir(self._binaryPath, opts.verbose)\n\n cmd = \"%s %s.exe %s\" % (self._monoPath, self._componentName, self._switches)\n\n if opts.autorestart:\n cmd = \"bash -c 'set carryon=true; trap \\\"carryon=false\\\" SIGUSR1; while $carryon; do %s; done'\" % (cmd)\n\n execCmd(\"%s -S %s -d -m %s\" % (self._screenPath, self._screenName, cmd), opts.verbose)\n\n screen = self.findScreen(opts.verbose)\n if screen != None:\n print(\"%s starting in screen instance %s\" % (self._componentName, screen))\n else:\n print(\"ERROR: %s did not start.\" % self._componentName, file=sys.stderr)\n return False\n\n if opts.attach:\n execCmd(\"%s -x %s\" % (self._screenPath, self._screenName))\n\n return True", "def on_screen(self) -> bool:\n\n return (\n self.env_var_helper.set_name(\"PYFUNCEBLE_DEBUG_ON_SCREEN\").exists()\n or self.env_var_helper.set_name(\"DEBUG_PYFUNCEBLE_ON_SCREEN\").exists()\n )", "def attach(self):\r\n sshpass = \"sshpass -p \\\"akanksha1\\\"\"\r\n remote_Station = \"[email protected]\"\r\n base = \"ssh -t \" + options[\"username\"] + \"@\" + options[\"server\"]\r\n\r\n screen = \" screen -r \"\r\n if self.device_type == \"Wireless_access_point\":\r\n screen += \"WAP_%d\" % self.getID()\r\n elif self.device_type == \"yRouter\":\r\n yrouter = \"yrouter --interactive=1 --config=/root/script_t1_y1.conf test3\"\r\n screen_yrouter = \"%s ssh %s \\\"source /root/.profile; %s\\\"\"%(sshpass, remote_Station, yrouter)\r\n else:\r\n name = self.getName()\r\n pid = mainWidgets[\"tm\"].getPID(name)\r\n if not pid:\r\n return\r\n screen += pid + \".\" + name\r\n\r\n command = \"\"\r\n\r\n window_name = str(self.getProperty(\"Name\")) # the strcast is necessary for cloning\r\n if(self.getName() != window_name):\r\n window_name += \" (\" + self.getName() + \")\"\r\n if environ[\"os\"] == \"Windows\":\r\n\r\n startpath = environ[\"tmp\"] + self.getName() + \".start\"\r\n try:\r\n outfile = open(startpath, \"w\")\r\n outfile.write(screen)\r\n outfile.close()\r\n except:\r\n mainWidgets[\"log\"].append(\"Failed to write to start file!\")\r\n return\r\n\r\n command += \"putty -\"\r\n if options[\"session\"]:\r\n command += \"load \" + options[\"session\"] + \" -l \" + options[\"username\"] + \" -t\"\r\n else:\r\n command += base\r\n command += \" -m \\\"\" + startpath + \"\\\"\"\r\n else:\r\n if self.device_type == \"yRouter\":\r\n command += \"rxvt -T \\\"\" + window_name + \"\\\" -e \" + screen_yrouter\r\n else:\r\n command += \"rxvt -T \\\"\" + window_name + \"\\\" -e \" + base + screen\r\n\r\n self.shell = subprocess.Popen(str(command), shell=True)", "def aml_run_attach():\n AmlRunWrapper().setup(attach=True)", "def screen_attach(self, sname):\n self._channel.sendall(\"screen -r %s\\n\" % (sname))\n rdata = '\\n'.join(self._channel.recv(65536).splitlines())\n return rdata", "def attach(self):\n args = {\n 'detach': True,\n 'tty': True,\n }\n if self._args.command:\n args['command'] = self._args.command\n\n try:\n try:\n ident = self.client.images.pull(self._args.image)\n img = self.client.images.get(ident)\n except podman.ImageNotFound as e:\n sys.stdout.flush()\n print(\n 'Image {} not found.'.format(e.name),\n file=sys.stderr,\n flush=True)\n return 1\n\n ctnr = img.create(**args)\n ctnr.attach(eot=4)\n\n try:\n ctnr.start()\n print()\n except (BrokenPipeError, KeyboardInterrupt):\n print('\\nContainer disconnected.')\n except podman.ErrorOccurred as e:\n sys.stdout.flush()\n print(\n '{}'.format(e.reason).capitalize(),\n file=sys.stderr,\n flush=True)\n return 1", "def test_landing_screen(self):\n # Checking current Screen(Login screen)\n self.assert_wait_no_except('//ScreenManager[@current]', timeout=15, value='login')\n # Dragging from sent to PROS: to NOTE:\n self.drag(\n '''//Login//Screen//ContentHead[1][@section_name=\\\"PROS:\\\"]''',\n '''//Login//Screen//ContentHead[0][@section_name=\\\"NOTE:\\\"]'''\n )\n # Assert the checkbox is rendered\n self.assertExists(\n '//Login//Screen[@name=\\\"check_screen\\\"]//AnchorLayout[1]/Check[@active=false]', timeout=5\n )\n # Clicking on the checkbox\n self.cli.wait_click(\n '//Login//Screen[@name=\\\"check_screen\\\"]//AnchorLayout[1]/Check', timeout=5\n )\n # Checking Status of checkbox after click\n self.assertExists(\n '//Login//Screen[@name=\\\"check_screen\\\"]//AnchorLayout[1]/Check[@active=true]', timeout=5\n )\n # Checking the Proceed Next button is rendered or not\n self.assertExists(\n '''//Login//Screen[@name=\\\"check_screen\\\"]'''\n '''//MDFillRoundFlatIconButton[@text=\\\"Proceed Next\\\"]''', timeout=5\n )\n # Clicking on Proceed Next Button to redirect to \"random\" screen\n self.cli.wait_click(\n '''//Login//Screen[@name=\\\"check_screen\\\"]'''\n '''//MDFillRoundFlatIconButton[@text=\\\"Proceed Next\\\"]''', timeout=5\n )\n self.assertExists(\"//ScreenManager[@current=\\\"random\\\"]\", timeout=5)", "def test_change_screen(self):\n self.sm.add_widget(Screen(name='screen1'))\n self.sm.current = 'screen1'\n self.assertEqual(self.sm.current, 'login')\n self.assertTrue(isinstance(self.sm.current_screen, LoginScreen))", "def attach(self, _place):\n\n\t\tself.kill()\n\t\tif not _place or not _place.putItem(self):\n\t\t\treturn False\n\n\t\tself.rect.center = (-1000, -1000) # trzeba go wyrzucić poza obszar rysowania(żeby nie wisiał w dziwnym miejscu póki się ekran nie odświeży)\n\t\tself._attached = _place\n\t\tself._detached = False\n\t\treturn True", "def do_attach(cs, args):\n response = cs.containers.attach(args.container)\n websocketclient.do_attach(cs, response, args.container, \"~\", 0.5)", "def teleport(self, screen):\n if screen in self.screens:\n self._sendCommand('TELEPORT ' + screen)\n else:\n print 'No such screen: %s' % screen", "def present(self):\n if self.isWindow :\n self.present(self)\n else :\n assert hasattr(self, 'window'), \\\n \"ManagedWindow: self.window does not exist!\"\n self.window.present()", "def attach_box(self, timeout=4):\n\n group = 'ur5_1_planning_group'\n touch_links = self.robot.get_link_names(group=group)\n\n # Attach box to EE\n self.scene.attach_box(self.ee_link,\n self.box_name,\n touch_links=touch_links)\n\n # Wait for update and return status\n return self.wait_for_state_update(box_is_attached=True,\n box_is_known=False,\n timeout=timeout)", "def activate(self):\n # Send command\n self._glir.command('FRAMEBUFFER', self._id, True)\n # Associate canvas now\n canvas = get_current_canvas()\n if canvas is not None:\n canvas.context.glir.associate(self.glir)", "def tap_screen(self, element=None, config=None, x_cord=None, y_cord=None):\n if element and config:\n self.touch.tap(x=config[element]['x'],\n y=config[element]['y']).perform()\n elif x_cord:\n self.touch.tap(x=x_cord, y=y_cord).perform()\n else:\n LOGGER.error('Either element or co-ordinates must be given for tap!')\n time.sleep(2)", "def addScreenToRender(self, screenToImport, screenName):\n self.screenDictionary.update({screenName:len(self.screens)})\n self.screens.append(screenToImport)", "def screens_maker(task):\n rend_type = int( task['render_type'] )\n rend_project = task['project_name']\n rend_result_dir = task['result_dir']\n file_name = p_rend_type[rend_type]['file_screen'].split( '/' )[1]\n logging.info( 'IN SCREEN Maker {}'.format( task ) )\n try:\n bpy.ops.wm.open_mainfile( filepath=rend_project )\n scn = bpy.context.scene\n scn.frame_start = 100\n scn.frame_end = 101\n bpy.data.scenes[scn.name].render.image_settings.file_format = 'JPEG'\n scn.render.filepath = '{}'.format( str( rend_result_dir ) + '/' + str( file_name ) )\n bpy.ops.render.render( write_still=True )\n try:\n os.chown( scn.render.filepath, int( u_ugid ), int( u_gguid ) )\n os.chmod( scn.render.filepath, 0o777 )\n except Exception as e:\n logging.info( 'err SCREEN MAKER rights{}'.format( str( e ) ) )\n except Exception as e:\n logging.info( 'ERR IN SCREEN Maker {}'.format( str( e ) ) )\n\n return 1", "def __liveActually(self, stdscr):\n global screenH, screenW\n self.__stdscr = stdscr\n (screenH, screenW) = self.__stdscr.getmaxyx()\n self.__stdscr.addstr(0, 0, \"Custom Burner \" + common.version)\n self.__stdscr.addstr(screenH - 1, 0, \"a: add ISO q: Quit\")\n self.__stdscr.noutrefresh()\n isoWindowHeight = ((screenH - 2) * 2)/ 3\n self.__isoWindow = IsoWindow(isoWindowHeight, screenW, 1, 0)\n self.__isoWindow.timeout(1000) # msec\n self.__logWindow = LogWindow(screenH - 2 - isoWindowHeight, screenW,\n isoWindowHeight + 1, 0)\n self.__focus = 0\n self.__focusedWindow = self.__isoWindow\n self.__isoWindow.focus()\n quitting = False\n while not quitting:\n self.__updateLog()\n curses.panel.update_panels()\n curses.doupdate()\n c = self.__focusedWindow.getch()\n if c == curses.ascii.TAB:\n self.__switchFocus()\n elif c == ord('a'):\n self.__askForIso()\n elif c == ord('q'):\n quitting = True", "def update_screen(ai_settings, screen, ship):", "def expert_screen(self):\n executable = 'motor-expert-screen'\n #hutch_location = '~' + blutil.guessBeamline() + 'opr/bin/'\n hutch_location = '/reg/g/xpp/scripts/'\n arg = self.pvname\n if os.path.exists(hutch_location + executable):\n os.system(hutch_location + executable + ' ' + arg)\n else:\n os.system(executable + ' ' + arg)", "def getComponentStatus(self, opts):\n\n # We'll check screen even if we found PID so that we can get screen information\n screen = self.findScreen(opts.verbose)\n\n if screen == None:\n print(\"Did not find screen named %s\" % self._screenName)\n else:\n print(\"Found screen %s\" % screen)\n\n if opts.verbose:\n print(\"OpenSimulator path: %s\" % self._binaryPath)\n\n if screen != None:\n print(\"Status: ### Active ###\")\n return True\n else:\n print(\"Status: ### Inactive ###\")\n return False", "def add_broadcast_component(component_name):\n try:\n click_on(component_name)\n wait()\n except Exception as e:\n return \"Error: \" + str(e)\n return \"Success\"", "def render(self, screen):\n pass", "def render(self, screen):\n pass", "def attachable(name, path=None):\n cachekey = f\"lxc.attachable{name}{path}\"\n try:\n return __context__[cachekey]\n except KeyError:\n _ensure_exists(name, path=path)\n # Can't use run() here because it uses attachable() and would\n # endlessly recurse, resulting in a traceback\n log.debug(\"Checking if LXC container %s is attachable\", name)\n cmd = \"lxc-attach\"\n if path:\n cmd += f\" -P {shlex.quote(path)}\"\n cmd += f\" --clear-env -n {name} -- /usr/bin/env\"\n result = (\n __salt__[\"cmd.retcode\"](\n cmd, python_shell=False, output_loglevel=\"quiet\", ignore_retcode=True\n )\n == 0\n )\n __context__[cachekey] = result\n return __context__[cachekey]", "def enter_alternate_screen(self) -> None:\n if not self._in_alternate_screen:\n GENERIC_READ = 0x80000000\n GENERIC_WRITE = 0x40000000\n\n # Create a new console buffer and activate that one.\n handle = HANDLE(\n self._winapi(\n windll.kernel32.CreateConsoleScreenBuffer,\n GENERIC_READ | GENERIC_WRITE,\n DWORD(0),\n None,\n DWORD(1),\n None,\n )\n )\n\n self._winapi(windll.kernel32.SetConsoleActiveScreenBuffer, handle)\n self.hconsole = handle\n self._in_alternate_screen = True", "def attach_volume(self):\n\n # Choose volume\n volume_id = self._choose_among_available_volumes()\n\n # Cancel\n if not volume_id:\n print 'Operation cancelled'\n return\n\n # Choose instance\n instance_id = self._choose_among_running_instances()\n\n # Cancel\n if not instance_id:\n print 'Operation cancelled'\n return\n\n # Attach the volume\n print '# Attaching volume \"%s\"!' % volume_id\n if self.compute.attach_volume(volume_id, instance_id):\n print 'The volume has been attached!'\n else:\n print 'The volume could not been attached'", "def attached(self, value: bool):\n self._properties[\"attached\"] = value", "def draw(self, screen):\n\n if self.exist:\n screen.blit(self._img, self._rect)", "def _do_attach(self, attach_device):\n try:\n if attach_device is not None:\n log.debug(\"Attaching volume '%s' to instance '%s' as device '%s'\" %\n (self.volume_id, self.app.cloud_interface.get_instance_id(),\n attach_device))\n self.volume.attach(\n self.app.cloud_interface.get_instance_id(), attach_device)\n else:\n log.error(\"Attaching volume '%s' to instance '%s' failed because \"\n \"could not determine device.\"\n % (self.volume_id, self.app.cloud_interface.get_instance_id()))\n return False\n except EC2ResponseError, e:\n if e.error_code == 'InvalidVolume.ZoneMismatch':\n msg = (\"Volume '{0}' is located in the wrong availability zone \"\n \"for this instance. You MUST terminate this instance \"\n \"and start a new one in zone '{1}' instead of '{2}' \"\n \"to be able to use this volume.\"\n .format(self.volume_id, self.volume.zone,\n self.app.cloud_interface.get_zone()))\n self.app.msgs.critical(msg)\n log.error(msg)\n self.fs.state = service_states.ERROR\n else:\n log.error(\"Attaching volume '%s' to instance '%s' as device '%s' failed. \"\n \"Exception: %s (%s)\" % (self.volume_id,\n self.app.cloud_interface.get_instance_id(),\n attach_device, e.message,\n e.error_code))\n return False\n return self.status" ]
[ "0.6491276", "0.59752214", "0.59555966", "0.58369565", "0.57265574", "0.5637465", "0.5335948", "0.5300422", "0.5275121", "0.527509", "0.5267567", "0.5206219", "0.52035046", "0.51799893", "0.5155661", "0.51364326", "0.5122207", "0.51052666", "0.5083114", "0.50777763", "0.50653064", "0.5050634", "0.5050254", "0.5050254", "0.50491816", "0.50236744", "0.50200117", "0.5018997", "0.50158745", "0.5010229" ]
0.8210587
0
Get the status of the given component. Returns True if active, False if inactive or problem finding.
def getComponentStatus(self, opts): # We'll check screen even if we found PID so that we can get screen information screen = self.findScreen(opts.verbose) if screen == None: print("Did not find screen named %s" % self._screenName) else: print("Found screen %s" % screen) if opts.verbose: print("OpenSimulator path: %s" % self._binaryPath) if screen != None: print("Status: ### Active ###") return True else: print("Status: ### Inactive ###") return False
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _getCurrentComponentStatus(self):\n resOverall = self.sysAdminClient.getOverallStatus()\n if not resOverall['OK']:\n return resOverall\n currentStatus = {'Down': set(), 'Run': set(), 'All': set()}\n informationDict = resOverall['Value']\n for systemsDict in informationDict.values():\n for system, instancesDict in systemsDict.items():\n for instanceName, instanceInfoDict in instancesDict.items():\n identifier = '%s__%s' % (system, instanceName)\n runitStatus = instanceInfoDict.get('RunitStatus')\n if runitStatus in ('Run', 'Down'):\n currentStatus[runitStatus].add(identifier)\n\n currentStatus['All'] = currentStatus['Run'] | currentStatus['Down']\n return S_OK(currentStatus)", "def check_status(self):\n return self.status", "def check_status(self):\n return self.status", "def getStatus(self):\n return self.enabled", "def getStatus(self):\r\n return self.controller.getStatus()", "def get_service_status(self):\n return self.service.status()", "def isActive(self):\n return self.data.active", "def getStatus(self):\n return self._status", "def getStatus(self):\n return self.__status", "def status(self) -> pulumi.Output['outputs.JobStatus']:\n return pulumi.get(self, \"status\")", "def active(self) -> pulumi.Output[bool]:\n return pulumi.get(self, \"active\")", "def status(self):\n return self.get(self._names[\"status\"])", "def get_status(self):\n # TODO retrieve from db if not set\n return self.status", "def get_status(self):\n return self._status", "def getstatus(self):\n return self.__status", "def get_status(self):\n return self.status", "def get_status(self):\n return self.status", "def get_status(self):\n return self.status", "def active(self):\n resp = self.server.request(\"get\", \"/jobs/%s/%s/state\" % (\n self.sessionid, self.name))\n if resp.body == b'1':\n return True\n return False", "def is_active(self):\n with settings(hide('running', 'stdout', 'stderr', 'warnings'), warn_only=True):\n return self._action('is-active').succeeded", "def test_get_current_component_status_OK(self):\n self._ucr({\n 'repository/online/component/a': 'no',\n 'repository/online/component/b': 'yes',\n 'repository/online/component/c': 'yes',\n 'repository/online/component/d': 'yes',\n })\n ORIG = UU.FN_UPDATER_APTSOURCES_COMPONENT\n try:\n tmp = NamedTemporaryFile()\n print >> tmp, 'deb http://host:port/prefix/0.0/maintained/component/ c/arch/'\n print >> tmp, 'deb http://host:port/prefix/0.0/unmaintained/component/ d/arch/'\n tmp.flush()\n UU.FN_UPDATER_APTSOURCES_COMPONENT = tmp.name\n self.assertEqual(UU.COMPONENT_AVAILABLE, self.u.get_current_component_status('c'))\n self.assertEqual(UU.COMPONENT_AVAILABLE, self.u.get_current_component_status('d'))\n finally:\n UU.FN_UPDATER_APTSOURCES_COMPONENT = ORIG\n tmp.close()", "def status(self):\n return self._query_status()['status']", "def status(self) -> Optional[pulumi.Input[Union[str, 'Status']]]:\n return pulumi.get(self, \"status\")", "def status(self) -> Optional[pulumi.Input[Union[str, 'Status']]]:\n return pulumi.get(self, \"status\")", "def GetStatus(self):\r\n return self.status", "def active(self) -> bool:\n return pulumi.get(self, \"active\")", "def active(self) -> pulumi.Output[Optional[bool]]:\n return pulumi.get(self, \"active\")", "def get_status(self):\n\t\treturn call_sdk_function('PrlJob_GetStatus', self.handle)", "def status(self) -> Optional[int]:\n return pulumi.get(self, \"status\")", "def status(self):\n return self._get(path='status')" ]
[ "0.680515", "0.66162956", "0.66162956", "0.66134614", "0.66031027", "0.65224445", "0.6489517", "0.6467912", "0.64524674", "0.64501303", "0.6445949", "0.6434319", "0.6432779", "0.6428746", "0.6420754", "0.64173096", "0.64173096", "0.64173096", "0.6391066", "0.637212", "0.63609946", "0.63531345", "0.6334581", "0.6334581", "0.63281393", "0.6300892", "0.6290477", "0.62902766", "0.6274717", "0.62727314" ]
0.6943719
0
Start the given component. Returns True on success, False otherwise
def startComponent(self, opts): screen = self.findScreen(opts.verbose) if screen != None: print("Screen session %s already started." % (screen), file=sys.stderr) return False chdir(self._binaryPath, opts.verbose) cmd = "%s %s.exe %s" % (self._monoPath, self._componentName, self._switches) if opts.autorestart: cmd = "bash -c 'set carryon=true; trap \"carryon=false\" SIGUSR1; while $carryon; do %s; done'" % (cmd) execCmd("%s -S %s -d -m %s" % (self._screenPath, self._screenName, cmd), opts.verbose) screen = self.findScreen(opts.verbose) if screen != None: print("%s starting in screen instance %s" % (self._componentName, screen)) else: print("ERROR: %s did not start." % self._componentName, file=sys.stderr) return False if opts.attach: execCmd("%s -x %s" % (self._screenPath, self._screenName)) return True
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def start_behavior(self, behavior_to_start):\n time.sleep(20)\n if not FlexBEHelper.start_flexbe_behavior(behavior_to_start):\n return False\n time.sleep(5)\n return True", "def start(self) -> \"bool\":\n return _beamforming_swig.beamformer_sptr_start(self)", "def _start(self) -> bool:\n CC3DPy.call_start()\n\n self.beginning_step = CompuCellSetup.persistent_globals.restart_manager.get_restart_step()\n\n return True", "def run_component(self):\n raise NotImplementedError", "def _ensureComponentRunning(self, shouldBeRunning):\n for instance in shouldBeRunning:\n self.log.info(\"Starting instance %s\" % instance)\n system, name = instance.split('__')\n if self.controlComponents:\n res = self.sysAdminClient.startComponent(system, name)\n if not res['OK']:\n self.logError(\"Failed to start component:\", \"%s: %s\" % (instance, res['Message']))\n else:\n self.accounting[instance][\"Treatment\"] = \"Instance was down, started instance\"\n else:\n self.accounting[instance][\"Treatment\"] = \"Instance is down, should be started\"", "def start(self):\r\n return self.start_subprocess()", "def start(self):\n return self.setup.start", "def start(self) -> \"bool\":\n return _beamforming_swig.doaesprit_sptr_start(self)", "def test_startService(self):\r\n self.pm.addProcess(\"foo\", [\"foo\"])\r\n # Schedule the process to start\r\n self.pm.startService()\r\n # advance the reactor to start the process\r\n self.reactor.advance(0)\r\n self.assertTrue(\"foo\" in self.pm.protocols)", "def start(self) -> bool:\n\t\tself.retry_counter.reset_counter()\n\t\treturn self.__start()", "def should_start(self):\n raise NotImplementedError()", "def started(self):\n return False", "def do_start(self, str_arg):\n try:\n # self.adbc.startActivity(validateString(str_arg))\n # the above approach failed in unittest complaining device is offline, weird...\n return self.runAdbCmd('shell am start -n', validateString(str_arg))\n except RuntimeError:\n self.resultFlag = False\n if DEBUG:\n traceback.print_exc()", "def start(self):\n self.active = True", "def start(self, unit):\n # Default: act as a dummy.\n return self._start(unit)", "def start(self):\n if self._start_event is None:\n _call_spawn_callbacks(self)\n hub = get_my_hub(self) # pylint:disable=undefined-variable\n self._start_event = hub.loop.run_callback(self.switch)", "def is_started(self):\n raise NotImplementedError", "def do_start(self, args) :\r\n if not self.wait2start:\r\n Thread(target=self.start_loop).start()\r\n self.wait2start = True\r\n else:\r\n self.__Logger.warn(\"Waiting for simulators to be ready. To force start, type \\\"forcestart\\\"\")", "def start(self):\n self.p.start()", "def start(self):\n self.parent.start(auto_terminate=False)\n self.started = True", "def _start(self):\n\n _log.debug(\"Pipeline {} launching run components\".format(self.id))\n self._start_time = time.time()\n for run in self.runs:\n run.start()\n if run.sleep_after:\n time.sleep(run.sleep_after)", "def startup(self):\n started = False\n self.start_driver_ctrl()\n return started", "def startComponent(self):\n\n # create message service instance\n self.ms = MessageService()\n\n # register\n self.ms.registerAs(\"MergeAccountant\")\n\n # subscribe to messages\n self.ms.subscribeTo(\"MergeAccountant:StartDebug\")\n self.ms.subscribeTo(\"MergeAccountant:EndDebug\")\n self.ms.subscribeTo(\"MergeAccountant:Enable\")\n self.ms.subscribeTo(\"MergeAccountant:Disable\")\n self.ms.subscribeTo(\"JobSuccess\")\n self.ms.subscribeTo(\"GeneralJobFailure\")\n self.ms.subscribeTo(\"MergeAccountant:SetJobCleanupFlag\")\n\n # set trigger access for cleanup\n self.trigger = Trigger(self.ms)\n\n # set message service instance for PM interaction\n File.ms = self.ms\n\n # wait for messages\n while True:\n\n\n # get message\n messageType, payload = self.ms.get()\n self.ms.commit()\n # create session object\n Session.set_database(dbConfig)\n Session.connect()\n\n # start transaction\n Session.start_transaction()\n\n # process it\n self.__call__(messageType, payload)\n self.ms.commit()\n\n # commit and close session\n Session.commit_all()\n Session.close_all()", "def start_driver_ctrl(self):\n try:\n args = [\n DRV_CTRL_PROCESS,\n \"-u\",\n self.user,\n \"start\"\n ]\n result = subprocess.run(args, check=True) #pylint: disable=unused-variable\n return True\n except subprocess.CalledProcessError:\n return False", "def start_as_service(self):\n from ..program_manager import ProgramManager\n send_action(ProgramManager.NAME, 'start', self.name)", "def start(self) -> None:\n ...", "def start(self) -> None:\n ...", "def activate(self):\n self.start()", "def start(self):\n cmd = self.doCommand(self.args)\n if cmd is not None:\n cmd.join()\n else:\n self.out = self.error", "def start(self):\n raise NotImplementedError" ]
[ "0.6390702", "0.6302733", "0.6256767", "0.60799384", "0.6042013", "0.6040436", "0.5989707", "0.59866524", "0.5907245", "0.5896782", "0.58284", "0.58061373", "0.5782687", "0.5770688", "0.5761375", "0.5749249", "0.57472557", "0.5734151", "0.57333994", "0.57286006", "0.57187134", "0.569626", "0.5690933", "0.5678431", "0.56740487", "0.5671952", "0.5671952", "0.5670864", "0.56696606", "0.5661485" ]
0.66940063
0
Restart the given component. Returns True on success, False otherwise.
def restartComponent(self, opts): self.stopComponent(opts) return self.startComponent(opts)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def restart(self):\n self.client.post(self.path+'/action', { 'restart': {} })\n return True", "def restart(name):\n ret = \"restart False\"\n if stop(name) and start(name):\n ret = \"restart True\"\n return ret", "def attempt_restart(self):\n self.controller.publish(self, 'restart')", "def restart_container(self, container_node):\n try:\n print(\"Restarting container: \", container_node.get_container_id())\n container = self.docker_client.containers.get(container_node.get_container_id())\n container.restart()\n return True\n except docker.errors.APIError as de:\n print(\"Error restarting the container\")\n traceback.print_exc()\n print de\n return False", "async def module_command_restart(self, ctx, parsed):\n if parsed.invoker != ctx.owner:\n return\n reason = \" \".join(parsed.args[\"msg\"] or []) or \"Restarting\"\n self.quit(reason)\n self._restarting = True", "def Restart(self):\n handler = self.get_command_object(\"Restart\")\n handler()", "def restart(self):\r\n self._update('restart')\r\n\r\n self.supervisord.options.mood = SupervisorStates.RESTARTING\r\n return True", "def restart(self):\n\t\treturn self.reset().start()", "async def do_force_restart(self):\n if self.config[\"allow_restart_requests\"]:\n os._exit(42)\n else:\n return self._rpc_failure(\"Restart disallowed by configuration\")", "def node_restart(ctx):\n ctx.obj['node'].attempt_restart()", "def restart(self, relay):\n if self.stop():\n return self.start(relay)\n return False", "def restart(self, **kwargs):\n return self.client.api.restart(self.id, **kwargs)", "def restart(self):\n\t\treturn Job(SDK.PrlVm_Restart(self.handle)[0])", "def repl_restart(restart: bool = True) -> None:", "def restart(self) -> None:", "def restart(verbose=False, force=False):\n\n _prepare_execution(verbose)\n _validate_components_prepared('restart')\n _validate_force(force, 'restart')\n\n stop(verbose, force)\n start(verbose)\n _print_time()", "def is_restarting(self) -> bool:\r\n return False", "def restart(self):\n global shouldRestart\n shouldRestart = True\n logging.info(\"Restarting bot\")\n self.die()", "def wmRestartService(self):\n user_role = uiCommon.GetSessionUserRole()\n if user_role != \"Administrator\":\n raise Exception(\"Only Administrators can restart services.\")\n\n component = uiCommon.getAjaxArg(\"component\")\n uiCommon.log(\"Service Restart!\", 3)\n os.system(\"$CSK_HOME/cato/services/restart_specific.sh %s\" % (component))\n \n return json.dumps({\"result\": \"success\"})", "def net_service_restart(self):\n\t\treturn Job(SDK.PrlSrv_NetServiceRestart(self.handle)[0])", "def _restart(self):\n pass", "def restart(self):\n pass", "def restart(service):\n # TODO: replace this with your relevant restart logic\n assert service.isalpha()\n run(\"service\", service, \"restart\")", "def restart(*args, **kwargs):\n return restart_type(args, kwargs)", "def restart_port(self, port):\n if port == 0: #tous\n return [p for p in self.ports if not self.ports[p].restart(self)]\n if port in self.ports :\n return self.ports[port].restart(self)\n return False", "def restart(self):\r\n pass", "def restart(self):\n print \"Restarting \" + executable + \" \" + str(argv) \n execl(executable, *([executable]+argv))", "def restart(self):", "def restart():\n stop()\n start()", "def restart(self):\n self.stop()\n self.start(init=False)" ]
[ "0.68808335", "0.6627833", "0.65335727", "0.64911735", "0.64604986", "0.64322287", "0.6412979", "0.6409854", "0.6307403", "0.6287451", "0.6283321", "0.62737554", "0.6273527", "0.62522614", "0.62217695", "0.6185333", "0.6137894", "0.610683", "0.6077489", "0.60514385", "0.60236126", "0.5972971", "0.5971468", "0.5942169", "0.5939324", "0.5931056", "0.59221846", "0.5918805", "0.5911755", "0.5911033" ]
0.7161356
0
Try to find the screen instance for this component. Returns the screen pid.name on success, None otherwise.
def findScreen(self, verbose = False): screenList = "" try: screenList = self.getScreenList(verbose) except subprocess.CalledProcessError as cpe: screenList = cpe.output #print "screenList: %s" % screenList # TODO: Need to improve this for screens with ( in their name res = re.search("\s+(\d+\.%s)\s+\(" % self._screenName, screenList) if not res == None: return res.group(1) else: return None
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def getscreen(self):\n return self.screen", "def getscreen(self):\n return self.screen", "def getScreen(self):\n \n return self.screen", "def getScreen(self, screenName):\n return self.screens[self.screenDictionary[screenName]]", "def getDisplay(self):\n for display in self.listDisplays():\n if self.testDisplay(display):\n if self.verbose:\n print \"Got an existing working display on %s\" % display\n return display\n if self.verbose:\n print \"Not found any existing working display\"\n\n return self.startServer()", "def find_screen_name(user_id: UserID) -> Optional[str]:\n screen_name = db.session \\\n .query(DbUser.screen_name) \\\n .filter_by(id=user_id) \\\n .scalar()\n\n if screen_name is None:\n return None\n\n return screen_name", "def getDisplay(self):\n m = _Regexps.pidFile.match(os.path.basename(self.filename))\n if m:\n return m.group(1)\n else:\n return None", "def get_screen(self):\n return self._cached('raw', self.ale.getScreen)", "def attachToComponent(self, opts):\n screen = self.findScreen(opts.verbose)\n\n if screen == None:\n print(\"Did not find screen named %s for attach\" % self._screenName)\n return False\n else:\n print(\"Found screen %s\" % screen)\n execCmd(\"%s -x %s\" % (self._screenPath, screen))\n return True", "def master_screen(self):\n return self.screen_manager.master_screen", "def get_board():\r\n try:\r\n get_board_property('BOARD')\r\n except:\r\n logging.info(\"board property not found\")\r\n return -1", "def screen_detach(self):\n self._channel.send('\\x01d')\n rdata = '\\n'.join(self.recv_to_prompt())\n smat = re.search(r'\\[detached from ([^ ]+)\\]', rdata, re.I|re.M)\n if smat:\n sname = smat.group(1)\n else:\n sname = False\n\n return sname", "def get_suspended_screen(self):\n\t\treturn Job(SDK.PrlVm_GetSuspendedScreen(self.handle)[0])", "def getScreenAsImage():\n\treturn _getRectAsImage(None)", "def screen_open(self, sname=None):\n if sname:\n xtitle = sname\n else:\n xtitle = 'msh_' + ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(8))\n\n self.run(\"screen -S %s\" % (xtitle))\n sret = self.run(\"echo $STY\")\n\n return sret", "def getSpimThreadID(self):\n\n\t\ttry:\n\t\t\tapp = api.getDesktopObject()\n\n\t\t\t# Eliminate items with a \"None\" name - these cause the list comprehension to fail.\n\t\t\tapp = filter(lambda x: x.name != None, app.children)\n\t\t\tapp = filter(lambda x: x.name[0:6] == \"PCSpim\", app)[0] # Drill down to the app itself\n\n\t\t\treturn app.windowThreadID\n\t\texcept:\n\t\t\treturn -1 # failure", "def getUserForDisplay(tty):\n\n #We'll use \"query user\" windows powershell command (requires Windows Pro!)\n #PS C:\\Users\\user1> query user\n #USERNAME SESSIONNAME ID STATE IDLE TIME LOGON TIME\n #>user1 console 1 Active 10 2/4/2021 11:26 AM\n # user2 4 Disc 14 2/4/2021 12:21 PM\n # user3 5 Disc 10 2/4/2021 12:24 PM\n \n result = subprocess.run(['powershell.exe', \"-Command\", \"query user\"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)\n logger.info(\"Running command {}\".format(result.args))\n for line in iter(result.stderr.splitlines()):\n logger.warning(line)\n\n user = None\n display = None\n for line in iter(result.stdout.splitlines()):\n #logger.debug(line)\n #we're only looking for the active tty (e.g. console)\n match = re.match(r'^(\\s|\\>)(......................)('+tty+')\\s+', line)\n if match:\n logger.debug(\"Matched line \"+line)\n current_session = match.group(1)\n user = match.group(2).rstrip(\" \")\n display = match.group(3)\n if user:\n return (user, display)\n else:\n raise Exception(\"Unable to find any user logged on {}\".format(tty))", "def start_screen_process(screen_log, session_name, binary_path, binary_params):\n start_cmd = \"screen -L -Logfile {logfile} \" \"-dmS {session} {binary} {params}\"\n start_cmd = start_cmd.format(\n logfile=screen_log,\n session=session_name,\n binary=binary_path,\n params=\" \".join(binary_params),\n )\n\n run_cmd(start_cmd)\n\n # Build a regex object to match (number).session_name\n regex_object = re.compile(r\"([0-9]+)\\.{}\".format(session_name))\n\n # Run 'screen -ls' in a retry_call loop, 30 times with a 1s\n # delay between calls.\n # If the output of 'screen -ls' matches the regex object, it will\n # return the PID. Otherwise, a RuntimeError will be raised.\n screen_pid = retry_call(\n search_output_from_cmd,\n fkwargs={\"cmd\": \"screen -ls\", \"find_regex\": regex_object},\n exceptions=RuntimeError,\n tries=30,\n delay=1,\n ).group(1)\n\n # Make sure the screen process launched successfully\n # As the parent process for the binary.\n screen_ps = psutil.Process(int(screen_pid))\n wait_process_running(screen_ps)\n\n # Configure screen to flush stdout to file.\n run_cmd(FLUSH_CMD.format(session=session_name))\n\n children_count = len(screen_ps.children())\n if children_count != 1:\n raise RuntimeError(\n f\"Failed to retrieve child process id for binary {binary_path}. \"\n f\"screen session process had [{children_count}]\"\n )\n\n return screen_pid, screen_ps.children()[0].pid", "def ThisComponent(self):\n comp = self.StarDesktop.getCurrentComponent()\n if comp is None:\n return None\n impl = comp.ImplementationName\n if impl in ('com.sun.star.comp.basic.BasicIDE', 'com.sun.star.comp.sfx2.BackingComp'):\n return None # None when Basic IDE or welcome screen\n return comp", "def name():\n code = \"get name of current screen saver\"\n return applescript.tell.app(\"System Events\", code).out", "def getCurrentDisplay():\n # Windows reports the active display as 'console', so we hardcode it\n return \"console\"", "def get_current_activity(self):\n cmd = shlex.split(\"adb shell dumpsys window windows | grep -E 'mCurrentFocus'\")\n p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n out, err = p.communicate()\n\n activity_name = out.split(\"\\n\")[0]\n\n if \"Application Error\" in activity_name:\n self.device(text=\"OK\").click()\n return self.get_current_activity()\n\n return activity_name", "def stopComponent(self, opts):\n screen = self.findScreen(opts.verbose)\n\n if screen == None:\n print(\"No screen session named %s to stop\" % self._screenName, file=sys.stderr)\n return False\n\n print(\"Stopping screen instance %s\" % screen)\n\n (autoRestartPid, comm) = execCmd(\"ps --ppid %s -o pid=,comm=\" % screen.split(\".\")[0], opts.verbose).split()\n\n # Any uncaught signal sent to mono (including SIGUSR1) will kill it\n if comm == \"bash\":\n os.kill(int(autoRestartPid), signal.SIGUSR1)\n\n execCmd(\"%s -S %s -p 0 -X stuff quit$(printf \\r)\" % (self._screenPath, screen), opts.verbose)\n\n timeElapsed = 0\n\n while timeElapsed < self._pollingTimeMax:\n time.sleep(self._pollingInterval)\n timeElapsed += self._pollingInterval\n\n screen = self.findScreen(opts.verbose)\n\n if screen == None:\n print(\"Screen instance %s terminated.\" % self._screenName)\n return True\n\n if timeElapsed % self._pollingNotificationInterval == 0:\n print(\"Waited %s seconds for screen named %s to terminate\" % (timeElapsed, self._screenName))\n\n print(\"Screen %s has not terminated after %s seconds. Please investigate.\" % (self._screenName, self._pollingTimeMax), file=sys.stderr)\n return False", "def getComponentStatus(self, opts):\n\n # We'll check screen even if we found PID so that we can get screen information\n screen = self.findScreen(opts.verbose)\n\n if screen == None:\n print(\"Did not find screen named %s\" % self._screenName)\n else:\n print(\"Found screen %s\" % screen)\n\n if opts.verbose:\n print(\"OpenSimulator path: %s\" % self._binaryPath)\n\n if screen != None:\n print(\"Status: ### Active ###\")\n return True\n else:\n print(\"Status: ### Inactive ###\")\n return False", "def _get_pid(self):\n ps_txt = six.ensure_str(self.controller.run(\n args=[\"ps\", \"ww\", \"-u\"+str(os.getuid())]\n ).stdout.getvalue()).strip()\n lines = ps_txt.split(\"\\n\")[1:]\n\n for line in lines:\n if line.find(\"ceph-{0} -i {1}\".format(self.daemon_type, self.daemon_id)) != -1:\n log.info(\"Found ps line for daemon: {0}\".format(line))\n return int(line.split()[0])\n log.info(\"No match for {0} {1}: {2}\".format(\n self.daemon_type, self.daemon_id, ps_txt\n ))\n return None", "def RecipientScreenName(self):\n return self._recipient_screen_name", "def get(self, display):\n if isinstance(display, Split):\n return display\n try:\n return [p for p in self.panes if p.display == display][0]\n except IndexError:\n return None", "def _get_linkable_component(script):\n component = None\n for c in script.components:\n if isinstance(c, SessionComponent):\n return c\n if isinstance(c, SpecialMixerComponent) and not c.is_return_mixer:\n component = c\n\n if component is None:\n if hasattr(script, '_session_ring'):\n return script._session_ring\n return component", "def input(self,input,session,context):\n return BaseScreen(\"None\") if self.next_screen is None else self.next_screen", "def startComponent(self, opts):\n screen = self.findScreen(opts.verbose)\n\n if screen != None:\n print(\"Screen session %s already started.\" % (screen), file=sys.stderr)\n return False\n\n chdir(self._binaryPath, opts.verbose)\n\n cmd = \"%s %s.exe %s\" % (self._monoPath, self._componentName, self._switches)\n\n if opts.autorestart:\n cmd = \"bash -c 'set carryon=true; trap \\\"carryon=false\\\" SIGUSR1; while $carryon; do %s; done'\" % (cmd)\n\n execCmd(\"%s -S %s -d -m %s\" % (self._screenPath, self._screenName, cmd), opts.verbose)\n\n screen = self.findScreen(opts.verbose)\n if screen != None:\n print(\"%s starting in screen instance %s\" % (self._componentName, screen))\n else:\n print(\"ERROR: %s did not start.\" % self._componentName, file=sys.stderr)\n return False\n\n if opts.attach:\n execCmd(\"%s -x %s\" % (self._screenPath, self._screenName))\n\n return True" ]
[ "0.6689616", "0.6689616", "0.6677859", "0.6607923", "0.5972942", "0.59641546", "0.5794162", "0.56380713", "0.5485115", "0.54674524", "0.53979915", "0.53072834", "0.53005725", "0.5264977", "0.5215528", "0.52096665", "0.5200662", "0.5164541", "0.5151755", "0.5118128", "0.51158476", "0.507472", "0.5030981", "0.5021632", "0.50012547", "0.49915668", "0.49873504", "0.49817944", "0.49800876", "0.49525964" ]
0.75568944
0
Get a list of available screens directly from the screen command.
def getScreenList(self, verbose = False): return execCmd("%s -list" % self._screenPath, verbose)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def list_screens(self):\n\n # Check if the form ws submitted\n form = request.forms.get(\"submit\", False)\n\n # If so...\n if form:\n\n # ...find out what the user wanted to do and to which screen\n action, screen = form.split(\"+\")\n\n # Call the relevant action\n if action == \"view\":\n r = requests.get(\"{}{}/view\".format(self.api,\n screen))\n\n elif action == \"enable\":\n r = requests.get(\"{}{}/enable\".format(self.api,\n screen))\n\n elif action == \"disable\":\n r = requests.get(\"{}{}/disable\".format(self.api,\n screen))\n\n elif action == \"configure\":\n redirect(\"/configure/{}\".format(screen))\n\n elif action == \"custom\":\n url = self.custom_screens.get(screen, \"/\")\n redirect(url)\n\n # Rebuild list of screens\n self.process_plugins()\n sc = self.screens\n\n # Return the web page\n return template(\"all_screens.tpl\", screens=sc)", "def findScreen(self, verbose = False):\n screenList = \"\"\n\n try:\n screenList = self.getScreenList(verbose)\n except subprocess.CalledProcessError as cpe:\n screenList = cpe.output\n\n #print \"screenList: %s\" % screenList\n # TODO: Need to improve this for screens with ( in their name\n res = re.search(\"\\s+(\\d+\\.%s)\\s+\\(\" % self._screenName, screenList)\n\n if not res == None:\n return res.group(1)\n else:\n return None", "def silkscreen_commands(self):\n return self.pcb_layers[\"silkscreen\"].commands", "def get_screens_data():\n result = subprocess.run((\"xrandr\", \"--query\"),\n check=True, universal_newlines=True,\n stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n # kinda like sscanf\n props = (('output', str), ('primary', bool), ('width', int), ('height', int))\n regex = re.compile(r\"^(\\S+) connected( primary)? (\\d+)x(\\d+)\",\n flags=re.MULTILINE | re.ASCII)\n for match in regex.findall(result.stdout):\n yield {name: type(value) for (name, type), value in zip(props, match)}", "def set_screens(screen_list):\n global screens, screen_manager\n screens = screen_list\n for s in screen_list:\n screen_manager.add_widget(s)", "def view(self, screen=None):\n r = requests.get(\"{}{}/view\".format(self.api,\n screen))\n\n return template(\"all_screens.tpl\", screens=self.screens)", "def grab_screens() -> QPixmap:\n # grab all screens\n screens = QtWidgets.QApplication.screens()\n pixmaps = []\n w = 0\n h = 0\n for screen in screens:\n pix = screen.grabWindow(0)\n w += pix.width()\n h = max(h, pix.height())\n pixmaps.append(pix)\n\n # merge all pixmaps\n final = QPixmap(w, h)\n painter = QPainter(final)\n final.fill(Qt.white)\n p = 0\n for pixmap in pixmaps:\n painter.drawPixmap(QPoint(p, 0), pixmap)\n p += pixmap.width()\n return final", "def enumerateDisplays():\n displays = {}\n disabledDisplays = {}\n device = None\n activeDisplays = []\n internalDisplay = None\n xrandr = subprocess.Popen('xrandr', stdout=subprocess.PIPE)\n for line in [x.decode() for x in xrandr.stdout.readlines()]:\n match = re.match('(?P<device>[\\w-]+) (?P<disconnected>dis)?connected ', line)\n if match:\n device = match.group('device')\n if isInternalDisplay(device):\n internalDisplay = device\n if match.group('disconnected') is not None:\n device = None\n disabledDisplays[match.group('device')] = []\n else:\n displays[device] = []\n elif device is not None:\n match = re.match(' +(?P<resolution>\\w+)', line)\n if match:\n resolution = match.group('resolution')\n displays[device].append(resolution)\n if line.find('*') != -1:\n activeDisplays += [(device, resolution)]\n xrandr.wait()\n return (displays, activeDisplays, disabledDisplays, internalDisplay)", "def screen_scan(self):\n if self.i2c_screen is None:\n print(\"No I2C bus set for the Screen\")\n raise AntennyScreenException(\"No I2C bus set for the Screen\")\n return self.i2c_screen.scan()", "def create_screens(self):\n\n for name in State.game['screens']:\n self.create_screen(name)", "def get_screen(self):\n return self._cached('raw', self.ale.getScreen)", "def enumerate(self):\n\n # Grab current path plus other interesting paths\n paths = set(pwncat.victim.getenv(\"PATH\").split(\":\"))\n paths = paths | {\n \"/bin\",\n \"/sbin\",\n \"/usr/local/bin\",\n \"/usr/local/sbin\",\n \"/usr/bin\",\n \"/usr/sbin\",\n }\n\n # Look for matching binaries\n with pwncat.victim.subprocess(\n f\"find {shlex.join(paths)} \\\\( -type f -or -type l \\\\) -executable \\\\( -name 'screen' -or -name 'screen-*' \\\\) -printf '%#m %p\\\\n' 2>/dev/null\"\n ) as pipe:\n for line in pipe:\n line = line.decode(\"utf-8\").strip()\n perms, *path = line.split(\" \")\n path = \" \".join(path)\n perms = int(perms, 8)\n\n # When the screen source code is on disk and marked as executable, this happens...\n if os.path.splitext(path)[1] in [\".c\", \".o\", \".h\"]:\n continue\n\n yield \"software.screen.version\", ScreenVersion(path, perms)", "def getscreen(self):\n return self.screen", "def getscreen(self):\n return self.screen", "def run_screen(\n self, screen_operation: colrev.ops.screen.Screen, records: dict, split: list\n ) -> dict:\n\n records = self.__screen_cli(screen_operation, split)\n\n return records", "def getDisplaysAsImages():\n\ttry:\n\t\trects = getDisplayRects()\n\texcept RectFailed as e:\n\t\traise GrabFailed(\"Error during getDisplayRects: \" + str(e))\n\t# im has an origin at (0, 0) in the top-left corner of the virtual screen,\n\t# but our `rect`s have a (0, 0) origin in the top-left corner of the main\n\t# display. So we normalize all coordinates in the rects to be >= 0.\n\tnormalizedRects = normalizeRects(rects)\n\tim = getScreenAsImage()\n\n\treturn list(im.crop(rect) for rect in normalizedRects)", "def list(self):\n return self.rpc.call(MsfRpcMethod.ConsoleList)['consoles']", "def getScreen(self):\n \n return self.screen", "def available_shells(self):", "def measure_screen(screen_x=None, screen_y=None):\n env = os.environ\n def ioctl_GWINSZ(fd):\n try:\n cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234'))\n except:\n return\n return cr\n\n cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)\n if not cr:\n try:\n fd = os.open(os.ctermid(), os.O_RDONLY)\n cr = ioctl_GWINSZ(fd)\n os.close(fd)\n except:\n pass\n\n if not cr:\n cr = (env.get('LINES', 25), env.get('COLUMNS', 80))\n\n if screen_x == None:\n screen_x = int(cr[1])\n\n if screen_y == None:\n screen_y = int(cr[0])\n\n return screen_x, screen_y", "def getScreen(self, screenName):\n return self.screens[self.screenDictionary[screenName]]", "def getCurrentMetrics(self):\n self.notifyPut('Obtaining Current Display Metrics')\n try:\n data = []\n data = win32api.EnumDisplayMonitors(None, None)\n screens = {}\n scrNum = 0\n for screen in data:\n screens[scrNum] = screen[2]\n scrNum += 1\n return screens \n except Exception, e:\n self.logQ.put('{0} - Unable to capture current metrics'.format(e))", "def menu_screen(win):\n\tpass", "def valid_screen(self, screen):\n return (screen is not None and\n screen in self.infoscreen.availablescreens)", "def screen_attach(self, sname):\n self._channel.sendall(\"screen -r %s\\n\" % (sname))\n rdata = '\\n'.join(self._channel.recv(65536).splitlines())\n return rdata", "def getCmdList():\n return [obj for name, obj in inspect.getmembers(sys.modules[__name__]) \n if inspect.isclass(obj) and issubclass(obj, Cmd)][1:]", "def listDisplays(self):\n pidFiles = self._listPidFiles()\n displays = []\n for pidFile in pidFiles:\n pid = pidFile.getPid()\n if self._pidIsMyXvnc(pid):\n displays.append(pidFile.getDisplay())\n else:\n # tidy up\n pidFile.remove()\n if self.verbose:\n print \"Existing displays: %s\" % displays\n return displays", "def screen_open(self, sname=None):\n if sname:\n xtitle = sname\n else:\n xtitle = 'msh_' + ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(8))\n\n self.run(\"screen -S %s\" % (xtitle))\n sret = self.run(\"echo $STY\")\n\n return sret", "def list():\n cmd_output = None\n\n try:\n cmd_output = tmux_exec('ls')\n except CalledProcessError:\n return []\n\n sessions = cmd_output.strip().split('\\n')\n sessions = map(lambda session: session.split(':')[0], sessions)\n\n return sessions", "def get_screen(env):\n # Returned screen requested by gym is 400x600x3\n # Transpose it into torch order (CHW).\n screen = env.render(mode='rgb_array').transpose((2, 0, 1))\n # Convert to float, rescale, convert to torch tensor\n screen = np.ascontiguousarray(screen, dtype=np.float32) / 255\n screen = torch.from_numpy(screen)\n # Resize, and add a batch dimension (BCHW)\n return resize(screen).unsqueeze(0)" ]
[ "0.6648239", "0.64354354", "0.6357261", "0.63446474", "0.632571", "0.62642527", "0.62542605", "0.61480975", "0.596525", "0.5948138", "0.59051406", "0.59023184", "0.58955187", "0.58955187", "0.58858234", "0.58700395", "0.580741", "0.5784875", "0.5708334", "0.57027566", "0.5640237", "0.5517011", "0.5509568", "0.55070823", "0.55061436", "0.5473709", "0.5456216", "0.5453922", "0.5439633", "0.53919244" ]
0.84285045
0
Store previous sorting information for multicolumn sorts.
def on_sort_column_change(self, model): id, order = self.tv.get_model().get_sort_column_id() if id is None and order is None: return False if self.prev_sort_column_id and self.prev_sort_column_id[0][0] == id: self.prev_sort_column_id.pop(0) self.prev_sort_column_id.insert(0, (id, order)) if len(self.prev_sort_column_id) > 2: self.prev_sort_column_id.pop()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def set_as_sort1(self):\n if self.is_sort1:\n #if self.analysis_code == 1:\n #self.nonlinear_factor = np.nan\n #print(self.data_code)\n #print(self._times, type(self._times))\n #aaa\n return\n #print(f'{self.class_name}-{self.table_name}')\n self.table_name = SORT2_TABLE_NAME_MAP[self.table_name]\n self.sort_bits[1] = 0 # sort1\n self.sort_method = 1\n assert self.is_sort1 is True, self.is_sort1\n self._update_time_word()", "def OnReorder( self, event ):\n column = self.columns[event.GetColumn()]\n if column.sortOn:\n # multiple sorts for the click...\n columns = [ self.columnByAttribute( attr ) for attr in column.sortOn ]\n diff = [ (a,b) for a,b in zip( self.sortOrder, columns ) if b is not a[1]]\n if not diff:\n self.sortOrder[0] = (not self.sortOrder[0][0], column)\n else:\n self.sortOrder = [\n (c.defaultOrder,c) for c in columns \n ] + [ (a,b) for (a,b) in self.sortOrder if b not in columns]\n else:\n if column is self.sortOrder[0][1]:\n # reverse current major order\n self.sortOrder[0] = (not self.sortOrder[0][0], column)\n else:\n self.sortOrder = [(column.defaultOrder,column)] + [\n (a,b) \n for (a,b) in self.sortOrder if b is not column \n ]\n # TODO: store current selection and re-select after sorting...\n self.reorder()\n self.Refresh()", "def _change_sort_order(self, column):\n if self.tableView.horizontalHeader().sortIndicatorOrder() == Qt.AscendingOrder and \\\n column == self._last_sorted_column:\n self.tableView.horizontalHeader().setSortIndicator(column, Qt.DescendingOrder)\n self.tableView.horizontalHeader().setSortIndicatorShown(False)\n self.tableView.model().unsort(column)\n self._last_sorted_column = -1\n self._last_sort_order = None\n else:\n self.tableView.horizontalHeader().setSortIndicatorShown(True)\n self._last_sorted_column = column\n self._last_sort_order = self.tableView.horizontalHeader().sortIndicatorOrder()", "def sortby(self):\n ...", "def finalize(self):\n self.set_as_sort1()", "def _sort_hybrid_meta_cols(self):\n self.__hybrid_meta_cols = sorted(\n [c for c in self._hybrid_meta.columns\n if not c.startswith(self._INTERNAL_COL_PREFIX)],\n key=self._column_sorting_key\n )", "def _sort(self):\n self.rows.sort(key=lambda x: (x['PERC1'], x['EQ'], x['PASS'], x['W2']),\n reverse=True)\n\n rank = 0\n prev_perc = 0\n prev_rank = 0\n for row in self.rows:\n if row[\"NR\"] == 0:\n # Something has already populated NR as 0 - so we set rank as\n # 0 too\n row['_RANK'] = 0\n row['_NR'] = 0\n continue\n\n # Increment our count\n rank += 1\n if row['PERC1'] == prev_perc:\n row['NR'] = \"\"\n row['_NR'] = prev_rank # I.e. joint 6th will be 6 here\n row['_RANK'] = rank # I.e. joint 6th could be 7, or 8 etc. here\n else:\n row['NR'] = rank\n row['_NR'] = rank\n row['_RANK'] = rank\n prev_perc = row['PERC1']\n prev_rank = rank", "def sort_column(self, column):\n if column == 1: # type\n self.sorted_keys = sorted(self.data_dict.keys(),\n key=lambda x: (self.data_dict[x]['type']),\n reverse=self.sorted_type_top)\n # Invert sorting method\n self.sorted_type_top = not self.sorted_type_top\n\n elif column == 2: # Score\n self.sorted_keys = sorted(self.data_dict.keys(),\n key=lambda x: (float(self.data_dict[x]['score'])),\n reverse=self.sorted_score_top)\n # Invert sorting method\n self.sorted_score_top = not self.sorted_score_top\n\n elif column == 4: # Duration\n d = dict()\n for k in self.sorted_keys:\n duration_string = self.data_dict[k]['duration']\n\n # Get amount of episodes\n if 'episode' in duration_string:\n if 'Some' in duration_string:\n episodes = 0\n else:\n episodes = int(duration_string.split(' episodes')[0])\n else:\n episodes = 1\n\n # Get the duration in minutes\n minutes = 0\n if 'min' in duration_string:\n minutes = int(re.findall('([0-9]+)min', duration_string)[0])\n if 'h' in duration_string:\n minutes += int(re.findall('([0-9]+)h', duration_string)[0]) * 60\n\n # Get total duration of the whole show\n minutes *= episodes\n\n # Store it for sorting\n d[k] = minutes\n\n # Sort titles based on duration\n self.sorted_keys = sorted(d.keys(),\n key=lambda x: d[x],\n reverse=self.sorted_duration_top)\n # Invert sorting method\n self.sorted_duration_top = not self.sorted_duration_top\n\n elif column == 5: # release year\n self.sorted_keys = sorted(self.data_dict.keys(),\n key=lambda x: (float(self.data_dict[x]['released'])),\n reverse=self.sorted_year_top)\n # Invert sorting method\n self.sorted_year_top = not self.sorted_year_top\n\n if column != 2:\n # Make sure next time we click to sort by score,\n # the highest score is on top\n self.sorted_score_top = True\n\n # Redraw the table\n self.setup_tableview()", "def sort(self, trans, query, ascending, column_name=None):\n return grids.GridColumn.sort(self, trans, query, ascending, column_name=\"history_id\")", "def oldsortslice(self):\n ...", "def reversesort(self):\n ...", "def _reset_header(self):\n new_header = []\n for col_name in self.header:\n is_left = self.left_cols.get(col_name)\n if is_left:\n new_header.append(col_name)\n self.header = new_header", "def _sort(self, row):\n if not self._head:\n self._head = self._create_head(row)\n if self._args.head:\n return row\n\n if 'key' not in self._state:\n self._state['key'] = self._replace_fields(self._args.key)\n\n r = list(map(self._convert, row))\n self._sorting_insert(self._result, r, key=lambda r: eval(self._state['key']))", "def sort_key(self):\n ...", "def __handle_sorts(self, df):\n for sort in self.sorts:\n ascending = True if sort.order == SortOrder.ASCENDING else False\n if sort.sortType == SortType.ABSOLUTE_VALUE:\n df = df.reindex(df[sort.columnName].abs().sort_values(ascending=ascending, na_position='last').index)\n else:\n df = df.sort_values(by=sort.columnName, ascending=ascending, na_position='last')\n return df", "def get_sort_by(self):\n\n\t\treturn self.__sort_by", "def get_sort_columns_raw(self):\n col_sort_orders = self.gridpreference_sort.all().select_related()\n \n return [x.sort_display for x in col_sort_orders]", "def sort_results(self):\n pass", "def reorder( self ):\n self.sorted.sort(self.compareFunction)", "def _sort_phot(self, verbose=False):\n if hasattr(self, \"data\") and hasattr(self, \"data_filters\"):\n ## This looks fugly.\n newkeys = np.array([i for i in self.data_filters.keys()])[np.argsort([self.data_filters[i].lambda_effective.value for i in self.data_filters])]\n\n sorted_data = OrderedDict()\n sorted_data_filters = OrderedDict()\n\n for newkey in newkeys:\n\n if verbose: print(newkey)\n\n sorted_data[newkey] = self.data[newkey]\n sorted_data_filters[newkey] = self.data_filters[newkey]\n\n self.data = sorted_data\n self.data_filters = sorted_data_filters\n\n else:\n warnings.warn(\"Doesn't seem to be any data here (empty self.data)\")\n pass", "def reorder_columns(the_reset_of_column, is_dict=False):\n cprint(f\"### Function Name:-> {inspect.stack()[0][3]} ###\", 'yellow', 'on_grey', attrs=['bold'])\n unique_idx = \"unique identifier (id)\"\n unique_col = ''\n\n try:\n if is_dict is False:\n for col in the_reset_of_column:\n if unique_idx in col.lower():\n idx = the_reset_of_column.index(col)\n unique_col = col\n del the_reset_of_column[idx]\n the_reset_of_column.insert(0, unique_col)\n\n return the_reset_of_column\n else:\n new_ordered_list = []\n for col_name, col_dtype in the_reset_of_column.items():\n if unique_idx in col_dtype:\n new_ordered_list.insert(0, col_name)\n else:\n new_ordered_list.append(col_name)\n\n return new_ordered_list\n\n except Exception as ex:\n cprint(traceback.format_exc(), 'red')\n log_exception(traceback.format_exc())", "def sort_on(self):\n if \"sortOn\" in self._prop_dict:\n return self._prop_dict[\"sortOn\"]\n else:\n return None", "def get_sort_order(self):\n\n\t\treturn self.__sort_order", "def data_for_sorting() -> NoReturn:\n raise NotImplementedError", "def data_for_sorting() -> NoReturn:\n raise NotImplementedError", "def _format_meta_pre_merge(self):\n self.__col_name_map = {\n ColNameFormatter.fmt(c): c\n for c in self.data.solar_meta.columns.values\n }\n\n self._rename_cols(self.data.solar_meta, prefix=SOLAR_PREFIX)\n self._rename_cols(self.data.wind_meta, prefix=WIND_PREFIX)\n\n self._save_rep_prof_index_internally()", "def double_sort(data, last_var=0):\n \n # doing simply np.sort(np.sort(pairs, axis=1), axis=0)\n # would uncouple first and second elements of pairs\n # during the second sorting (axis=0)\n data = np.sort(data, axis=1)\n x_sort = np.argsort(data[:, 0])\n data = data[x_sort]\n \n return data", "def cvarsort(self):\n return self.sortinfo.get(CVARSORT)", "def sorted(self): \n pass", "def _sortHandler(self) -> None:\n response, columnIndex, ascending = self._sortDialog()\n order = Qt.AscendingOrder if ascending else Qt.DescendingOrder\n if response:\n self._mainFileView.sortByColumn(columnIndex, order)" ]
[ "0.5893826", "0.5629862", "0.55866504", "0.5547809", "0.55312973", "0.53235435", "0.53210545", "0.5307315", "0.52941406", "0.5270745", "0.5201339", "0.51783633", "0.51715374", "0.5168619", "0.5166643", "0.5110402", "0.51094055", "0.51090115", "0.5073252", "0.50645584", "0.5064289", "0.5060438", "0.5048527", "0.50413465", "0.50413465", "0.5039226", "0.5014261", "0.4993158", "0.49914727", "0.49782184" ]
0.6001303
0
Set up the Ruckus Unleashed integration in Open Peer Power.
async def init_integration(opp) -> MockConfigEntry: entry = mock_config_entry() with patch( "openpeerpower.components.ruckus_unleashed.Ruckus.connect", return_value=None, ), patch( "openpeerpower.components.ruckus_unleashed.Ruckus.mesh_name", return_value=DEFAULT_TITLE, ), patch( "openpeerpower.components.ruckus_unleashed.Ruckus.system_info", return_value=DEFAULT_SYSTEM_INFO, ), patch( "openpeerpower.components.ruckus_unleashed.Ruckus.ap_info", return_value=DEFAULT_AP_INFO, ), patch( "openpeerpower.components.ruckus_unleashed.RuckusUnleashedDataUpdateCoordinator._fetch_clients", return_value={ TEST_CLIENT[API_MAC]: TEST_CLIENT, }, ): entry.add_to_opp(opp) await opp.config_entries.async_setup(entry.entry_id) await opp.async_block_till_done() return entry
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def startup( self ):\n # ---- Setup UPNPC ----\n if self.config.neuron.use_upnpc:\n bittensor.logging.success(prefix = 'Set upnpc', sufix = '<green>ON</green>')\n try:\n self.external_port = net.upnpc_create_port_map( port = self.axon.port )\n except net.UPNPCException as upnpc_exception:\n logger.critical('Failed to hole-punch with upnpc')\n raise RuntimeError('Failed to hole-punch with upnpc')\n else:\n bittensor.logging.success(prefix = 'Set upnpc', sufix = '<red>OFF</red>')\n self.external_port = self.config.axon.port\n\n # ---- Get external ip ----\n try:\n self.external_ip = net.get_external_ip()\n bittensor.logging.success(prefix = 'External IP', sufix = '<blue>{}</blue>'.format(self.external_ip))\n except net.ExternalIPNotFound as external_port_exception:\n raise RuntimeError('Unable to attain your external ip. Check your internet connection. error:{}', external_port_exception)\n\n # ---- Setup tensorboard ----\n if self.config.neuron.use_tensorboard == True:\n self._tensorboard_program = program.TensorBoard()\n self._tensorboard_program.configure(argv=[None, '--logdir', self.config.neuron.full_path, '--load_fast=true'])\n self._tensorbaord_url = self._tensorboard_program.launch()\n bittensor.logging.success(prefix = 'Set tensorboard', sufix = '<blue>http://localhost:6006/</blue>')\n else: bittensor.logging.success(prefix = 'Set tensorboard', sufix = '<red>OFF</red>')\n\n # ---- Setup Wallet. ----\n if not self.wallet.has_coldkeypub:\n self.wallet.create_new_coldkey( n_words = 12, use_password = True )\n if not self.wallet.has_coldkeypub:\n raise RuntimeError('Miner must have access to a decrypted coldkeypub')\n if not self.wallet.has_hotkey:\n self.wallet.create_new_hotkey( n_words = 12, use_password = False )\n if not self.wallet.has_hotkey:\n raise RuntimeError('Miner must have access to a decrypted hotkey')\n\n # ---- Subscribe to chain ----\n subscribe_success = self.subtensor.subscribe(\n wallet = self.wallet,\n ip = self.external_ip,\n port = self.external_port,\n modality = bittensor.proto.Modality.TEXT,\n wait_for_finalization = True,\n timeout = 4 * bittensor.__blocktime__,\n )\n if not subscribe_success:\n raise RuntimeError('Failed to subscribe neuron.')\n\n # ---- Starting axon ----\n self.axon.start()", "def setup(self):\n # if not system.restore_snapshot():\n # self.log.debug(\"No snapshot to restore, if this is not expected please contact automation team\")\n crindsim.set_mode(\"manual\")\n pos.connect()\n pos.sign_on()", "def initialize_home_hub(argv):\n parse_cmd_line_opts(argv)\n init_logging()\n init_error_reporting()\n \n # Verify we have a valid home id\n if HOME_ID is None:\n print('Home ID is invalid or missing. Please provide an integer following the -i flag')\n exit()\n\n # Begin Home Hub Specific Setup\n logger.info('Starting the Home Hub main program for Home: %s', HOME_ID)\n\n # Get the email and password for this HH's user from the env vars\n powernet_user_email = os.getenv('POWERNET_USER_EMAIL', None)\n powernet_user_password = os.getenv('POWERNET_USER_PASSWORD', None)\n \n if powernet_user_email is None:\n logger.info('Missing the required login email address')\n logger.info('Please set the POWERNET_USER_EMAIL environment variable and try again')\n exit()\n \n if powernet_user_password is None:\n logger.info('Missing the required login password')\n logger.info('Please set the POWERNET_USER_PASSWORD environment variable and try again')\n exit()\n \n # attempt to authenticate against our API\n form_payload = {'email': powernet_user_email, 'password': powernet_user_password}\n response = requests.post('https://pwrnet-158117.appspot.com/api/v1/powernet_user/auth/', data=form_payload)\n auth_token = response.json()['token']\n\n # Initializing variables for queue and threads\n rpi = HardwareInterface(house_id=HOME_ID, gpio_map=None, auth_token=auth_token)\n buffer_size = 8\n q_ai = Queue(buffer_size)\n\n # Initialize threads\n producer_ai_thread = Thread(name='Producer', target=rpi.producer_ai, args=(q_ai,))\n producer_ai_thread.start()\n\n consumer_ai_thread = Thread(name='Consumer', target=rpi.consumer_ai, args=(q_ai,))\n consumer_ai_thread.start()\n\n devices_thread = Thread(name='Device', target=rpi.devices_th)\n devices_thread.start()\n\n load_control_thread = Thread(name=\"LoadControl\", target=rpi.local_controller_th)\n load_control_thread.start()", "async def test_setup(hass: HomeAssistant, ufp: MockUFPFixture) -> None:\n\n await hass.config_entries.async_setup(ufp.entry.entry_id)\n await hass.async_block_till_done()\n\n assert ufp.entry.state == ConfigEntryState.LOADED\n assert ufp.api.update.called\n assert ufp.entry.unique_id == ufp.api.bootstrap.nvr.mac", "def setup(self):\n if not system.restore_snapshot():\n self.log.warning(\"Not able to restore snapshot\")\n\n pos.connect()\n\n pos.sign_on()", "def setup(self):\n #if not system.restore_snapshot():\n # self.log.debug(\"No snapshot to restore, if this is not expected please contact automation team\")\n if not pos.connect():\n self.tc_fail(\"Failed to connect to POS\")\n self.recover()", "def initialize(self):\n self.log.info(\"Initialize raspPinball hardware.\")\n\n self.config = self.machine.config['rasppinball']\n self.machine.config_validator.validate_config(\"rasppinball\", self.config)\n print(\"***************************\")\n print(self.config)\n #self.machine_type = (\n # self.machine.config['hardware']['driverboards'].lower())\n\n self._connect_to_hardware()\n\n\n # keypad\n self._kp = Keypad()\n self.old_key = \"\"\n self.key = \"\"\n # leds\n self.init_strips()", "def setup(self):\n self.log.debug('RFSwitch - in RFSwitch setup()')\n # Add resource setup code here\n print(\"Calling RFSwitch:setup\")", "def setUp(self):\n import protolibs.ics_servers as ics_servers\n from point import Point\n from configobj import ConfigObj\n\n # Get config file\n configfile = '/'.join(['sims', 'rtutank', 'config'])\n config=ConfigObj(infile=configfile, unrepr=True)\n self.config = config\n #Set global variable devconfig here \n devconfig=config['vdevs']['slave'] \n\n ##--Set up points\n points={}\n for p in devconfig['points']:\n points.update( { p['name'] : Point(**p) } ) \n #The ** treats the p dictionary as the arguments to the Point class\n self.server = ics_servers.ModbusRTU(devconfig['icsifaces'][0], points.values())\n self.server.start()", "async def async_setup(self):\n token = self._august_gateway.access_token\n # This used to be a gather but it was less reliable with august's recent api changes.\n user_data = await self._api.async_get_user(token)\n locks = await self._api.async_get_operable_locks(token)\n doorbells = await self._api.async_get_doorbells(token)\n if not doorbells:\n doorbells = []\n if not locks:\n locks = []\n\n self._doorbells_by_id = {device.device_id: device for device in doorbells}\n self._locks_by_id = {device.device_id: device for device in locks}\n self._house_ids = {device.house_id for device in chain(locks, doorbells)}\n\n await self._async_refresh_device_detail_by_ids(\n [device.device_id for device in chain(locks, doorbells)]\n )\n\n # We remove all devices that we are missing\n # detail as we cannot determine if they are usable.\n # This also allows us to avoid checking for\n # detail being None all over the place\n\n # Currently we know how to feed data to yalexe_ble\n # but we do not know how to send it to homekit_controller\n # yet\n _async_trigger_ble_lock_discovery(\n self._hass,\n [\n lock_detail\n for lock_detail in self._device_detail_by_id.values()\n if isinstance(lock_detail, LockDetail) and lock_detail.offline_key\n ],\n )\n\n self._remove_inoperative_locks()\n self._remove_inoperative_doorbells()\n\n pubnub = AugustPubNub()\n for device in self._device_detail_by_id.values():\n pubnub.register_device(device)\n\n self.activity_stream = ActivityStream(\n self._hass, self._api, self._august_gateway, self._house_ids, pubnub\n )\n await self.activity_stream.async_setup()\n pubnub.subscribe(self.async_pubnub_message)\n self._pubnub_unsub = async_create_pubnub(\n user_data[\"UserID\"],\n pubnub,\n self.brand,\n )\n\n if self._locks_by_id:\n # Do not prevent setup as the sync can timeout\n # but it is not a fatal error as the lock\n # will recover automatically when it comes back online.\n self._config_entry.async_create_background_task(\n self._hass, self._async_initial_sync(), \"august-initial-sync\"\n )", "def __init__(self):\n super(UpnpEmbeddedDevice, self).__init__()\n return", "def setupHw():\n\n pin.setupHw()\n pin.setupOutPins(traffic_lights)\n pin.setDebug(False)", "def setup(self, rc):\n pass", "def init():\n\n global registry, fsk_router, ook_router\n\n radio.init()\n OpenThings.init(Devices.CRYPT_PID)\n\n fsk_router = Registry.Router(\"fsk\")\n\n #OOK receive not yet written\n #It will be used to be able to learn codes from Energenie legacy hand remotes\n ##ook_router = Registry.Router(\"ook\")\n\n registry = Registry.DeviceRegistry()\n registry.set_fsk_router(fsk_router)\n ##registry.set_ook_router(ook_router\n\n path = os.path.join(sys.path[0], registry.DEFAULT_FILENAME)\n if os.path.isfile(path):\n registry.load_from(path)\n print(\"loaded registry from file\")\n registry.list()\n fsk_router.list()\n\n # Default discovery mode, unless changed by app\n ##discovery_none()\n ##discovery_auto()\n ##discovery_ask(ask)\n discovery_autojoin()\n ##discovery_askjoin(ask)", "def setup(self):\n self.log.debug('upm - in upm setup()')\n # Add resource setup code here", "def setup():\n global zb\n # Signal handler (Ctrl+C exit)\n signal.signal(signal.SIGINT, signal_handler) \n # DBus\n session_bus = dbus.SessionBus()\n objXBZB = session_bus.get_object(PROTOCOL_BUS_NAME, PROTOCOL_OBJ_PATH + \"/\" + XBEE_ZB + \"/\" + SOCKET0)\n zb = dbus.Interface(objXBZB, dbus_interface=PROTOCOL_BUS_NAME)", "def setUp(self):\n sumo_bin = sumolib.checkBinary('sumo')\n traci.start([sumo_bin, \"-n\", self.network_path, \"-r\", self.routes_path])\n traci.simulationStep()", "def usb_setup():\n print(\"Warning: using deprecated usb_setup routine!\")\n largest = largest_partition()\n medium = medium_partition()\n smallest = smallest_partition()\n\n print(\"Starting USB installation\")\n print(\"Using {} as archive storage\".format(largest))\n print(\"Using {} as volatile storage\".format(medium))\n print(\"Using {} as important storage\".format(smallest))\n\n lncm_usb = \"/usr/local/sbin/lncm-usb\"\n\n cli_invocation = [\n lncm_usb,\n largest,\n medium,\n smallest,\n get_uuid(largest),\n get_uuid(medium),\n get_uuid(smallest),\n str(largest_part_size()),\n ]\n\n call(cli_invocation)", "def auto_setup(self):\n if self.mot_type == \"xps8p\":\n return\n if self.get_par(\"err_sevr\") == 3:\n print \"Reinitializing motor {}...\".format(self.name)\n self.reinit()\n ok = self.wait_par(\"err_sevr\", 3, match_value=False, timeout=20)\n if ok:\n print \"Successfully reinitialized {}.\".format(self.name)\n time.sleep(0.5)\n else:\n print \"Reinitializing {} timed out. Aborting auto_setup.\".format(self.name)\n return\n\n for i in range(3):\n for clear, name in ((self.clear_pu, \"powerup\"),\n (self.clear_stall, \"stall flag\"),\n (self.clear_error, \"error flag\")):\n clear(check=True, wait=False)\n\n ok = []\n for bit, mask in ((RA_POWERUP, 1), (RA_STALL, 1), (RA_ERR, RA_ERR_MASK)):\n ok.append(self._wait_msta_bit(bit, 0, mask, timeout=10))\n if not all(ok):\n print \"Issues with clearing flags for {}\".format(self.name)\n\n try: # Not every environment has pmgr access\n self.pmgr.apply_config(dumb_config=self.name)\n except:\n pass", "def _setup_rumble(self):\n self.left_rumble = self._get_ready_to('99500')\n self.right_rumble = self._get_ready_to('00599')\n self.double_rumble = self._get_ready_to('99599')", "async def _hw_init(self):\n await self._write_async(b\":XR\\r\") # Broadcast: initialize + execute\n # Note: no need to consume reply here because there is none (since we are using broadcast)", "def setupMonti():\n #Update /etc/hosts with mongo-server and management-engine nodes\n sudo(\"apt-get install zookeeper\")\n sudo(\"apt-get install zookeeperd\")\n sudo(\"pip2 install chariot-runtime\")\n #update configuration file located in /etc/chariot/chariot.conf\n run (\"cd /etc/init.d && sudo update-rc.d chariot-nmw defaults 99\")\n sudo(\"reboot\")", "def setup_method(self, method):\n self.opp = get_test_open_peer_power()", "def setup_method(self, method):\n self.opp = get_test_open_peer_power()", "def setup(bot):\n\tbot.add_cog(Wallet(bot))", "def setup(self):\n self.pi.set_pull_up_down(self.gpio, pigpio.PUD_OFF)\n self.pi.set_watchdog(self.gpio, 0)\n self.register_callbacks()", "def setup():\n print('Setup option is not working')\n quit()\n print('Long press the reset button until the blue Led is blinking quickly')\n print('Long press again until blinking slowly')\n print('Manually connect this device to the Wifi SSID named BlroadlinkProv')\n print('Press security mode (0 = none, 1 = WEP, 2 = WPA1, 3 = WPA2, 4 = WPA1/2)')\n print('Default:3')\n\n security = raw_input('Security mode:').lower()\n\n if security == 'none':\n security = 0\n elif security == 'wep':\n security = 1\n elif security == 'wpa1':\n security = 2\n elif (security == 'wpa2') or (security == ''):\n security = 3\n elif security == 'wpa1/2':\n security = 4\n security = int(security)\n if not(0 <= security <= 4):\n raise IndexError\n\n ssid = raw_input('SSID of your router :')\n if security != 0:\n password = raw_input('Password:')\n else:\n password = ''\n broadlink.setup(ssid, password, security)", "def main():\n\n # Install crypt32 (not required for Proton 3.16-3 and up)\n util.protontricks('crypt32')\n\n # Install directmusic, set overrides\n util.protontricks('directmusic')\n util.winedll_override('dmime', 'n')\n util.winedll_override('dmsynth', 'n')\n util.winedll_override('dmusic', 'n')\n util.winedll_override('dsound', 'n')\n util.winedll_override('dswave ', 'n')\n util.winedll_override('l3codecx', 'n')\n\n # Set sound to alsa\n util.protontricks('sound=alsa')\n\n # Disable launcher\n util.replace_command('patriots.exe', 'riseofnations.exe')", "def launch():\n\n core.openflow.addListenerByName(\"ConnectionUp\", _handle_ConnectionUp)\n log.info(\"Hub running\")", "def setUp(self):\n self.pump = Pump('127.0.0.1', 8000)" ]
[ "0.6547017", "0.5888096", "0.5840804", "0.5837989", "0.5739", "0.57326514", "0.57269007", "0.57230777", "0.5663273", "0.56224823", "0.5589745", "0.5567595", "0.55671215", "0.5561098", "0.55436313", "0.5507387", "0.54814506", "0.54813504", "0.5467217", "0.5465253", "0.5435919", "0.54321074", "0.54231024", "0.54231024", "0.5414604", "0.5413742", "0.5400242", "0.53987914", "0.5392234", "0.53908825" ]
0.63256496
1
Translate an OID into a string suitable for printing.
def oid2name(oid): if not isinstance(oid, (str, unicode)) or not all(o.isdigit() for o in oid.split(".")): raise ValueError("Parameter does not look like an OID string: " + repr(oid)) return _oid2name.get(oid, oid)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __repr__(self) -> str:\n return \"-\".join(chain((\"OID\",), map(str, self.value)))", "def show_oid(oid: str=typer.Argument('', help=\"OID name or GUID\",\n autocompletion=oid_completer)) -> None:\n uid: UUID = None\n name: str = None\n node: Node = None\n try:\n uid = UUID(oid)\n except Exception: # pylint: disable=W0703\n name = oid\n\n if uid is not None:\n node = oid_registry.get(uid)\n else:\n node = oid_registry.find(lambda x: x.full_name.startswith(name))\n if node is None:\n console.print_error('OID not registered!')\n return\n\n table = Table.grid()\n table.add_column(style='green')\n table.add_column()\n table.add_row('OID:', Text(node.oid, style='number'))\n table.add_row('UID:', _h(Text(str(node.uid))))\n table.add_row('Node name:', Text(node.name))\n table.add_row('Full name:', Text(node.full_name))\n table.add_row('Description:', Text(node.description))\n table.add_row('Contact:', Text(node.contact))\n table.add_row('E-mail:', _h(Text(node.email)))\n table.add_row('Site:', _h(Text(node.site)))\n table.add_row('Node spec.:', _h(Text(str(node.node_spec))))\n table.add_row('Node type:', _h(Text(node.node_type.name)))\n table.add_row('Parent spec.: ', _h(Text(str(node.parent_spec))))\n console.print(table)", "def _idprint(target):\n return ''.join([\"%02X\" % char for char in bytearray(target)])", "def internal2spice(self,asteroid):\n return(str(2444444+asteroid.id))", "def stringReco(obj):\n name = obj.get_name()\n name = obj._pid if (name is None) else name\n return (\"pdg: \" + name + \" E: \" + str(obj._E)\n + \" px: \" + str(obj._px) + \" py: \" + str(obj._py)\n + \" pz: \"+ str(obj._pz) + \" mass: \" + str(obj._m))", "def getValueAsString(self, o: ghidra.util.graph.KeyedObject) -> unicode:\n ...", "def id_str(self):\n if hasattr(self, 'id'):\n return str(self.id)\n else:\n return 'obj%s' % id(self)", "def internal_id_to_display_id(i_id: int) -> str:\n i_id = str(i_id).zfill(9)\n return ''.join(i_id[x - 1] for x in [1, 5, 9, 6, 3, 8, 2, 4, 7])", "def arg2str(expr, pos=None, loc_db=None):\n\n if isinstance(expr, ExprId) or isinstance(expr, ExprInt):\n return str(expr)\n\n elif isinstance(expr, ExprLoc):\n if loc_db is not None:\n return loc_db.pretty_str(expr.loc_key)\n else:\n return str(expr)\n return str(expr)", "def astr(obj):\n\treturn unicode(obj).encode(\"ascii\", \"replace\")", "def get_printable_object_name(obj):\n try:\n if isinstance(obj, dict):\n return \"Dict ID={}: first-5-keys={}\".format(id(obj), list(obj.keys())[:10])\n else:\n return \"{}: {}\".format(type(obj), str(obj))\n except TypeError:\n return \"Foreign object (raised TypeError): {}, ID={}\".format(type(obj), id(obj))\n except ModuleNotFoundError:\n return \"Foreign object (raised ModuleNotFoundError): {}, ID={}\".format(type(obj), id(obj))", "def autoid(self) -> str:", "def autoid(self) -> str:", "def _convert_os_to_sio(id):\n\n # Base64 encode the id to get a volume name less than 32 characters due\n # to ScaleIO limitation.\n name = six.text_type(id).replace(\"-\", \"\")\n try:\n name = base64.b16decode(name.upper())\n except (TypeError, binascii.Error):\n pass\n encoded_name = name\n if isinstance(encoded_name, six.text_type):\n encoded_name = encoded_name.encode('utf-8')\n encoded_name = base64.b64encode(encoded_name)\n if six.PY3:\n encoded_name = encoded_name.decode('ascii')\n return encoded_name", "def lstr (obj):\n\n cmdlenc = locale.getdefaultlocale()[1]\n return repr(obj).decode(\"unicode_escape\").encode(cmdlenc)", "def __str__(self):\n return str(self._id())", "def str_id(self, id):\n\t\ts = bin(id)\n\t\ts = '0'*64 + s[2:]\n\t\tidbits = 64 - (2*self.xybits+self.tbits)\n\t\tret = []\n\t\tnover = self.xybits - self.level\n\t\tfor l, k in [(0, idbits), (0, self.tbits), (nover, self.xybits), (nover, self.xybits)]:\n\t\t\tc = s[-k:]\n\t\t\ts = s[:-k]\n\t\t\tif l:\n\t\t\t\tc = c[:-l] + '[' + c[-l:] + ']'\n\t\t\tret.insert(0, c)\n\t\treturn ' '.join(ret)", "def computed_id(o):\n\n if o.id is not None and o.id.startswith(namespace + \":\"):\n return o.id\n\n return \"{i.namespace}:{i.accession}\".format(i=computed_identifier(o))", "def __str__(self):\n return self.identifier", "def __str__(self):\n return self.identifier", "def __str__(self):\n return self.identifier", "def gnss2str(gnss_id: int) -> str:\r\n\r\n try:\r\n return GNSSLIST[gnss_id]\r\n except KeyError:\r\n return str(gnss_id)", "def str_(object_):\n return str(object_)", "def __str__(self) -> str:\n return f'P{self.id}'", "def stringifyID(point: dict, uid: Union[int, str]) -> str:\n # ordinal time for begin (b) and end (e)\n b = dt.datetime.fromisoformat(point['TBTimestamp']).strftime('%s')\n e = dt.datetime.fromisoformat(point['TETimestamp']).strftime('%s')\n # string concat of all sensor labels\n values = \"-\".join([str(sens[\"Scaled\"]) for sens in point[\"Channels\"]])\n\n idString = f\"{uid}-{b}-{e}_{values}\" # actual id string\n return idString", "def get_device_value_oid(ip, oid, community_string=\"public\"):\n\n iterator = get_iterator(ip, oid, community_string, is_oid=True)\n\n error_indication, error_status, error_index, var_binds = next(iterator)\n\n if error_indication: # SNMP engine errors\n print(error_indication)\n else:\n if error_status: # SNMP agent errors\n print(\n '%s at %s' % (error_status.prettyPrint(), var_binds[int(error_index) - 1] if error_index else '?'))\n else:\n for varBind in var_binds: # SNMP response contents\n return str(varBind).split(\"=\")[1].replace(\" \", \"\")", "def _to_str(obj: object) -> str:\n if obj is Ellipsis:\n return '...'\n elif isinstance(obj, type) and not isinstance(obj, _GENERIC_ALIAS_TYPE):\n if obj.__module__ == 'builtins':\n return obj.__qualname__\n else:\n return f'{obj.__module__}.{obj.__qualname__}'\n else:\n return repr(obj)", "def print_atom(atom):\n\n return atom[\"id\"]", "def computed_identifier(o):\n\n pfx = vmc_model_prefixes[type(o)]\n dig = digest(o)\n accession = \"{pfx}_{dig}\".format(pfx=pfx, dig=dig)\n ir = models.Identifier(namespace=namespace, accession=accession)\n return ir", "def get_str(self, obj):\n if self.pretty:\n return pprint.pformat(obj)\n else:\n return str(obj)" ]
[ "0.6707145", "0.6375536", "0.63288414", "0.6170568", "0.6022612", "0.60083026", "0.5973114", "0.5937652", "0.59257114", "0.5896126", "0.58893806", "0.5858727", "0.5858727", "0.58204067", "0.5775452", "0.57691926", "0.5726823", "0.57196903", "0.56979704", "0.56979704", "0.56979704", "0.56549245", "0.56507134", "0.5637632", "0.5636964", "0.563366", "0.56322783", "0.5628591", "0.56213367", "0.5607437" ]
0.6383701
1
Run analysis pipeline on video existing on local machine
def local_video(**kwargs): output_dir = run_video_preprocess( video_file=input_video, roi_locations=kwargs["roi_locations"], preprocess_analysis=kwargs["preprocess_analysis"], database=False ) run_analysis_pipeline( preprocess_analysis=kwargs["preprocess_analysis"], json_filepath=output_dir, )
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def main(path):\n logger.info(f'Processing video file {path}')\n # Extract audio\n audio_file = extract_audio(path, pipeline_config.audio_target_dir)\n\n # Generate sound classification results and speech recogniser results\n sound_results = SoundRecogniser().process_file(audio_file)\n sound_results = process_overlap(sound_results)\n speech_results = SpeechRecogniser().process_file(audio_file)\n\n # NLP\n wrds = get_words(speech_results)\n nlp = SpaCyNaturalLanguageProcessor(pipeline_config.spacy_model)\n custom_nlp = SpaCyNaturalLanguageProcessor(pipeline_config.custom_spacy_model)\n processor = nlp.get_spacy_results_processor(wrds, speech_results)\n custom_processor = custom_nlp.get_spacy_results_processor(wrds, speech_results)\n chunk_results = processor.process_speech_results_chunk()\n ner_results = processor.process_speech_results_ner()\n ner_results.extend(custom_processor.process_speech_results_ner())\n match_results = processor.process_speech_results_match()\n speech_results = nlp.process_spurious_words(speech_results, chunk_results)\n\n # Add Speech recogniser results, sound classification results and NLP results to a subtitle file\n subs_1 = save_to_subtitles(speech_results,\n lambda speech_result: speech_result['word'])\n subs_1 = compress_subs(subs_1)\n subs_2 = save_to_subtitles(sound_results,\n lambda sound_result: sound_result['class'])\n subs_2 = flatten_subs(subs_2)\n subs_3 = save_to_subtitles(chunk_results,\n lambda chunk_result: f'{chunk_result[\"word\"]} ({chunk_result[\"head\"]})')\n subs_4 = save_to_subtitles(ner_results,\n lambda ner_result: f'{ner_result[\"type\"]} {ner_result[\"word\"]}')\n subs_5 = save_to_subtitles(match_results,\n lambda match_result: match_result[\"word\"])\n\n combined_subs = append_subs(None, subs_1, style='bottom')\n combined_subs = append_subs(combined_subs, subs_2, exclude=['bottom'], style='top', formatter=lambda x: f'({x})')\n combined_subs = append_subs(combined_subs, subs_3, style='left')\n combined_subs = append_subs(combined_subs, subs_4, style='right')\n combined_subs = append_subs(combined_subs, subs_5, style='bottom_left_pred')\n combined_subs = remove_tiny_subs(combined_subs, duration_millis=1000, left_millis=None,\n right_millis=None, style='top')\n subtitle_file_name = os.path.splitext(path)[0] + '.ass'\n create_styles(combined_subs)\n combined_subs.save(subtitle_file_name)\n\n # Burn to a video\n burn_subtitles_into_video(path, subtitle_file_name, pipeline_config.audio_target_dir)\n logger.info(f'Done processing {audio_file}')", "def main():\n parser = argparse.ArgumentParser(description=\"Tracks adult fish\")\n # add options for argument parser\n parser.add_argument(\"in_path\",\n help=\"Path to the video directory.\")\n parser.add_argument(\"out_path\",\n help=\"Directory for results. Should be empty.\")\n parser.add_argument(\"-x\", \"--keep_temp\", action=\"store_true\",\n help=\"Keep temporary folder after execution.\")\n parser.add_argument(\"--visual\", action=\"store_true\",\n help=\"shows a visual representation of the tracking progress.\")\n\n # parse arguments from command line\n args = parser.parse_args()\n # get all file names and directories ready\n out_dir, temp_dir, video_bases, videos = housekeeping(args)\n borders = []\n for i in range(len(videos)):\n v = videos[i]\n get_borders(borders, temp_dir, v)\n\n for i in range(len(videos)):\n vbn = video_bases[i]\n v = videos[i]\n scaled_video = \"scaled_\" + vbn + \".avi\"\n ffmpeg = Ffmpeg(v, os.path.join(temp_dir, scaled_video))\n ffmpeg.f = \"avi\"\n ffmpeg.vcodec = \"libx264rgb\"\n ffmpeg.width = 480\n ffmpeg.run()\n\n for i in range(len(videos)):\n vbn = video_bases[i]\n pts = tracker(args, temp_dir, vbn)\n border = borders[i]\n tracks_lower, tracks_upper = split_tracks(border, pts)\n analysis = Analysis(tracks_lower, tracks_upper, px_size=0.06)\n analysis.analyze(os.path.join(out_dir, 'stats.txt'), vbn, vel=True)\n\n if not args.keep_temp:\n shutil.rmtree(temp_dir)", "def run(self, vid_input_path='project_video.mp4'):\n vid_output_path = self.g.output_movie_path + vid_input_path\n print('Finding lanes for:', vid_input_path) \n\n # Load the Video\n # video_clip = VideoFileClip(video_filename).subclip(10, 11)\n clip1 = VideoFileClip(vid_input_path)\n\n # Feed the video, clip by clip into the pipeline.\n test_clip = clip1.fl_image(self.__image_pipeline) \n test_clip.write_videofile(vid_output_path, audio=False)\n\n return True", "def run(config_path, pipeline_config_path=None):\n clip_config = ModuleConfig.from_json(config_path)\n etam.setup(clip_config, pipeline_config_path=pipeline_config_path)\n _clip_videos(clip_config)", "def process_video(input_file, output_file):\n # video = VideoFileClip(input_file).subclip(40,44) # from 38s to 46s\n video = VideoFileClip(input_file)\n annotated_video = video.fl_image(process_pipeline)\n annotated_video.write_videofile(output_file, audio=False)", "def process_video(input_file, output_file):\n # video = VideoFileClip(input_file).subclip(40,44) # from 38s to 46s\n video = VideoFileClip(input_file)\n annotated_video = video.fl_image(process_pipeline)\n annotated_video.write_videofile(output_file, audio=False)", "def main(path):\n video_client = (video_intelligence_service_client.\n VideoIntelligenceServiceClient())\n features = [enums.Feature.LABEL_DETECTION]\n video_context = video_intelligence_pb2.VideoContext()\n video_context.stationary_camera = True\n video_context.label_detection_mode = video_intelligence_pb2.FRAME_MODE\n operation = video_client.annotate_video(path, features, video_context=video_context)\n print('\\nProcessing video for label annotations:')\n\n while not operation.done():\n sys.stdout.write('.')\n sys.stdout.flush()\n time.sleep(10)\n\n print('\\nFinished processing.')\n\n results = operation.result().annotation_results[0]\n\n return(results)", "def execute_pipeline(userId, srcDir, srcName, isShinobi):\n # print(f'{userId} - {srcDir} - {srcName}')\n videoSrc = srcDir + '/' + srcName \n metaDataDict = extract_metadata(videoSrc)\n\n video_id = write_metadata(\n userId, \n srcName,\n metaDataDict[\"width\"], \n metaDataDict[\"height\"], \n metaDataDict[\"fps\"], \n metaDataDict[\"numframes\"]\n )\n \n # Splitting up \n print(\"***************** Splitting up... *****************\")\n call([\n movieToFrames, \n videoSrc, \n str(metaDataDict[\"fps\"]), \n srcDir + \"\"\"/frames%d.png\"\"\"\n ])\n \n # Processing\n shapePoints = []\n pupilPoints = []\n skullPoints = []\n print(\"Starting landmark detection...\")\n print(\"***************** Starting landmark detection... *****************\")\n for i in range(1, metaDataDict[\"numframes\"] + 1):\n imgPath = srcDir + \"/frames\" + str(i) + \".png\"\n imgDest = srcDir + \"/landmark\" + str(i) + \".png\"\n tempDict = detectLandmarks(imgPath, imgDest, isShinobi)\n shapePoints.append(tempDict[\"shape\"])\n pupilPoints.append(tempDict[\"pupils\"])\n skullPoints.append(tempDict[\"rotation\"])\n \n # Merging\n print(\"***************** Starting stiching up... *****************\")\n call([\n framesToMovie, \n str(metaDataDict[\"fps\"]), \n str(metaDataDict[\"width\"]) + \"x\" + str(metaDataDict[\"height\"]), \n str(metaDataDict[\"numframes\"]),\n srcDir + \"\"\"/landmark%d.png\"\"\", \n srcDir + \"/\" + str(userId) + '_' + srcName\n ])\n \n write_pupils(video_id, pupilPoints)\n write_landmarks(video_id, shapePoints)\n write_skull(video_id, skullPoints)\n\n with open(srcDir + \"/\" + str(userId) + '_' + srcName + '.json', 'w') as cache: \n metaDataDict[\"video_id\"] = video_id\n json.dump(metaDataDict, cache)", "def run(self):\n\n # Start the video stream process\n self._process.start()", "def main():\n\n parser = ArgumentParser()\n parser.add_argument('--config', '-c', type=str, required=True, help='Path to config file')\n parser.add_argument('--input', '-i', type=str, required=True, help='Path to video')\n parser.add_argument('--snapshot_path', '-s', type=str, required=False, default='', help='Path to snapshot')\n parser.add_argument('--out_scale', type=float, default=1.0, help='Output frame scale')\n parser.add_argument('--deploy', '-d', action='store_true', help='Execute in deploy mode')\n args = parser.parse_args()\n\n assert exists(args.config)\n assert exists(args.input)\n assert exists(args.snapshot_path + '.index')\n assert args.out_scale > 0.0\n\n task_monitor = get_monitor(args.config, snapshot_path=args.snapshot_path)\n task_monitor.demo(args.input, args.out_scale, args.deploy)", "def action(args):\n innput = args.image if args.image else args.video\n\n assert innput is not None, \"Image/Video is none\"\n assert os.path.exists(innput), 'Image/Video doesnt exist'\n assert os.path.isfile(innput), 'Image/Video cant be a folder'\n\n print(\"Starting detection ...\")\n proc_video(innput, None, 0, process_image, window_name=innput)", "def find_cars_video(input_path, output_path, clf, hyperparams, box_color=None, debug=False):\n v = VideoProcessor(clf, hyperparams, box_color)\n v.process_video(input_path, output_path, debug)", "def main():\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"-hgt\", \"--imgHeight\", help=\"The height of the images, default=720.\",\n type=int, default=720)\n\n parser.add_argument(\"-wd\", \"--imgWidth\", help=\"The width of the images, default=1280.\",\n type=int, default=1280)\n\n parser.add_argument(\"-r\", \"--chessboardRows\", help=\"The rows of the chessboard calibration images, default=6.\",\n type=int, default=6)\n\n parser.add_argument(\"-c\", \"--chessboardCols\", help=\"The cols of the chessboard calibration images, default=9.\",\n type=int, default=9)\n\n parser.add_argument(\"-cp\", \"--calibrationPath\", help=\"The height of the images, default=720.\",\n type=str, default='')\n\n parser.add_argument(\"-in\", \"--inputVideoPath\", help=\"The path to the input video to be processed.\",\n type=str, default='')\n\n parser.add_argument(\"-out\", \"--outputVideoPath\", help=\"The path to the where to store output video.\",\n type=str, default='')\n\n args = parser.parse_args()\n\n print(args)\n\n assert args.calibrationPath != '', \"The path to calibration images can't be empty\"\n assert args.inputVideoPath != '', \"The path to input video can't be empty\"\n assert args.outputVideoPath != '', \"The path to output video can't be empty\"\n\n camera_mtx, dist_coeff = CameraCalibration((args.imgHeight, args.imgWidth),\n (args.chessboardRows, args.chessboardCols),\n args.calibrationPath).calibrate()\n print(\"Camera Mtx\", camera_mtx)\n print(\"Distortion Coefficient\", dist_coeff)\n # img = cv2.imread('test_images/test5.jpg')\n # img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n AdvancedLaneDetection(args.inputVideoPath, camera_mtx, dist_coeff).process_video(args.outputVideoPath)\n\n # cv2.imwrite(\"output.jpg\", result)", "def main():\n # Parameters\n opt = get_args()\n\n assert os.path.exists(opt.path_video), \"Video file does not exist\"\n try:\n os.makedirs(opt.path_images)\n except Exception:\n print(\"Folder already exists. Overwriting it\")\n pass\n\n assert opt.size is None or opt.size is not None and len(opt.size) <= 2, \"Make sure the size indicated contains at maximum two numbers [none, max_dimension or width and height]\"\n\n # Get base path\n base_path = os.path.join(opt.path_images, opt.basename)\n\n # Load video from file\n try:\n cap = cv2.VideoCapture(opt.path_video)\n except Exception as e:\n print('Video failed to be loaded:', e)\n sys.exit(0)\n\n # Parse video\n parse_video(cap, base_path, opt.step, opt.size)\n\n # Release capture\n cap.release()\n cv2.destroyAllWindows()\n \n return 0", "def detect_from_video(config: Dict):\n video = config['inference']['video_input']['video_input_path']\n vp = VideoProcessing(video=video)\n vp.generate_frames(export_path=config['inference']['video_input']['video_to_frames_export_path'])\n if config['inference']['video_input']['video_to_frames_export_path'] == config['inference']['predicted_frames_export_path']:\n print(\"[Warning]... You have given Video to frame path same as prediction output path /nPredicted output will overwrite video to frame\")\n img_height = config['inference']['img_height']\n img_width = config['inference']['img_width']\n model = ssd_300(image_size=(img_height, img_width, 3),\n n_classes=config['inference']['n_classes'],\n mode='inference',\n l2_regularization=0.0005,\n scales=[0.1, 0.2, 0.37, 0.54, 0.71, 0.88, 1.05], # The scales for MS COCO are [0.07, 0.15, 0.33, 0.51, 0.69, 0.87, 1.05]\n aspect_ratios_per_layer=[[1.0, 2.0, 0.5],\n [1.0, 2.0, 0.5, 3.0, 1.0/3.0],\n [1.0, 2.0, 0.5, 3.0, 1.0/3.0],\n [1.0, 2.0, 0.5, 3.0, 1.0/3.0],\n [1.0, 2.0, 0.5],\n [1.0, 2.0, 0.5]],\n two_boxes_for_ar1=True,\n steps=[8, 16, 32, 64, 100, 300],\n offsets=[0.5, 0.5, 0.5, 0.5, 0.5, 0.5],\n clip_boxes=False,\n variances=[0.1, 0.1, 0.2, 0.2],\n normalize_coords=True,\n subtract_mean=[123, 117, 104],\n swap_channels=[2, 1, 0],\n confidence_thresh=0.5,\n iou_threshold=0.45,\n top_k=200,\n nms_max_output_size=400)\n\n # Load the trained weights into the model.\n weights_path = config['inference']['weights_path']\n\n model.load_weights(weights_path, by_name=True)\n \n # Working with image\n all_images = glob.glob(f\"{config['inference']['video_input']['video_to_frames_export_path']}/*/*\")\n \n # Setting Up Prediction Threshold\n confidence_threshold = config['inference']['confidence_threshold']\n \n # Setting Up Classes (Note Should be in same order as in training)\n classes = config['inference']['classes']\n \n vp.existsFolder(f\"{config['inference']['predicted_frames_export_path']}/{video.split('.')[0]}\")\n # Working with image\n for current_img in tqdm(all_images):\n current_img_name = current_img.split('/')[-1]\n orig_image = cv2.imread(current_img)\n input_images = [] # Store resized versions of the images here\n img = image.load_img(current_img, target_size=(img_height, img_width))\n img = image.img_to_array(img) \n input_images.append(img)\n input_images = np.array(input_images)\n \n # Prediction\n y_pred = model.predict(input_images)\n\n # Using threshold\n y_pred_thresh = [y_pred[k][y_pred[k,:,1] > confidence_threshold] for k in range(y_pred.shape[0])]\n \n # Drawing Boxes\n for box in y_pred_thresh[0]:\n xmin = box[2] * orig_image.shape[1] / img_width\n ymin = box[3] * orig_image.shape[0] / img_height\n xmax = box[4] * orig_image.shape[1] / img_width\n ymax = box[5] * orig_image.shape[0] / img_height\n \n label = f\"{classes[int(box[0])]}: {box[1]:.2f}\"\n cv2.rectangle(orig_image, (int(xmin), int(ymin)), (int(xmax),int(ymax)), (255, 0, 0), 2)\n cv2.putText(orig_image, label, (int(xmin), int(ymin)), cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 255, 255), 2, cv2.LINE_AA)\n cv2.imwrite(f\"{config['inference']['predicted_frames_export_path']}/{video.split('.')[0]}/{current_img_name}\", orig_image)\n \n # Creating video\n vp.generate_video(import_path=config['inference']['predicted_frames_export_path'],\n export_path=config['inference']['video_input']['video_output_path'])", "def video_files():\n p = parse_cmdline(get_parser=get_parser_files)\n log.setup_main_handler(\n mods=(\"fogtools\", \"typhon\", \"fogpy\", \"sattools\", \"fcitools\", \"satpy\",\n \"pyresample\"),\n level=logging.INFO)\n vis.show_video_abi_glm(\n files=p.files,\n img_out=p.filename_pattern_image,\n vid_out=p.filename_pattern_video,\n out_dir=p.outdir)\n print(\"Files written to:\", p.outdir)", "def process_video(lane, fname, output):\n\tclip = VideoFileClip(fname)\n\toutput_name = output\n\toutput_clip = clip.fl_image(lane.pipeline)\n\toutput_clip.write_videofile(output_name, audio=False)\n\tprint ('Video processed successfully')", "def main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--visualize', dest='visualize_dir', help=\"Path to directory to load all vizualization info from\")\n parser.add_argument('--overwrite', dest='overwrite', default=False, action='store_true', help=\"Overwrite existing logs parts if found\")\n args = parser.parse_args()\n if not args.visualize_dir:\n print \"Missing required argument, --visualize\"\n exit(-1)\n\n dsrc_log_file = args.visualize_dir + '/dsrc.log'\n radar_log_file = args.visualize_dir + '/radar.log'\n video_file = args.visualize_dir + '/video.mp4'\n log_config = args.visualize_dir + '/config.json'\n\n config = parse_config(log_config)\n\n if 'parts_auto_enabled' in config and config['parts_auto_enabled']:\n cap = cv2.VideoCapture(video_file)\n fps = cap.get(cv2.CAP_PROP_FPS)\n frames = cap.get(cv2.CAP_PROP_FRAME_COUNT)\n duration = float(frames) / fps\n cap.release()\n\n print 'Video duration: %s' % duration\n start = 0\n count = 1\n while start < duration:\n config['parts'].append({\n 'start': start,\n 'end': start + config['parts_auto_interval'],\n 'name': 'auto_part_%s' % count\n })\n count = count + 1\n start = start + config['parts_auto_interval']\n\n print config \n\n for index, part in enumerate(config['parts']):\n part_path = args.visualize_dir + '/' + (part['name'] if 'name' in part else 'part_%s' % (index+1))\n print \"---------------------------------------\"\n print \" Writing log to %s\" % part_path\n print \"---------------------------------------\"\n if not args.overwrite and os.path.exists(part_path):\n print \"Log already exists, skipping...\"\n continue\n\n if not os.path.exists(part_path):\n os.makedirs(part_path)\n\n export_part_video(part, part_path, video_file)\n export_part_log(part, part_path + '/radar.log', radar_log_file, config['video_start'])\n export_part_log(part, part_path + '/dsrc.log', dsrc_log_file, config['video_start'])\n export_part_config(part_path + '/config.json', config)", "def create_video(input_file, output_file):\n input_video = VideoFileClip(input_file)\n output_video = input_video.fl_image(detect_lane.fit_and_plot)\n output_video.write_videofile(output_file, audio=False)", "def main(base_dir: str, output_dir: str) -> None:\n base_path = pathlib.Path(base_dir)\n output_path = pathlib.Path(output_dir).expanduser()\n\n stage_copy_images(base_path, output_path)\n stage_extract_videos(base_path, output_path)", "def remote_video(**kwargs):\n # SSH into the Raspberry Pi\n logging.info(\"Conneting to the Raspberry Pi\")\n ssh_client = connect_to_client()\n\n # Check the inputs\n if kwargs[\"output_filename\"] is None:\n # TODO: Add nice error classes instead of raising exceptions\n raise Exception(\"Missing an output filename\")\n if kwargs[\"destination_filepath\"] is None and not kwargs[\"database\"]:\n raise Exception(\"Missing the filepath to the data destination on local machine\")\n\n # Add \"matrix_decomposition\" to the end of the file if necessary\n if kwargs[\"preprocess_analysis\"] == \"MD\":\n kwargs[\"output_filename\"] = \"_\".join([kwargs[\"output_filename\"], \"matrix_decomposition\"])\n \n if kwargs[\"database\"]:\n database = True\n else:\n database = False\n\n # Create the name of the remote output location\n remote_output_file = os.path.join(\n \"/home/pi/Desktop\",\n kwargs[\"output_filename\"] + \".h264\"\n )\n \n # TODO: Check if the file already exists and delete it if it does\n\n # Record the video on the pi\n video_length = int(kwargs[\"video_length\"])\n cmd = f\"python3 /home/pi/Desktop/capstone/software/data_stream/rpi_camera_collect.py {remote_output_file} --video_length {video_length}\"\n logging.info(\"Launching remote data collection on Raspberry Pi\")\n stdin, stdout, stderr = ssh_client.exec_command(cmd)\n exit_status = stdout.channel.recv_exit_status() \n\n # Check the command exited successfully\n if exit_status != 0:\n logging.error(stderr.read())\n # TODO: Nice error class here\n raise Exception()\n \n # Remotely run preprocess on the data collected by the Raspberry Pi\n output_dir, batch_ids = run_video_preprocess(\n video_file=remote_output_file, \n roi_locations=kwargs[\"roi_locations\"],\n preprocess_analysis=kwargs[\"preprocess_analysis\"],\n ssh_client=ssh_client,\n database=database,\n )\n\n if not kwargs[\"database\"]:\n base_local_output_filepath = kwargs[\"destination_filepath\"]\n local_output_filepath = os.path.join(\n kwargs[\"destination_filepath\"], \n kwargs[\"output_filename\"]\n )\n # TODO: Check if output file already exists on local and delete if it does\n logging.info(\"Copying video file to local machine\")\n # Make the local directory\n if not os.path.exists(base_local_output_filepath):\n os.makedirs(base_local_output_filepath)\n\n # Rsync the file from the Raspberry Pi to the local\n cmd = f\"rsync -avPL pi@{PI_IP}:{output_dir} {base_local_output_filepath}\"\n subprocess.check_call(cmd, shell=True)\n # TODO: Check the files were copied correctly (checksum/filesize) before closing the SSH client\n ssh_client.close()\n else:\n local_output_filepath = None\n\n # Run the analysis pipeline\n # TODO: Batch ID not required here? change in run_pipeline.py\n run_analysis_pipeline(\n preprocess_analysis=kwargs[\"preprocess_analysis\"],\n json_filepath=local_output_filepath,\n )", "def run_detection(params):\n # make a defaultdict out of @parameters so that we could always access its first-level keys\n params_default_first_level = defaultdict(dict)\n params_default_first_level.update(params)\n params = params_default_first_level\n\n verbose = params['GeneralArguments'].get('verbose', False)\n\n out_folder = params['GeneralArguments'].get('output_folder')\n if out_folder is None:\n out_folder = tempfile.mkdtemp(prefix='sp_tool_')\n warnings.warn('No output folder provided, using {}'.format(out_folder))\n if verbose:\n print >> sys.stderr, 'Outputs will be written to folder', out_folder\n\n saccade_detector = SaccadeDetector(**params['SaccadeDetector'])\n blink_detector = BlinkDetector(**params['BlinkDetector'])\n fixation_detector = FixationDetector(**params['FixationDetector'])\n\n recording_processor = RecordingProcessor(saccade_detector=saccade_detector,\n blink_detector=blink_detector,\n fixation_detector=fixation_detector)\n\n sp_detector = SmoothPursuitDetector(**params['SmoothPursuitDetector'])\n\n # The next lines deal with identifying the names of the video clips used for the eye tracking experiment.\n # Can be initialized in various ways, here we just get all video paths be regex and cut off everything that\n # is not needed.\n #\n #\n in_folder = params['GeneralArguments'].get('input_folder')\n if not in_folder:\n raise ValueError('\\'input_folder\\' is a required parameter of the \\'GeneralArguments\\' group in @params!')\n folder_names = sorted(glob.glob('{}/*/'.format(in_folder))) # getting all the folders of the input folder\n # extract names from path\n if not folder_names and verbose:\n print >> sys.stderr, 'No subfolders found under \"{}\"'.format(in_folder)\n folder_names = [os.path.splitext(os.path.basename(folder.rstrip('/')))[0] for folder in folder_names]\n\n movies = params['GeneralArguments'].get('movies')\n if movies: # not empty, restrict to these folders only\n movies = set(movies)\n folder_names = [fn for fn in folder_names if fn in movies]\n\n if verbose:\n print >> sys.stderr, 'Working with movies:', folder_names\n\n # data files extension\n gaze_pattern = params['GeneralArguments'].get('gaze_file_pattern', '*.coord')\n if '*' not in gaze_pattern:\n gaze_pattern = '*' + gaze_pattern\n\n for movie in folder_names:\n full_out_folder = '{}/{}/'.format(out_folder, movie)\n if not os.path.exists(full_out_folder):\n os.makedirs(full_out_folder)\n if verbose:\n print >> sys.stderr, 'Started processing for {},'.format(movie), 'results will appear in', full_out_folder\n\n # The next lines load the data files of the recording with one particular movie.\n # To do this, here we provide a regex that includes all the .{extension} files in the respective folder.\n #\n #\n gaze_data_files = sorted(glob.glob('{}/{}/{}'.format(in_folder, movie, gaze_pattern)))\n if len(gaze_data_files) == 0:\n print >> sys.stderr, 'Found 0 files with this pattern: \"{}\". Omitting this directory.'.format(\n '{}/{}/{}'.format(in_folder, movie, gaze_pattern)\n )\n continue\n try:\n # The next line loads the data, labels saccades, blinks and fixations.\n gaze_points_list = recording_processor.load_multiple_recordings(\n gaze_data_files, verbose=verbose, data_format=params['GeneralArguments'].get('input_data_type'))\n # This will label the smooth pursuits\n if verbose:\n print >> sys.stderr, 'Saccades/blinks/fixations are detected, starting SP detection.'\n classified_gaze_points = sp_detector.detect(gaze_points_list)\n\n # Now just dump the resulting structure into .arff files in the respective subdirectory of the @out_folder\n for file_name, arff_data in zip(gaze_data_files, classified_gaze_points):\n output_file_name = os.path.splitext(os.path.basename(file_name))[0]\n ArffHelper.dump(arff_data, open(\n '{}/{}.arff'.format(full_out_folder, output_file_name), 'w')).close()\n except Exception as e:\n print >> sys.stderr, 'Had to skip {} due to an error \"{}\"'.format(movie, e.message)\n return out_folder", "def run():\n logger.info(f\"Process started:\")\n logger.info(f\"Converting Glove file to Word2Vec format\")\n convert_to_word2vec.convert(\n \"./data/source/glove.6B.50d.txt\", \"./data/source/glove.6B.50d.w2vformat.txt\"\n )\n\n logger.info(f\"Extracting Click Stream data\")\n extract_click_stream_data()\n\n logger.info(\"Extracting Wiki articles\")\n extract_wiki_articles()\n\n logger.info(f\"Generating Clickstream dataset\")\n generate_datasets()\n\n logger.info(\"Tokenizing articles\")\n WikiArticlesTokenizer().process()\n\n logger.info(\"Creating dataset with Wiki Articles\")\n create_wiki_articles_dataset()", "def detect(self):\n # process the input video and get the attributes:\n self.process_video()\n\n # build a rcnn/ yolov5 predictor:\n self.build_predictor()\n\n \n # assert not os.path.isfile(args.output_file), \"File with the name %s already exists\"%args.output_file\n # build the writer with same attributes:\n self.vid_writer = cv2.VideoWriter(self.output, self.fourcc, self.fps, (self.w, self.h))\n\n # inference time:\n start = time.time()\n print(\"Started inference\\n\")\n \n # progress bar using tqdm:\n pbar = tqdm(total=self.nframes)\n\n while(self.cap.isOpened()):\n ret, frame = self.cap.read()\n if ret == False:\n break # when the last frame is read \n\n # different formats of results:\n if self.library == \"yolov5\":\n # predict and bring the outputs to cpu:\n results = self.predictor(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)) # convert to RGB\n predictions = results.xyxy[0].cpu()\n # find the instance indices with person:\n person_idx = predictions[:,5] == self.label_dict[\"person\"]\n # extract the corresponding boxes and scores:\n boxes = predictions[person_idx,:4].numpy()\n probs = predictions[person_idx,4].numpy()\n\n if self.library == \"detectron2\":\n # predict and bring the outputs to cpu:\n results = self.predictor(frame) # RGB conversion done automatically in detectron\n predictions = results[\"instances\"].to(\"cpu\")\n # find the instance indices with person:\n person_idx = [predictions.pred_classes == self.label_dict[\"person\"]]\n # extract the corresponding boxes and scores:\n boxes = predictions.pred_boxes[person_idx].tensor.numpy()\n probs = predictions.scores[person_idx].numpy()\n\n # draw boxes and write the frame to the video:\n if len(boxes): # check whether there are predictions\n box_frame = self.draw_person_boxes(frame, boxes, probs)\n else:\n box_frame = frame\n self.vid_writer.write(box_frame)\n\n pbar.update(1)\n pbar.close()\n\n # release the video capture object and write object:\n self.cap.release()\n self.vid_writer.release()\n\n print(\"Inferene on the video file took %0.3f seconds\"%(time.time()-start))", "def analyze_video(file, name, api):\n args = Namespace(video=file, name=name, input_data=None, api=True)\n scene_content = scenescoop(args)\n content = ''\n maxframes = 0\n for description in scene_content:\n if(len(scene_content[description]) > maxframes):\n content = description\n maxframes = len(scene_content[description]) \n \n if(api):\n return jsonify(status=\"200\", scene_content=scene_content, content=content, maxframes=maxframes)\n else:\n return content", "def main():\n print(\"This is a library for reading video sequences into python via ffmpeg. \")\n print(\"Provides the 'Video_Reader' iterator class. \")\n print(\"Requires ffmpeg be installed. \")", "def main():\n cv2.namedWindow('video', cv2.WINDOW_AUTOSIZE)\n\n cap = cv2.VideoCapture(sys.argv[1])\n while cap.isOpened():\n ret, frame = cap.read()\n if not ret: # done\n break\n\n cv2.imshow('video', frame)\n\n key = cv2.waitKey(30)\n if key & 0xFF == ord('q'): # quit\n break\n\n cap.release()\n cv2.destroyAllWindows()", "def run(model: str, label: str, max_results: int, num_threads: int,\n camera_id: int, width: int, height: int) -> None:\n # Initialize the video classification model\n options = VideoClassifierOptions(\n num_threads=num_threads, max_results=max_results)\n classifier = VideoClassifier(model, label, options)\n\n # Variables to calculate FPS\n counter, fps, last_inference_start_time, time_per_infer = 0, 0, 0, 0\n categories = []\n\n # Start capturing video input from the camera\n cap = cv2.VideoCapture(camera_id)\n cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)\n cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)\n\n # Continuously capture images from the camera and run inference\n while cap.isOpened():\n success, image = cap.read()\n if not success:\n sys.exit(\n 'ERROR: Unable to read from webcam. Please verify your webcam settings.'\n )\n counter += 1\n\n # Mirror the image\n image = cv2.flip(image, 1)\n\n # Ensure that frames are feed to the model at {_MODEL_FPS} frames per second\n # as required in the model specs.\n current_frame_start_time = time.time()\n diff = current_frame_start_time - last_inference_start_time\n if diff * _MODEL_FPS >= (1 - _MODEL_FPS_ERROR_RANGE):\n # Store the time when inference starts.\n last_inference_start_time = current_frame_start_time\n\n # Calculate the inference FPS\n fps = 1.0 / diff\n\n # Convert the frame to RGB as required by the TFLite model.\n frame_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\n # Feed the frame to the video classification model.\n categories = classifier.classify(frame_rgb)\n\n # Calculate time required per inference.\n time_per_infer = time.time() - current_frame_start_time\n\n # Notes: Frames that aren't fed to the model are still displayed to make the\n # video look smooth. We'll show classification results from the latest\n # classification run on the screen.\n # Show the FPS .\n fps_text = 'Current FPS = {0:.1f}. Expect: {1}'.format(fps, _MODEL_FPS)\n text_location = (_LEFT_MARGIN, _ROW_SIZE)\n cv2.putText(image, fps_text, text_location, cv2.FONT_HERSHEY_PLAIN,\n _FONT_SIZE, _TEXT_COLOR, _FONT_THICKNESS)\n\n # Show the time per inference.\n time_per_infer_text = 'Time per inference: {0}ms'.format(\n int(time_per_infer * 1000))\n text_location = (_LEFT_MARGIN, _ROW_SIZE * 2)\n cv2.putText(image, time_per_infer_text, text_location,\n cv2.FONT_HERSHEY_PLAIN, _FONT_SIZE, _TEXT_COLOR,\n _FONT_THICKNESS)\n\n # Show classification results on the image.\n for idx, category in enumerate(categories):\n class_name = category.label\n probability = round(category.score, 2)\n result_text = class_name + ' (' + str(probability) + ')'\n # Skip the first 2 lines occupied by the fps and time per inference.\n text_location = (_LEFT_MARGIN, (idx + 3) * _ROW_SIZE)\n cv2.putText(image, result_text, text_location, cv2.FONT_HERSHEY_PLAIN,\n _FONT_SIZE, _TEXT_COLOR, _FONT_THICKNESS)\n\n # Stop the program if the ESC key is pressed.\n if cv2.waitKey(1) == 27:\n break\n cv2.imshow('video_classification', image)\n\n cap.release()\n cv2.destroyAllWindows()", "def execute_live(args):\n logger.debug('Starting analysis...')\n # create the working directory\n setup()\n # create a layer object to bundle package metadata into\n layer = ImageLayer(\"\")\n # see if there is an os-release file at the mount point\n layer.os_guess = single_layer.find_os_release(args.live)\n # create a Prereqs object to store requirements to inventory\n prereqs = core.Prereqs()\n prereqs.host_path = os.path.abspath(args.live)\n # Find a shell that may exist in the layer\n prereqs.fs_shell = dcom.find_shell(prereqs.host_path)\n # Find the host's shell\n prereqs.host_shell = host.check_shell()\n # collect metadata into the layer object\n fill_packages(layer, prereqs)\n # report out the packages\n report.report_layer(layer, args)", "def demo_video(net, im,frame_number,args, output_folder, conf_thresh):\n \n #data_dir = '/mnt/nfs/scratch1/souyoungjin/RESULTS_FACE_DETECTIONS/ARUNI/video'+str(args.video_id)\n #out_dir = '/mnt/nfs/scratch1/ashishsingh/RESULTS_DOG_DETECTIONS/ARUNI/OHEM/'+args.video_folder_name\n \n out_dir = join(output_folder, args.video_id)\n\n if not os.path.exists(out_dir):\n os.makedirs(out_dir)\n\n\n timer = Timer()\n timer.tic()\n scores, boxes = im_detect(net, im)\n timer.toc()\n print ('Detection took {:.3f}s for '\n '{:d} object proposals').format(timer.total_time, boxes.shape[0])\n\n # Visualize detections for each class\n #CONF_THRESH = 0.80 #check threshold values\n CONF_THRESH = conf_thresh\n NMS_THRESH = 0.15 #check threshold values\n \n # detection file\n dets_file_name = os.path.join(out_dir, 'video'+str(args.video_id)+'.txt') \n fid = open(dets_file_name, 'a+')\n sys.stdout.write('%s ' % (frame_number))\n \n cls_ind = 1\n cls_boxes = boxes[:, 4*cls_ind:4*(cls_ind + 1)]\n cls_scores = scores[:, cls_ind]\n dets = np.hstack((cls_boxes,cls_scores[:, np.newaxis])).astype(np.float32)\n keep = nms(dets, NMS_THRESH)\n dets = dets[keep, :]\n\n keep = np.where(dets[:, 4] > CONF_THRESH)\n dets = dets[keep]\n \n dets[:, 2] = dets[:, 2] - dets[:, 0] + 1\n dets[:, 3] = dets[:, 3] - dets[:, 1] + 1\n \n fid.write('FRAME NUMBER: '+ str(frame_number) + '\\n')\n fid.write(str(dets.shape[0]) + '\\n')\n for j in xrange(dets.shape[0]):\n fid.write('%f %f %f %f %f\\n' % (dets[j, 0], dets[j, 1], dets[j, 2], dets[j, 3], dets[j, 4]))\n\n print ''\n fid.close()\n \n #for cls_ind, cls in enumerate(CLASSES[1:]):\n #cls_ind += 1 # because we skipped background\n #cls_boxes = boxes[:, 4*cls_ind:4*(cls_ind + 1)]\n\n #cls_scores = scores[:, cls_ind]\n #dets = np.hstack((cls_boxes,cls_scores[:, np.newaxis])).astype(np.float32)\n #keep = nms(dets, NMS_THRESH)\n #dets = dets[keep, :]\n #im=vis_detections_video(im, cls, dets, thresh=CONF_THRESH)\n #cv2.imwrite(os.path.join('output',str(time.time())+'.jpg'),im)\n \n \n #cv2.imshow('ret',im)\n #cv2.waitKey(20)" ]
[ "0.7059301", "0.70090806", "0.6889676", "0.6699481", "0.63987863", "0.63987863", "0.63744324", "0.6357981", "0.63418233", "0.6324679", "0.63238215", "0.6317075", "0.6313249", "0.6285913", "0.6272834", "0.6231296", "0.6174944", "0.6139632", "0.61304486", "0.6111183", "0.61073726", "0.6084779", "0.6079142", "0.6073256", "0.60165155", "0.6007529", "0.59947526", "0.59558135", "0.5915498", "0.59145975" ]
0.76880926
0
test a random image for the correct amount of gray pixels
def test_aperture(self, identifier, image_id, expected_amount_gray, ratio_gray): assembly = brainio.get_assembly(identifier) stimulus_set = assembly.stimulus_set image_path = Path(stimulus_set.get_image(image_id)) assert image_path.is_file() # count number of gray pixels in image image = Image.open(image_path) image = np.array(image) amount_gray = 0 for index in np.ndindex(image.shape[:2]): color = image[index] gray = [128, 128, 128] if (color == gray).all(): amount_gray += 1 assert amount_gray / image.size == approx(ratio_gray, abs=.0001) assert amount_gray == expected_amount_gray
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def random_img_to_gray(self, img, p = 0.5):\n if self.decision(p):\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n img = np.zeros_like(img)\n img[:, :, 0] = gray\n img[:, :, 1] = gray\n img[:, :, 2] = gray\n return img", "def randomize_pixels(image):\n shape_ = image.size()\n image_flat = image.view(-1, image.size(-1))\n shuffled_image = shuffle(image_flat)\n return shuffled_image.view(shape_)", "def test_image(filename, x_size=350, y_size=350):\n # Create image and loop over all pixels\n im = Image.new(\"RGB\", (x_size, y_size))\n pixels = im.load()\n for i in range(x_size):\n for j in range(y_size):\n pixels[i, j] = (random.randint(0, 255), # Red channel\n random.randint(0, 255), # Green channel\n random.randint(0, 255)) # Blue channel\n im.save(filename)\n return 'saved'", "def chooseRandPixel(mask):\n array = np.transpose(np.nonzero(mask)) # Get the indices of nonzero elements of mask.\n index = random.randint(0,len(array)-1) # Select a random index\n return array[index]", "def test_rand(self):\n assert len(self._mnist.random()[:5]) == 5\n pass", "def create_image(path, pxcount):\n img = Image.open(path, 'r').convert('L')\n pixels = img.load()\n for i in range(pxcount):\n x = randint(0, img.size[0]-1)\n y = randint(0, img.size[0]-1)\n if pixels[x, y] == 0:\n pixels[x, y] = 255\n else:\n pixels[x, y] = 0\n return img", "def test_image(filename, x_size=def_x_size, y_size=def_y_size):\n # Create image and loop over all pixels\n im = Image.new(\"RGB\", (x_size, y_size))\n pixels = im.load()\n for i in range(x_size):\n for j in range(y_size):\n x = remap_interval(i, 0, x_size, -1, 1)\n y = remap_interval(j, 0, y_size, -1, 1)\n pixels[i, j] = (random.randint(0, 255), # Red channel\n random.randint(0, 255), # Green channel\n random.randint(0, 255)) # Blue channel\n im.save(filename)", "def test_image(filename, x_size=350, y_size=350):\n # Create image and loop over all pixels\n im = Image.new(\"RGB\", (x_size, y_size))\n pixels = im.load()\n for i in range(x_size):\n for j in range(y_size):\n x = remap(i, 0, x_size, -1, 1)\n y = remap(j, 0, y_size, -1, 1)\n pixels[i, j] = (random.randint(0, 255), # Red channel\n random.randint(0, 255), # Green channel\n random.randint(0, 255)) # Blue channel\n\n im.save(filename)", "def main():\n\n os.system(\"rm -rf images; mkdir images\")\n\n if (len(sys.argv) > 1):\n N = int(sys.argv[1])\n else:\n N = 10\n\n x_test = np.load(\"../../../../data/mnist/mnist_test_images.npy\")\n\n for i in range(N):\n r,c = random.randint(6,12), random.randint(6,12)\n g = np.zeros(r*c)\n for j in range(r*c):\n if (random.random() < 0.15):\n g[j] = 1\n g = g.reshape((r,c))\n g[:,0] = g[0,:] = g[:,-1] = g[-1,:] = 0\n\n img = np.zeros((28*r,28*c), dtype=\"uint8\")\n for x in range(r):\n for y in range(c):\n if (g[x,y] == 1):\n n = random.randint(0, x_test.shape[0])\n im = x_test[n]\n img[28*x:(28*x+28), 28*y:(28*y+28)] = im\n \n Image.fromarray(img).save(\"images/image_%04d.png\" % i)", "def test_image(filename, x_size=350, y_size=350):\n # Create image and loop over all pixels\n im = Image.new(\"RGB\", (x_size, y_size))\n pixels = im.load()\n for i in range(x_size):\n for j in range(y_size):\n x = remap_interval(i, 0, x_size, -1, 1)\n y = remap_interval(j, 0, y_size, -1, 1)\n pixels[i, j] = (random.randint(0, 255), # Red channel\n random.randint(0, 255), # Green channel\n random.randint(0, 255)) # Blue channel\n\n im.save(filename)", "def test_image(filename, x_size=350, y_size=350):\n # Create image and loop over all pixels\n im = Image.new(\"RGB\", (x_size, y_size))\n pixels = im.load()\n for i in range(x_size):\n for j in range(y_size):\n x = remap_interval(i, 0, x_size, -1, 1)\n y = remap_interval(j, 0, y_size, -1, 1)\n pixels[i, j] = (random.randint(0, 255), # Red channel\n random.randint(0, 255), # Green channel\n random.randint(0, 255)) # Blue channel\n\n im.save(filename)", "def test_image(filename, x_size=350, y_size=350):\n # Create image and loop over all pixels\n im = Image.new(\"RGB\", (x_size, y_size))\n pixels = im.load()\n for i in range(x_size):\n for j in range(y_size):\n x = remap_interval(i, 0, x_size, -1, 1)\n y = remap_interval(j, 0, y_size, -1, 1)\n pixels[i, j] = (random.randint(0, 255), # Red channel\n random.randint(0, 255), # Green channel\n random.randint(0, 255)) # Blue channel\n\n im.save(filename)", "def generateRandomMask(size, p=0.5):\n mask_array = (np.random.random(size) > p).astype(int)\n mask = sitk.GetImageFromArray(mask_array) \n return mask", "def salt_and_pepper_noise(image, prob):\n output = np.zeros(image.shape,np.uint8)\n thres = 1 - prob \n for i in range(image.shape[0]):\n for j in range(image.shape[1]):\n rdn = random.random()\n if rdn < prob:\n output[i][j] = 0\n elif rdn > thres:\n output[i][j] = 255\n else:\n output[i][j] = image[i][j]\n return output", "def test_gray_code(self, rank, expected_gray_code):\n\n assert gray_code(rank) == expected_gray_code", "def test_color_balance_random_images(self, img):\n\n # color balance only works if every channel has at least two different\n # values, otherwise everything in that channel would be mapped to 0\n for channel in cv2.split(img):\n assume(len(np.unique(channel)) >= 2)\n\n balanced_img = balance_color(img, percentile=0)\n\n assert balanced_img.max() == 255, \\\n \"Maximum of a balanced image should be 255\"\n assert balanced_img.min() == 0, \\\n \"Minimum of a balanced image should be 0\"\n for channel in cv2.split(balanced_img):\n assert channel.max() == 255, \\\n \"Maximum of each channel should be 255\"\n assert channel.min() == 0, \\\n \"Minimum of each channel should be 0\"", "def setUp(self):\n self.image = np.random.randint(\n 0, 256, size=(10, 10, 3)).astype('uint8')", "def random_crop(self, img, output_img_h = 0.5, output_img_w = 0.5, p = 0.5):\n if self.decision(p):\n height, width, channels = img.shape\n new_height = random.randint(int(height * output_img_h), height)\n new_width = random.randint(int(width * output_img_w), width)\n y = random.randint(0, height - new_height)\n x = random.randint(0, width - new_width)\n roi = img[y:y + new_height, x:x + new_width]\n # check if cut is ahve to much dark pixels, more then 20 %\n non_zeros = np.count_nonzero(roi)\n non_zeros_procent = non_zeros / roi.size\n if non_zeros_procent < 0.8:\n pass\n else:\n img = roi\n return img", "def test_random_noise_img(alg, repNum=1):\n\timport math\n\n\tperformance = alg.predict_perf(repNum=repNum)\n\tprint performance\n\talg.plot()\n\n\talg.shape = (math.sqrt(alg.N),math.sqrt(alg.N))\n\tsave_img(alg.x, alg, 'random_original.png', False)\n\tsave_img(alg.x_pred, alg, 'random_predicted.png', False)\n\n\treturn performance", "def get_random_image():\r\n\r\n logging.debug('get_random_image()')\r\n\r\n choice = random.randint(1, 10)\r\n if choice < 7:\r\n return get_random_image_from_any_source()\r\n else:\r\n return get_random_image_from_database()", "def randomBitmap(size):\n\n b = bitmap(size)\n xmax, ymax = size\n for x in xrange(xmax):\n for y in xrange(ymax):\n b.set(x, y, random.randint(0,1))\n return b", "def image(n, low=1, high=9):\n output = numpy.random.randint(low, high=high, size=n)\n index = numpy.random.randint(0, len(output))\n output[index] = 0\n return output", "def random_brightness(image):\r\n image = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)\r\n brightness = .25 + np.random.uniform()\r\n image[:, :, 2] = image[:, :, 2] * brightness\r\n image = cv2.cvtColor(image, cv2.COLOR_HSV2RGB)\r\n return image", "def generateRandomImage(size, lims=[0,255]):\n a,b = lims\n image_array = (b-a)*np.random.random(size) + a\n image = sitk.GetImageFromArray(image_array.astype(int))\n return image", "def random_gaussian_noise(self, img, p = 0.5):\n if self.decision(p):\n mean = 30.0\n std = 80.0\n img = img + np.random.normal(mean, std, img.shape)\n\n img = np.clip(img, 0, 255).astype('uint8')\n return img", "def random_brightness(image):\n\n hsv_channel = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)\n brightness_scalar = np.random.rand()\n ratio = 1.0 + 0.4 * (brightness_scalar - 0.5)\n hsv_channel[:,:,2] = hsv_channel[:,:,2] * ratio\n return cv2.cvtColor(hsv_channel, cv2.COLOR_HSV2RGB)", "def addMaskImage(img):\r\n [h, w, c] = img.shape\r\n h_start = np.random.randint(h/2,h-1)\r\n w_start = np.random.randint(w/2, w-1)\r\n img[h_start:h-1, :,0]= np.random.randint(0,120)\r\n img[h_start:h-1, :,1]= np.random.randint(0,120) \r\n img[h_start:h-1, :,2]= np.random.randint(0,120) \r\n img[:,w_start:w-1,0]= np.random.randint(0,120)\r\n img[:,w_start:w-1,1]= np.random.randint(0,120) \r\n img[:,w_start:w-1,2]= np.random.randint(0,120) \r\n img = np.uint8(img)\r\n return img, h_start, w_start", "def random_noise(self, images, amount=20, noise_chance=0.5):\n noise_applied = False\n if uniform(0, 1) > noise_chance:\n noise = np.zeros_like(images, images.dtype) # needs preallocated input image\n noise = cv2.randn(noise, (0), (amount))\n\n images = np.where((255 - images) < noise, 255, images + noise)\n noise_applied = True\n\n return images, noise_applied", "def random_crop(img, mask):\n if str(img.dtype) != 'uint8':\n img = (img * 255).astype(np.uint8)\n if str(mask.dtype) != 'uint8':\n mask = (mask * 255).astype(np.uint8)\n img = Image.fromarray(img)\n mask = Image.fromarray(mask)\n x, y = img.size\n matrix = 256\n img_list = []\n label_list = []\n for i in range(CROP_NUM):\n x1 = randrange(0, x - matrix)\n y1 = randrange(0, y - matrix)\n img_list.append(img.crop((x1, y1, x1 + matrix, y1 + matrix)))\n label_list.append(mask.crop((x1, y1, x1 + matrix, y1 + matrix)))\n\n return img_list, label_list", "def __call__(self, results):\n if np.random.rand() > self.prob:\n return results\n self._adjust_color_img(results, self.factor)\n return results" ]
[ "0.6626922", "0.65953696", "0.6567646", "0.65488124", "0.6406716", "0.6374079", "0.63496333", "0.63314855", "0.63160866", "0.63101625", "0.63101625", "0.63101625", "0.6243581", "0.6231311", "0.6229561", "0.62180096", "0.62058157", "0.6160729", "0.61351556", "0.6100564", "0.6088092", "0.60839206", "0.6066346", "0.603352", "0.6024922", "0.6022973", "0.60064465", "0.59704196", "0.5957757", "0.5951009" ]
0.6663026
0
(dict), (float), (float) > (list) Return a sorted list of the films data by their distance to user location
def get_distance(film_coordinates, latitude, longitude): film_distance = [] for film in film_coordinates.keys(): user_coordinates = (latitude, longitude) film_coord = (film[0], film[1]) distance = great_circle(user_coordinates, film_coord).kilometers film_distance.append((distance, film[0], film[1], film_coordinates[film])) film_distance.sort(key=lambda x: x[0]) return film_distance[:10]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_nearest_films(films_list, number, input_location):\n output_list = []\n for film_data in films_list:\n film_dist = int(distance.distance(film_data[1], input_location).km)\n film_data.append(film_dist)\n output_list.append(film_data)\n output_list.sort(key=lambda x: x[-1])\n if len(output_list) >= int(number):\n output_list.pop()\n dist_list = [film[-1] for film in output_list]\n print(f'Closest film distance: {dist_list[0]} km.')\n print(f'Furthest film distance: {dist_list[-1]} km.')\n return output_list", "def get_nearest_films_filming_from_file(path, user_coordinates):\n data = pandas.read_csv(path, sep=';\\t', engine='python')\n locations, films = data['location'], data['films']\n lat, long = data['latitude'], data['longitude']\n\n distance_list = []\n for location, x, y, film in zip(locations, lat, long, films):\n distance = geodesic((x, y), user_coordinates).km\n distance_list.append((location, film, (x, y), distance))\n distance_list_sorted = sorted(distance_list, key=lambda t: t[-1])\n nearest_films_filming = [(elem[1], elem[2])\n for elem in distance_list_sorted]\n return nearest_films_filming", "def distance(pref, person1, person2, distance_metric):\n\tdistance = 0\n\trating1 = []\n\trating2 = []\n\tfor item in pref[person1]:\n\t\tif (item in pref[person2]):\n\t\t\trating1.append(pref[person1][item])\n\t\t\trating2.append(pref[person2][item])\n\t\n\treturn distance_metric(rating1, rating2)", "def filter_distance(rest_list, user, dist=10):\n user_location = get_lat_long(user)\n rest_dict1 = dict()\n rest_dict2 = dict()\n for restaurant in rest_list:\n rest_name = restaurant[0]\n rest_address = restaurant[1] + ', ' + \\\n restaurant[2] + ', '+restaurant[3]\n rest_location = get_lat_long(rest_address)\n rest_dist = get_distance(rest_location, user_location)\n if rest_dist < dist:\n if rest_name in rest_dict1:\n if rest_dist < rest_dict1[rest_name]:\n rest_dict1[rest_name] = rest_dist\n rest_dict2[rest_name] = rest_address\n else:\n rest_dict1[rest_name] = rest_dist\n rest_dict2[rest_name] = rest_address\n return rest_dict2", "def get_closest(list_of_nearby, favorite_place):\n\tref_rating = float(favorite_place[\"rating\"]) # this is a float\n\tref_price_len = len(favorite_place[\"price\"]) # this is the length of the dollar sign - an int\n\tref_categ = favorite_place[\"categories\"] # this is a string!\n\n\tfor item in list_of_nearby:\n\t\tscore = 0\n\t\tlist_of_cat_words = item[categories].split()\n\t\tfor word in list_of_cat_words:\n\t\t\tif word in ref_categ:\n\t\t\t\tscore += 1\n\t\tscore = score * 5\n\t\tscore = score - 2 * abs(len(item[\"price\"]) - ref_price_len)\n\t\tscore = score - 10 * abs(float(item[\"rating\"]) - ref_rating)\n\t\titem[\"score\"] = score\n\n\tfor item in list_of_nearby:\n\t\treturn_list = []\n\t\treturn_list.append({\"id\": item[\"id\"], \"score\": item[\"score\"]})\n\n\treturn_list = sorted(return_list, key = lambda i: i[\"score\"])\n\treturn return_list", "def _sort_results(\n self, results: Dict[tuple, List[dict]]\n ) -> List[List[tuple[int, float, float]]]:\n\n sorted_weather = [results[url] for url in self.urls_list]\n all_results = []\n\n for num, location in enumerate(self.locations):\n city_weather_list = sorted_weather[num * 6 : (num + 1) * 6]\n city_result = [\n (\n city_weather_list[0][\"daily\"][day][\"dt\"],\n city_weather_list[0][\"daily\"][day][\"temp\"][\"min\"],\n city_weather_list[0][\"daily\"][day][\"temp\"][\"max\"],\n )\n for day in range(6)\n ]\n\n for day in range(1, 6):\n weather = city_weather_list[day]\n temp = [w[\"temp\"] for w in weather[\"hourly\"]]\n city_result.append((weather[\"current\"][\"dt\"], min(temp), max(temp)))\n\n all_results.append(sorted(city_result, key=lambda x: x[0]))\n\n return all_results", "def distances(self):", "def get_cities_sorted_location(request):\n latitude, longitude = latlang(request)\n point = Point(float(longitude), float(latitude), srid=4326)\n locations = Location.objects.filter(point__distance_lte=(point, D(km=200))).annotate(distance=Distance(\"point\", point)).order_by(\"distance\")[:10]\n return JsonResponse(json.dumps([serializer_distance(location) for location in locations]), safe=False)", "def quicksort_from_pos(dataset, lat, lng) -> List[dict]:\n\tdist_from_x = calculateDistance(lat, lng)\n\tadd_dist_to_dataset(dataset, dist_from_x)\n\treturn quicksort(dataset, \"dist\")", "def sortDistance(netlist):\n netlist_dictionary = {}\n for i in range(len(netlist)):\n start = chips[netlist[i][0]]\n end = chips[netlist[i][1]]\n\n delta_x = abs(start[0]-end[0])\n delta_y = abs(start[1]-end[1])\n distance = delta_x + delta_y\n\n netlist_dictionary[(netlist[i][0], netlist[i][1])] = distance\n\n sorted_dictionary = sorted(netlist_dictionary.items(), key=operator.itemgetter(1))\n sorted_netlist = []\n for j in range(len(sorted_dictionary)):\n sorted_netlist.append(sorted_dictionary[j][0])\n\n return sorted_netlist", "def sorted_objects(detected_objects, keyname):\n\n if detected_objects.get(keyname):\n return sorted(detected_objects[keyname],\n key=lambda u: math.sqrt(u['norm_pos'][0] ** 2 + u['norm_pos'][1] ** 2))\n else:\n return []", "def order_by_fitness(self):\n self.fauna_list['Herbivore'].sort(key=operator.\n attrgetter('animal_fitness'))\n self.fauna_list['Carnivore'].sort(key=operator.\n attrgetter('animal_fitness'),\n reverse=True)", "def get_stops_sorted( latitude, longitude ):\n\treturnvalue = []\n\tstops_file = open( 'google_transit/stops.txt' )\n\tstops_iter = DictReader( stops_file )\n\tfor stop in stops_iter:\n\t\tdistance = angular_distance( latitude, longitude, \n\t\t\t\t\t\t\t float( stop[ 'stop_lat' ] ), float( stop[ 'stop_lon' ]))\n\t\tstop[ 'distance' ] = distance * MI\n\t\treturnvalue.append(( distance, stop ))\n\tstops_file.close( )\n\treturnvalue.sort( )\n\treturn [ y for x,y in returnvalue ]", "def get_average_scores(directors: Dict[str, List[Movie]]) -> List[Tuple[str, float]]:\n res = []\n for director_name, movies in directors.items():\n if len(movies) >= MIN_MOVIES:\n avg_score = calc_mean_score(movies)\n info = (director_name, avg_score)\n res.append(info)\n\n return sorted(res, key=lambda x: x[1], reverse=True)", "def order_songs(songs, target, n):\n songs_with_features = []\n # Adds the Euclidean distance to the dictionaries and sorts the list in ascending order.\n for song in songs:\n if song['excitedness']:\n song['distance'] = distance.euclidean(target, (song['excitedness'], song['happiness']))\n songs_with_features.append(song)\n\n\n ordered_songs = sorted(songs_with_features, key=lambda k: k['distance'])\n\n # Removes the distance from the dictionaries and returns the best n tracks.\n for d in ordered_songs:\n del d['distance']\n\n return ordered_songs[:n]", "def distances(self):\n self._sort_measurements()\n return self._distances", "def calcRestaurantList2(latlngs, cuisines, distance):\n restlist = []\n used = []\n cuisine = str(cuisines[0])\n if len(cuisines) > 1:\n cuisine = \",\".join(cuisines)\n minrating = 5.0\n worst = ''\n ratings = []\n for point in latlngs:\n yelpresults = search2(cuisine,point,distance)['businesses']\n processedyelpresults = processResults(yelpresults)\n for result in processedyelpresults:\n if (result not in used):\n if len(restlist) < 40:\n restlist.append(processedyelpresults[result])\n used.append(result)\n ratings.append(float(processedyelpresults[result]['rating']))\n if float(processedyelpresults[result]['rating']) < minrating:\n minrating = float(processedyelpresults[result]['rating'])\n worst = result\n # print (\"The worst restaurant is {0}\".format(worst))\n elif len(restlist) >= 40:\n ratings.sort()\n minrating = ratings[0]\n if float(processedyelpresults[result]['rating']) > ratings[0]:\n if worst in restlist:\n ratings.remove(minrating)\n restlist.remove(restlist.index(worst))\n # print (\"Removed {0}, which had a rating of {1}. It was in restlist\".format(worst, minrating))\n if len(restlist) <= 45:\n restlist.append(processedyelpresults[result])\n # print (\"Added {0}, which had a rating of {1}\".format(result, processedyelpresults[result]['rating']))\n else:\n minrating = float(ratings[0])\n # print (\"The minimum rating for a restaurant is {0}\".format(minrating))\n for r in restlist:\n # print (r)\n if float(r['rating']) == minrating:\n restlist.remove(r)\n # print (\"Removed {0}, which had a rating of {1}. Matched on minrating\".format(r, minrating))\n if minrating in ratings:\n ratings.remove(minrating)\n if len(restlist) <= 45:\n restlist.append(processedyelpresults[result])\n # print (\"Added {0}, which had a rating of {1}\".format(result, processedyelpresults[result]['rating']))\n\n # pprint.pprint(restlist)\n # print(used)\n\n return restlist", "def filter_by_compare(self, diclist, fidname, value, comparison, outputfidlist=[]):\n if comparison == 'GT':\n result = [item for item in diclist if item[fidname] > value]\n elif comparison == 'LT':\n result = [item for item in diclist if item[fidname] < value]\n elif comparison == 'EQ':\n result = [item for item in diclist if item[fidname] == value]\n else:\n result = []\n \n return self.filter_output(result, outputfidlist)", "def get_distance_metrics():\n\n return [HausdorffDistance(),\n AverageDistance(),\n MahalanobisDistance(),\n VariationOfInformation(),\n GlobalConsistencyError(),\n ProbabilisticDistance()]", "def subdata(min_,dict_):\n list_ = []\n return [value for value,freq in dict_.items() if freq > min_]", "def calculate_distances(coords: List[Tuple[float, float]]) -> List[Dict]:\n miles = 0\n od = []\n for idx in range(len(coords)):\n if idx == 0:\n continue\n dist = distance(coords[idx], coords[idx - 1]).miles\n miles = miles + dist\n od.append(\n {\n \"start\": coords[idx - 1],\n \"stop\": coords[idx],\n \"distance\": dist,\n \"total\": miles,\n }\n )\n return od", "def merge_geos(data1, data2): # (geodist, datastore)\n data_merged = [\n dict(**el1, **el2)\n for el1 in data1\n for el2 in data2\n if el1['ipv4'] in el2['meta']\n ]\n merged_sorted = sorted(\n data_merged,\n key=lambda k: k['dist'],\n reverse=False\n )\n return merged_sorted", "def distance_score(rows):\n # If there's only one word, everyone wins!\n if len(rows[0]) <= 2:\n return dict([(row[0], 1.0) for row in rows])\n\n # Initialize the dictionary with large values\n mindistance = dict([(row[0], 1000000) for row in rows])\n\n for row in rows:\n dist = sum([abs(row[i]-row[i-1]) for i in range(2, len(row))])\n # get the min distance for this url\n if dist < mindistance[row[0]]:\n mindistance[row[0]] = dist\n return normalize_scores(mindistance, small_is_better=1)", "def album_distance(self, items, album_info, mapping):\n dist = Distance()\n\n if (album_info.data_source == 'Wikipedia'):\n dist.add('source', self.config['source_weight'].as_number())\n return dist", "def main():\n users = {}\n\n with open('../the_data.json', 'r') as f:\n the_data = json.loads(f.read())\n\n user_data = the_data['data']\n the_user_ids = json.loads(the_data['user_ids_list'])\n \n def p(vector):\n vector = json.loads(vector)\n return {field: vector[i] for i,field in enumerate(the_data['vector_fields'])}\n\n result = {}\n for step in range(1, 20):\n step = str(step)\n\n users = {}\n the_user_ids_for_this_step = []\n for uid in the_user_ids:\n try:\n users[uid] = p(user_data[uid][step])\n the_user_ids_for_this_step.append(uid) \n except:\n pass\n\n for user_id in the_user_ids_for_this_step: \n nearest = computeNearestNeighbor(user_id,\n users,\n distance_algorithm='minkowski')\n # print user_id\n if user_id not in result:\n result[user_id] = {}\n\n result[user_id][step] = nearest[:3]\n\n\n\n # print result\n\n for u in result.keys():\n woha = []\n print '%s, step_count: %s' % (u, user_data[u]['step_count'])\n ls = result[u].keys()\n ls.sort()\n for s in ls: \n print s\n for near in result[u][s]:\n if near[1] in woha:\n ulala = '>'*woha.count(near[1])\n else:\n ulala = ''\n woha.append(near[1])\n print '\\t'*int(s), '%s %s, %s, step_count: %s' % (ulala, near[1], near[0], user_data[near[1]]['step_count'])\n\n print", "def _analyse_topics(frequencies):\n freq = frequencies[0]\n freq_ref = frequencies[1]\n the_dict = weight_term_frequencies_one(freq,freq_ref)\n sorted_toks = sorted(the_dict.iteritems(),\n key=operator.itemgetter(1))\n \n sorted_toks.reverse()\n sorted_toks = sorted_toks[:400]\n final_toks = []\n for (k,v) in sorted_toks:\n best = True\n for (k1,v1) in sorted_toks:\n if k != k1:\n if (abs(v1-v)) < 0.2:\n if k in k1:\n best = False\n #print \"dropped\", k\n if best:\n final_toks.append((k,v))\n \n very_final_toks = {}\n for (k,v) in final_toks:\n close_val = [(k2,v2) for k2,v2 in final_toks[:50] if abs(v-v2) < 0.2]\n if len(close_val) < 1:\n very_final_toks[k] = v\n else:\n similar = [(k3,v3,len(k3)) for k3,v3 in close_val if difflib.SequenceMatcher(None,k,k3).quick_ratio() > 0.89]\n if len(similar) > 1:\n a,b,c = sorted(similar,key=operator.itemgetter(2))[0]\n very_final_toks[a] = b\n else:\n very_final_toks[k] = v\n \n very_final_toks = sorted(very_final_toks.iteritems(),\n key=operator.itemgetter(1))\n very_final_toks.reverse()\n return very_final_toks", "def suggest_movies(self, reviewer: Any, other: Any) -> list[Any]:\n potential_recs = self.get_neighbours(other)\n suggestions_so_far = []\n neighbours = self.get_neighbours(reviewer)\n\n for p_rec in potential_recs:\n if p_rec not in neighbours and self.get_weight(other, p_rec) >= 9:\n suggestions_so_far.append(p_rec)\n\n return suggestions_so_far", "def get_most_similar(distances):\n threshold = get_threshold(distances)\n most_similar = list()\n distances = sorted(distances, key=lambda x: x[0])\n\n for i in distances:\n if i[0] < threshold:\n most_similar.append(i)\n else:\n break\n\n return most_similar", "def distance_user_point_to_polygons(user_point, polygon_list):\n list_polygons_distances = []\n\n for polygon in polygon_list:\n dist = user_point.distance(polygon)\n list_polygons_distances.append(dist)\n\n #return sorted(list_polygons_distances, key=lambda x: x[1], reverse=True)\n return list_polygons_distances", "def sort_bike_stations(bike_stations, location):\n\n stations = bike_stations.copy()\n\n for index, station in enumerate(stations):\n station_location = (station[\"lat\"], station[\"lon\"])\n dist = distance.distance(station_location, location).m\n stations[index][\"distance\"] = dist\n\n stations = sorted(stations, key=lambda station: station[\"distance\"])\n stations = list(filter(lambda station: station[\"bikesAvailable\"] > 0, stations))\n\n return stations" ]
[ "0.695379", "0.62231535", "0.5737258", "0.5702767", "0.5697553", "0.56067765", "0.5601279", "0.55895054", "0.5549139", "0.55441296", "0.554395", "0.55432135", "0.5508882", "0.5467602", "0.5463768", "0.5454729", "0.5454257", "0.54269826", "0.5369309", "0.53676164", "0.53409404", "0.53058904", "0.52712184", "0.5261546", "0.52481914", "0.5243778", "0.523075", "0.5216992", "0.52139425", "0.5212712" ]
0.6938966
1
(dict) > (dict) Return a dictionary of coordinates of films
def get_film_coordinates(film_dict): coordinate_dict = dict() for location in film_dict.keys(): try: locator = geopy.Nominatim(user_agent="filmGeocoder", timeout=10) coordinates = locator.geocode(location) coordinate_dict[coordinates.latitude, coordinates.longitude] = film_dict[location] except (TypeError, AttributeError, IndexError): continue return coordinate_dict
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_data_from_films_locations_file(path):\n film_locations_data = {}\n with open(path, encoding='utf-8', errors='ignore') as f:\n for line in f:\n line = line.strip()\n line_values = line.split(',')\n film, year, location = line_values[0], line_values[1],\\\n line_values[-1]\n if year in film_locations_data:\n if location not in film_locations_data[year]:\n film_locations_data[year][location] = {film}\n else:\n film_locations_data[year][location].add(film)\n else:\n film_locations_data[year] = {location: {film}}\n return film_locations_data", "def get_distance(film_coordinates, latitude, longitude):\n film_distance = []\n for film in film_coordinates.keys():\n user_coordinates = (latitude, longitude)\n film_coord = (film[0], film[1])\n\n distance = great_circle(user_coordinates, film_coord).kilometers\n film_distance.append((distance, film[0], film[1], film_coordinates[film]))\n\n film_distance.sort(key=lambda x: x[0])\n return film_distance[:10]", "def _get_positions(self):\n position_map = dict()\n # Assumes that the positions are indexed in the order of Row-->Well-->FOV\n for well in self.wells:\n for pos in self.store[well].attrs.get('well').get('images'):\n pos_name = pos['path']\n # pos name is 'Pos_xxx'\n pos_idx = int(pos_name.split('_')[-1])\n position_map[pos_idx] = {'name': pos_name, 'well': well}\n return position_map", "def get_coordinates_by_category(self):\n\n result = {}\n for crime in self.crimes:\n cat_name = crime.category.category_name.strip()\n if cat_name in result:\n result[cat_name].append((crime.latitude, crime.longitude))\n else:\n result[cat_name] = [(crime.latitude, crime.longitude)]\n \n return result", "def get_mouth(dictionary):\r\n mouth = []\r\n for landmark, coordinate in dictionary.items():\r\n if landmark.startswith(\"mouth_\"):\r\n mouth.append((coordinate['x'], coordinate['y']))\r\n return mouth", "def get_location_coordinates(films_set, film_number=0):\n if not film_number:\n film_number = len(films_set)\n\n films_list = sorted(list(films_set))\n print(f'List has {len(films_list)} films with specified year. '\n f'\\nAmount of films to analyze: {film_number} '\n f'\\n------------------------------')\n\n locations_loss = 0\n lost_locations = []\n output_list = []\n coordinates_set = set()\n geoloc = Nominatim(user_agent=\"map\")\n print('Loading...')\n for i in range(film_number):\n if '.' in films_list[i][-1]:\n geo_value = geoloc.geocode(films_list[i][-1]\n [films_list[i][-1].find('.'):], timeout=30)\n else:\n geo_value = geoloc.geocode(films_list[i][-1], timeout=30)\n if geo_value is None or \\\n (geo_value.latitude, geo_value.longitude) in coordinates_set:\n locations_loss += 1\n lost_locations.append(films_list[i])\n continue\n time.sleep(1.1)\n coordinates = (geo_value.latitude, geo_value.longitude)\n coordinates_set.add(coordinates)\n output_list.append([films_list[i][0], coordinates])\n print(f\"Lost {locations_loss} locations overall, due to geopy\", lost_locations)\n return output_list", "def get_films_in_country(film_set, country):\n film_dict = dict()\n for film in film_set:\n try:\n film_locations = film[1].split(', ')\n film_country = film_locations[-1]\n film_city = film_locations[-2]\n\n if film_country == country:\n if film_city in film_dict:\n film_dict[film_city].add(film[0])\n else:\n film_dict[film_city] = {film[0]}\n except (TypeError, IndexError, AttributeError):\n continue\n return film_dict", "def get_imdb_list():\n list_file = 'imdb.txt'\n name_column = 26\n f = open(list_file, 'r')\n film_list = []\n pos = 0\n\n for line in f:\n pos += 1\n words = line.split()\n name = line[name_column:-1]\n # could be problematic is there are brackets in the film name\n year = name[name.find('(') + 1:name.find(')')]\n name = name.replace('(' + year + ')', '')\n film = {\n 'pos': pos,\n 'score': Decimal(words[2]),\n 'name': name.strip(),\n 'year': year\n }\n film_list.append(film)\n f.close()\n return film_list", "def get_popular_locations_dict(film_set):\n popular_locations = dict()\n for film in film_set:\n try:\n location = film[1].split(', ')[-1]\n if location in popular_locations.keys():\n popular_locations[location] += 1\n else:\n popular_locations[location] = 1\n except (TypeError, AttributeError, IndexError):\n continue\n\n return popular_locations", "def filecoords(self):\n coords = sorted(self.map.keys())\n for coord in coords:\n yield coord, self.map[coord]", "def dict_to_coordinates(dictionary):\r\n coordinates = []\r\n\r\n for landmark, coordinate in dictionary.items():\r\n coordinates.append((coordinate['x'], coordinate['y']))\r\n\r\n return coordinates", "def getTF_IDFSpace():\n sids,documents = getSongTextInfo()\n texts = [[word for word in document.lower().split()] for document in documents]\n dictionary = corpora.Dictionary(texts)\n corpus = [dictionary.doc2bow(text) for text in texts]\n tfidf = models.TfidfModel(corpus)\n corpus_tfidf = tfidf[corpus]\n songMap = {}\n index = 0\n for doc in corpus_tfidf:\n sid = sids[index]\n rMap = {}\n for item in doc:\n wid = item[0]\n count = item[1]\n rMap[wid] = count\n songMap[sid] = rMap\n index += 1\n return songMap", "def data_xy(position) -> dict:\n\n return {\"x\": position[0], \"y\": position[1]}", "def _getMdrizskyValues(self):\n mdict = {}\n mlist = []\n for member in self.assoc.parlist:\n fname = member['image'].datafile\n if not mdict.has_key(fname): \n mlist.append((fname, member['image'].getSubtractedSky()))\n mdict[fname] = 1\n \n return mlist", "def signal_dictionary(music_filename):\n\tx = []\n\ty = []\n\tassign_points = {}\n\n\tsignal = input_waves.WAVtoSignal(music_filename)\n\tfor i in range(len(signal)):\n\t\tx = signal[i][0]\n\t\ty = signal[i][1]\n\t\tassign_points.update({x:y})\n\tprint 'assign dictionary complete'\n\treturn assign_points", "def _get_queried_pts(self):\n queries = {}\n for f_name in self.f_names:\n queries[f_name] = np.asarray([qi.pt\n for qi in self.query_history[f_name]])\n return queries", "def position(self):\n return dict(x=self.x, y=self.y)", "def castFilmography (movies, minAppearances):\n actors = {}\n for (k,v) in movies.items():\n for a in v[2:7]:\n actors[a] = actors.get(a, []) + [k]\n return sorted([ [k] + v for (k,v) in actors.items() if len(v) >= minAppearances ])", "def get_pixel_cordinate_from_xml(self, path):\n \n \n spot_dict = {}\n try:\n xml_doc = minidom.parse(path)\n for space_list in xml_doc.getElementsByTagName(\"object\"):\n spot_name = str(space_list.getElementsByTagName(\"name\")[0].firstChild.nodeValue)\n min_overlap_thres = self.default_thres_list[0]\n max_overlap_thres = self.default_thres_list[1]\n overflow_thres = self.default_thres_list[2]\n if spot_name in list(self.special_spot.keys()):\n for thres_name in self.special_spot[spot_name].keys():\n if thres_name == \"min_overlap_thres\":\n min_overlap_thres = self.special_spot[spot_name][\"min_overlap_thres\"]\n if thres_name == \"max_overlap_thres\":\n max_overlap_thres = self.special_spot[spot_name][\"max_overlap_thres\"]\n if thres_name == \"overflow_thres\":\n overflow_thres = self.special_spot[spot_name][\"overflow_thres\"]\n \n for spot in space_list.getElementsByTagName(\"bndbox\"):\n cordinate_list = []\n cordinate_list.append(int(spot.getElementsByTagName(\"xmin\")[0].firstChild.nodeValue))\n cordinate_list.append(int(spot.getElementsByTagName(\"ymin\")[0].firstChild.nodeValue))\n cordinate_list.append(int(spot.getElementsByTagName(\"xmax\")[0].firstChild.nodeValue))\n cordinate_list.append(int(spot.getElementsByTagName(\"ymax\")[0].firstChild.nodeValue))\n \n \n if spot_name in self.parked_spots:\n init_status = True\n else:\n init_status = False\n \n spot_dict[spot_name] = [[(cordinate_list[0], cordinate_list[1]), (cordinate_list[0], cordinate_list[3]), (cordinate_list[2], cordinate_list[3]), (cordinate_list[2], cordinate_list[1])],min_overlap_thres, max_overlap_thres, overflow_thres, init_status]\n except FileNotFoundError as fnf:\n print(\"XML File not found at the location :\"+str(path))\n print(fnf)\n except Exception as e:\n print(e)\n return spot_dict", "def get_kml_dict(self,name,filename):\n\n lon1,lon2,lat1,lat2=self.get_bounds()\n d={'lat1':lat1,'lat2':lat2,'lon1':lon1,'lon2':lon2, \\\n 'name':name,'filename':filename,'time':self.get_time()}\n return d", "def get_photos_info():\n photos_info = np.loadtxt(PHOTOS_INFO, delimiter=',', unpack=True, dtype=str, usecols=(0, 1))\n photos_info_dict = dict(zip(photos_info[0], photos_info[1]))\n return photos_info_dict", "def rf_extents(rf_dict):\n x_min, y_min, x_max, y_max = np.inf, np.inf, -np.inf, -np.inf\n for rf in rf_dict:\n x_min = np.min([rf['on_center_x'], x_min])\n x_max = np.max([rf['on_center_x'], x_max])\n y_min = np.min([rf['on_center_y'], y_min])\n y_max = np.max([rf['on_center_y'], y_max])\n if x_min == x_max:\n x_max += 1\n if y_min == y_max:\n y_max += 1\n return {\n 'x_min': x_min,\n 'x_max': x_max,\n 'y_min': y_min,\n 'y_max': y_max\n }", "def get_bfi_list():\n list_file = 'bfi_sight_and_sound_2012.txt'\n f = open(list_file, 'r')\n film_list = []\n\n for line in f:\n words = line.split(' ')\n #NOTE: pos is not the position in the pyton list but in the original\n # list so is not always an integer due to joint places\n film = {'pos': words[0], 'name': words[1][:-1]}\n film_list.append(film)\n f.close()\n return film_list", "def get_nearest_films_filming_from_file(path, user_coordinates):\n data = pandas.read_csv(path, sep=';\\t', engine='python')\n locations, films = data['location'], data['films']\n lat, long = data['latitude'], data['longitude']\n\n distance_list = []\n for location, x, y, film in zip(locations, lat, long, films):\n distance = geodesic((x, y), user_coordinates).km\n distance_list.append((location, film, (x, y), distance))\n distance_list_sorted = sorted(distance_list, key=lambda t: t[-1])\n nearest_films_filming = [(elem[1], elem[2])\n for elem in distance_list_sorted]\n return nearest_films_filming", "def get_observations(asteroid_map: str) -> Dict[Asteroid, List[Asteroid]]:\n # initialize asteroid map\n asteroids = intialize_asteroid_map(asteroid_map)\n all_observations = {}\n for asteroid_1 in asteroids:\n asteroid_1_observations = {}\n for asteroid_2 in asteroids:\n if asteroid_1 == asteroid_2:\n continue\n angle = calculate_angle(asteroid_1, asteroid_2)\n if angle in asteroid_1_observations:\n asteroid_1_observations[angle].append(asteroid_2)\n else:\n asteroid_1_observations[angle] = [asteroid_2]\n all_observations[asteroid_1] = asteroid_1_observations\n return all_observations", "def getFeaturedLocation(guide):\n photos = guide.photos.all()\n\n x = 0\n y = 0\n z = 0\n\n size = 0\n\n for photo in photos:\n if photo.latitude:\n lat = radians(float(photo.latitude))\n lon = radians(float(photo.longitude))\n x += cos(lat) * cos(lon)\n y += cos(lat) * sin(lon)\n z += sin(lat)\n size+=1\n\n if size is 0:\n return None\n\n x = float(x / size)\n y = float(y / size)\n z = float(z / size)\n\n return {\n 'latitude': degrees(atan2(z, sqrt(x * x + y * y))),\n 'longitude': degrees(atan2(y, x))\n }\n # return atan2(z, sqrt(x * x + y * y)), atan2(y, x)\n\n\n\n # for photo in photos:\n # if photo.latitude:\n # return {\n # 'latitude': photo.latitude,\n # 'longitude': photo.longitude\n # }\n\n # return None", "def coordinates(self):", "def _get_positions(self, image):\n\t\tH, W, _ = image.shape\n\t\tpos_list = self.apply_detection(image)\n\t\tdetections = {}\n\t\thasDetection = False\n\t\tfor i, L in enumerate(pos_list):\n\t\t\ttext, coordinates = L[0], L[1]\n\t\t\tfor x, y, w, h in coordinates:\n\t\t\t\tif x < 0 or y < 0 or x + w > W or \\\n\t\t\t\t y + h > H or w <= 1 or h <= 1:\n\t\t\t\t\tcontinue\n\t\t\t\t# add the detection to the dict for tracking\n\t\t\t\tif text == 'face' or text == 'super woman':\n\t\t\t\t\tself.detection_index[self.num_detect] = (x, y, w, h, self.num_save, text, -1)\n\t\t\t\telse:\n\t\t\t\t\tself.detection_index[self.num_detect] = (x, y, w, h, self.num_save, text, -2)\n\t\t\t\tdetections[self.num_detect] = (x, y, w, h)\n\t\t\t\tself.num_detect += 1\n\t\t\t\thasDetection = True\n\t\tif hasDetection:\n\t\t\tself.detection_frames[self.num_save] = detections\n\t\tself.num_save +=1", "def resolution(self):\n return {'x': self.width, 'y': self.height}", "def getVSMSpace():\n sids,documents = getSongTextInfo()\n texts = [[word for word in document.lower().split()] for document in documents]\n dictionary = corpora.Dictionary(texts)\n corpus = [dictionary.doc2bow(text) for text in texts]\n songMap = {}\n index = 0\n for doc in corpus:\n sid = sids[index]\n rMap = {}\n for item in doc:\n wid = item[0]\n count = item[1]\n rMap[wid] = count\n songMap[sid] = rMap\n index += 1\n return songMap" ]
[ "0.6048309", "0.57136226", "0.57079375", "0.57055396", "0.5634014", "0.54674006", "0.54155713", "0.540007", "0.5340333", "0.5332164", "0.52578497", "0.5231767", "0.51908624", "0.5190739", "0.5182495", "0.5181372", "0.5179014", "0.51677597", "0.516235", "0.51522034", "0.51505136", "0.5124498", "0.5121125", "0.51013017", "0.508921", "0.5074385", "0.506112", "0.5057438", "0.50472105", "0.49962783" ]
0.72613245
0
(str) > (str) Return a country from a user coordinates
def get_user_country(user_location): geo_locator = geopy.Nominatim(user_agent="User Location", timeout=10) location = geo_locator.reverse(user_location, language='en') location = str(location).split(', ') country = location[-1] if country == 'United States of America': country = 'USA' elif country == 'United Kingdom': country = 'UK' return country
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_country_from_coordinates(coordinates):\n geolocator = Nominatim(user_agent=\"random_one\")\n location = geolocator.reverse(coordinates, language='en')\n country = location.address.split(',')[-1].strip()\n return country", "def country() -> str:", "def country(alpha_2_code: str) -> None:", "def get_country(ip):\r\n return geoip.country_code_by_addr(ip)", "def country(name):\n return location_db().find(name=name)[\"country\"]", "def get_city_country(city, country, population=''):\n if population:\n location = city + ' ' + country + ' ' + str(population)\n return location.title()\n\n else:\n location = city + ' ' + country\n return location.title()", "def city_country(city, country):\n return(city + ', ' + country)", "def convert_country(country):\n if (country and 'China' in country) or \\\n country == 'Chin' or country == 'CHINA':\n country = 'China'\n elif country and 'Brazil' in country or \\\n country == 'Brasil' or \\\n country == 'ITA - Instituto Tecnologico de Aeronautica (':\n country = 'Brazil'\n elif country and 'Argentina' in country:\n country = 'Argentina'\n elif country == 'Czechia':\n country = 'Czech Republic'\n elif 'Norwegian' in country:\n country = 'Norway'\n elif country and 'United Kingdom' in country:\n country = 'United Kingdom'\n elif country and 'Hong Kong' in country:\n country = 'Hong Kong'\n elif country == 'Cameroun':\n country = 'Cameroon'\n elif (country and 'Chile' in country) or country == 'CHILE':\n country = 'Chile'\n elif (country and 'United States of America' in \\\n country) or country == 'United States' or country \\\n == 'USA' or 'Florida' in country or \\\n 'California' in country or\\\n country == 'National Reference Centre for' or \\\n country == 'United State of America' or \\\n country == 'U.S.A.' or \\\n country == 'Virginia':\n country = 'United States of America'\n elif country=='Republic of Panamá' or country=='Panamá' or 'Panama' in country:\n country = 'Panama'\n elif 'Canada' in country:\n country = 'Canada'\n elif 'Colombia' in country:\n country = 'Colombia'\n elif 'Spain' in country or country=='España':\n country = 'Spain'\n elif 'Iran' in country:\n country = 'Iran'\n elif 'Saudi Arabia' in country:\n country = 'Saudi Arabia'\n elif 'Italy' in country:\n country = 'Italy'\n elif 'Japan' in country:\n country = 'Japan'\n elif 'Germany' in country:\n country = 'Germany'\n elif 'Luxembourg' in country:\n country = 'Luxembourg'\n elif ('France' in country) or country == 'Marseille':\n country = 'France'\n elif country == 'ROC' or country == 'R. O. C':\n country = 'Taiwan'\n elif country == 'Brasil':\n country = 'Brazil'\n elif country == 'México' or 'Mexico' in country:\n country = 'Mexico'\n elif 'Slowakia' in country:\n country = 'Slowakia'\n elif country == 'Korea' or 'Republic of Korea' in country:\n country = 'South Korea'\n elif country == 'United Kindgom':\n country = 'United Kingdom'\n elif country and 'Netherlands' in country:\n country = 'Netherlands'\n elif country == 'Commonwealth of Australia' or 'Australia' in country:\n country = 'Australia'\n elif 'Singapore' in country:\n country = 'Singapore'\n elif country and (country[0].isdigit() or country[0] == '+'):\n country = 'N/A'\n return country", "def test_get_country_by_geo_location(self):\n pass", "def locate(location):\n coord = None\n country_name = None\n if location:\n location = location.lower()\n\n for ind, row in country_map.iterrows():\n\n if (\n (re.match(r'(.*\\W|\\W*){}\\b'.format(row['code2']), location))\n or(re.match(r'(.*\\W|\\W*){}\\b'.format(row['code3']), location))\n or(re.match(r'(.*\\W|\\W*){}\\b'.format(row['name']), location))):\n\n coord = [row['lat'], row['lang']]\n country_name = row['name']\n break\n return country_name, coord", "def city_country(city, country):\n full_city = city + \", \" + country\n return full_city.title()", "def city_country(city, country):\n city_and_country = city + ', ' + country\n return city_and_country.title()", "def city_country(city_name, country_name):\n city_country_combo = city_name + ', ' + country_name\n return city_country_combo.title()", "def get_country(ip_addr):\r\n html = urllib2.urlopen('http://freegeoip.net/json/' + ip_addr).read()\\\r\n .decode('utf-8')\r\n responseJson = json.loads(html)\r\n return responseJson.get('country_code')", "def city_country(city, country):\n c_c = '\"' + city + \", \" + country + '\"'\n return c_c.title()", "def get_country_from_string(affiliation_string):\n\n affiliation_string = affiliation_string.replace(\"Electronic address:\",\"\")\n \n mail = re.findall(\"\\S+@\\S+\" , affiliation_string)\n if len(mail)>0:\n for m in mail:\n affiliation_string = affiliation_string.replace(m,\"\")\n\n brcts = re.findall(\"\\(.*\\)\" , affiliation_string) \n if len(brcts)>0:\n for b in brcts:\n affiliation_string = affiliation_string.replace(b,\"\") \n\n for term in affiliation_string.strip().split(\",\"):\n if term!=\"\":\n country = term.strip()\n \n country = country.strip(\".\") \n return(country)", "def get_country_from_record(ip):\r\n record = geoip.record_by_addr(ip)\r\n if record != None:\r\n return record['country_code']", "def get_country_details(self,country):\n try:\n country_obj = pycountry.countries.get(name=country)\n if country_obj is None:\n c = pycountry.countries.search_fuzzy(country)\n country_obj = c[0]\n continent_code = pc.country_alpha2_to_continent_code(country_obj.alpha_2)\n continent = pc.convert_continent_code_to_continent_name(continent_code)\n return country_obj.alpha_3, continent\n except:\n if 'Congo' in country:\n country = 'Congo'\n elif country == 'Diamond Princess' or country == 'Laos' or country == 'MS Zaandam' or country == 'Holy See' or country == 'Timor-Leste':\n return country, country\n elif country == 'Korea, South' or country == 'South Korea':\n country = 'Korea, Republic of'\n elif country == 'Taiwan*':\n country = 'Taiwan'\n elif country == 'Burma':\n country = 'Myanmar'\n elif country == 'West Bank and Gaza':\n country = 'Gaza'\n else:\n return country, country\n country_obj = pycountry.countries.search_fuzzy(country)\n continent_code = pc.country_alpha2_to_continent_code(country_obj[0].alpha_2)\n continent = pc.convert_continent_code_to_continent_name(continent_code)\n return country_obj[0].alpha_3, continent", "def city_country(city, country):\n return city.title() + \", \" + country.title()", "def get_formatted_location(city, country):\n\tformatted_location = city + \", \" + country\n\treturn formatted_location.title()", "def city_country(city, country):\n return(city.title() + \", \" + country.title())", "def city_country(city, country):\r\n\treturn(city.title() + ', ' + country.title())", "def searchCountry(host):\n process = subprocess.Popen(\"geoiplookup \"+host,stdout=subprocess.PIPE, shell=True)\n (output, err) = process.communicate()\n secondPart = output.split(\"GeoIP Country Edition: \", 1)[1]\n country = secondPart.split(\"\\nGeoIP City Edition\", 1)[0]\n return country", "def get_geo_location(country: str) -> Optional[str]:\n country_to_geo_location_mapping = {\n \"Portugal\": \"Europe\",\n \"Spain\": \"Europe\",\n \"France\": \"Europe\",\n \"Italy\": \"Europe\",\n \"Malta\": \"Europe\",\n \"Switzerland\": \"Europe\",\n \"Austria\": \"Europe\",\n \"Slovenia\": \"Europe\",\n \"Croatia\": \"Europe\",\n \"Greece\": \"Europe\",\n \"Turkey\": \"Europe\",\n \"North Macedonia\": \"Europe\",\n \"Poland\": \"Europe\",\n \"Germany\": \"Europe\",\n \"Netherlands\": \"Europe\",\n \"Denmark\": \"Europe\",\n \"Sweden\": \"Europe\",\n \"Norway\": \"Europe\",\n \"Finland\": \"Europe\",\n \"Latvia\": \"Europe\",\n \"Russia\": \"Europe\",\n \"Belgium\": \"Europe\",\n \"Ireland\": \"Europe\",\n \"United Kingdom\": \"Europe\",\n \"Iceland\": \"Europe\",\n \"Canada\": \"North America\",\n \"Mexico\": \"North America\",\n \"United States\": \"North America\",\n }\n\n return country_to_geo_location_mapping.get(country, None)", "def get_country_info(country):\n return GoogleV3().geocode(country)", "def city_country(city, country):\n place = f\"{city}, {country}\"\n return place.title()", "def find_nearest_countries_from_coordinates(countries_coordinates_path,\n user_coordinates):\n data = pandas.read_csv(countries_coordinates_path, sep='\\t')\n latitudes, longitudes = data['latitude'], data['longitude']\n countries = data['name']\n distance_list = []\n for x, y, country in zip(latitudes, longitudes, countries):\n distance = geodesic((x, y), user_coordinates).km\n distance_list.append((distance, country))\n nearest_countries = [elem[1] for elem in sorted(distance_list)][:2]\n try:\n user_country = get_country_from_coordinates(user_coordinates)\n if user_country not in nearest_countries:\n nearest_countries.append(user_country)\n except Exception:\n # if doesn't matter what we fill in user_country, but\n # if it's empty string, there will be an exception later\n user_country = 'Ukraine'\n # If user's country is not USA, but it's near his country,\n # get rid of USA\n if pycountry.countries.search_fuzzy(user_country)[0].alpha_3 != 'USA':\n for country in nearest_countries:\n if pycountry.countries.search_fuzzy(country)[0].alpha_3 == 'USA':\n nearest_countries.remove(country)\n break\n else:\n # There too many filming in USA, get rid of near countries\n return ['USA']\n return nearest_countries", "def country_codes(country):\n countryObject = None\n try:\n countryObject = pycountry.countries.search_fuzzy(country)\n return countryObject[0].alpha_2\n except LookupError:\n pass\n try:\n splittedCountry = country.split(',')[0]\n countryObject = pycountry.countries.search_fuzzy(splittedCountry)\n return countryObject[0].alpha_2\n except LookupError:\n return 'No Code'", "def lookup_country(latitude, longitude):\n r = requests.get(\"https://api.opencagedata.com/geocode/v1/json?q={}+{}&key=1a43cea9caa6420a8faf6e3b4bf13abb\".format(latitude, longitude))\n if r.status_code != 200:\n print(\"Error accessing OpenCage API: {}\".format(r.content))\n return \"Unknown\"\n result = r.json()\n if not \"results\" in result.keys() or len(result[\"results\"]) < 1:\n print(\"No results found\")\n return \"Unknown\"\n components = result[\"results\"][0][\"components\"]\n if not \"country\" in components.keys():\n print(\"Couldn't locate {}N {}E to a country\".format(latitude, longitude))\n return \"Unknown\"\n return components[\"country\"]", "def city_country(city, country):\n formatted_city_country = city.title() + \", \" + country.title() + \".\"\n return formatted_city_country" ]
[ "0.7684879", "0.7317886", "0.7093736", "0.69725704", "0.69260246", "0.67910033", "0.67259896", "0.67130053", "0.6685056", "0.66664284", "0.65944654", "0.6548454", "0.6544576", "0.65261066", "0.6513852", "0.651363", "0.6501452", "0.6493296", "0.64910215", "0.64739454", "0.64675057", "0.6461319", "0.6454813", "0.6446489", "0.64352334", "0.6434451", "0.64331096", "0.6392535", "0.63770217", "0.63731384" ]
0.7679369
1
(set), (str) > (dict) Return a dictionary of locations of the films
def get_films_in_country(film_set, country): film_dict = dict() for film in film_set: try: film_locations = film[1].split(', ') film_country = film_locations[-1] film_city = film_locations[-2] if film_country == country: if film_city in film_dict: film_dict[film_city].add(film[0]) else: film_dict[film_city] = {film[0]} except (TypeError, IndexError, AttributeError): continue return film_dict
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_popular_locations_dict(film_set):\n popular_locations = dict()\n for film in film_set:\n try:\n location = film[1].split(', ')[-1]\n if location in popular_locations.keys():\n popular_locations[location] += 1\n else:\n popular_locations[location] = 1\n except (TypeError, AttributeError, IndexError):\n continue\n\n return popular_locations", "def get_data_from_films_locations_file(path):\n film_locations_data = {}\n with open(path, encoding='utf-8', errors='ignore') as f:\n for line in f:\n line = line.strip()\n line_values = line.split(',')\n film, year, location = line_values[0], line_values[1],\\\n line_values[-1]\n if year in film_locations_data:\n if location not in film_locations_data[year]:\n film_locations_data[year][location] = {film}\n else:\n film_locations_data[year][location].add(film)\n else:\n film_locations_data[year] = {location: {film}}\n return film_locations_data", "def get_films_location(year):\n locations_set = set()\n f = open('locations.list', 'r', encoding='utf-8', errors='ignore')\n for line in f:\n line = line.strip()\n\n try:\n if get_year(line) == str(year):\n name = get_title(line)\n location = get_location(line)\n locations_set.add((name, location))\n except IndexError:\n continue\n return locations_set", "def get_film_locations(input_year):\n film_set = set()\n with open('data/locations.csv', 'r', encoding=\"utf-8\", errors='ignore') as file:\n line = file.readline()\n while line:\n if line.split(',')[1] == input_year and line.split(',')[1] != 'NO DATA':\n film_set.add(tuple([line.split(',')[0].strip(), line.split(',')[-1].strip()]))\n line = file.readline()\n return film_set", "def get_film_coordinates(film_dict):\n coordinate_dict = dict()\n for location in film_dict.keys():\n try:\n locator = geopy.Nominatim(user_agent=\"filmGeocoder\", timeout=10)\n coordinates = locator.geocode(location)\n\n coordinate_dict[coordinates.latitude, coordinates.longitude] = film_dict[location]\n except (TypeError, AttributeError, IndexError):\n continue\n\n return coordinate_dict", "def _vector_mapping(self) -> dict:\n words = set()\n for file in os.listdir(self.processed_path):\n doc_path = f\"{self.processed_path}/{file}\"\n with open(doc_path, 'r') as f:\n text_words = f.readline().split()\n words = words.union(set(text_words))\n words = list(words)\n words.sort()\n\n return dict(zip(words, range(len(words))))", "def castFilmography (movies, minAppearances):\n actors = {}\n for (k,v) in movies.items():\n for a in v[2:7]:\n actors[a] = actors.get(a, []) + [k]\n return sorted([ [k] + v for (k,v) in actors.items() if len(v) >= minAppearances ])", "def get_location_coordinates(films_set, film_number=0):\n if not film_number:\n film_number = len(films_set)\n\n films_list = sorted(list(films_set))\n print(f'List has {len(films_list)} films with specified year. '\n f'\\nAmount of films to analyze: {film_number} '\n f'\\n------------------------------')\n\n locations_loss = 0\n lost_locations = []\n output_list = []\n coordinates_set = set()\n geoloc = Nominatim(user_agent=\"map\")\n print('Loading...')\n for i in range(film_number):\n if '.' in films_list[i][-1]:\n geo_value = geoloc.geocode(films_list[i][-1]\n [films_list[i][-1].find('.'):], timeout=30)\n else:\n geo_value = geoloc.geocode(films_list[i][-1], timeout=30)\n if geo_value is None or \\\n (geo_value.latitude, geo_value.longitude) in coordinates_set:\n locations_loss += 1\n lost_locations.append(films_list[i])\n continue\n time.sleep(1.1)\n coordinates = (geo_value.latitude, geo_value.longitude)\n coordinates_set.add(coordinates)\n output_list.append([films_list[i][0], coordinates])\n print(f\"Lost {locations_loss} locations overall, due to geopy\", lost_locations)\n return output_list", "def films_id(n, dict_votes):\n lst = list(dict_votes.items())[:n]\n lst.sort(key=lambda x: x[1][0], reverse=True)\n rating_set = set(lst)\n return rating_set", "def filenames(self) -> dict[str, str]:\r\n ...", "def get_imdb_list():\n list_file = 'imdb.txt'\n name_column = 26\n f = open(list_file, 'r')\n film_list = []\n pos = 0\n\n for line in f:\n pos += 1\n words = line.split()\n name = line[name_column:-1]\n # could be problematic is there are brackets in the film name\n year = name[name.find('(') + 1:name.find(')')]\n name = name.replace('(' + year + ')', '')\n film = {\n 'pos': pos,\n 'score': Decimal(words[2]),\n 'name': name.strip(),\n 'year': year\n }\n film_list.append(film)\n f.close()\n return film_list", "def find_annotations(forms, files):\n if not type(forms) in [list, tuple]:\n forms = [forms]\n ambiguities = defaultdict(list)\n for file_ in files:\n with open(file_, 'r') as data_file:\n for line in data_file:\n three_first_chars = line[:3]\n if three_first_chars == 'URL':\n line_content = line.split('\\t')\n current_document_url = line_content[1].strip('\\n')\n elif three_first_chars == 'MEN':\n line_content = line.split('\\t')\n mention_title = line_content[-3]\n if mention_title in forms:\n mention_url = line_content[-1].strip('\\n')\n annotation_title = get_wiki_annotation(mention_url)\n annotation_url = 'https://en.wikipedia.org/wiki/{}'.format(annotation_title.replace(' ', '_'))\n ambiguities[annotation_url].append((mention_title, current_document_url))\n\n return ambiguities", "def getVSMSpace():\n sids,documents = getSongTextInfo()\n texts = [[word for word in document.lower().split()] for document in documents]\n dictionary = corpora.Dictionary(texts)\n corpus = [dictionary.doc2bow(text) for text in texts]\n songMap = {}\n index = 0\n for doc in corpus:\n sid = sids[index]\n rMap = {}\n for item in doc:\n wid = item[0]\n count = item[1]\n rMap[wid] = count\n songMap[sid] = rMap\n index += 1\n return songMap", "def _get_genres(self):\n separated = self.movies['genre'].apply(self.separate_genre)\n return {g: True for x in separated for g in x}.keys()", "def get_movies_by_director() -> Dict[str, List[Movie]]:\n movie_data = {}\n with open(os.path.abspath(FILE_PATH), newline='', encoding='utf-8') as in_file:\n for row in csv.DictReader(in_file):\n # keys\n name = row.get(\"director_name\")\n title = row.get(\"movie_title\")\n year = row.get(\"title_year\")\n score = row.get(\"imdb_score\")\n\n # convert\n int_year = 0\n if year:\n try:\n int_year = int(year)\n except ValueError:\n int_year = 0\n\n float_score = 0.0\n if score:\n try:\n float_score = float(score)\n except ValueError:\n float_score = 0.0\n\n # filter\n if int_year > MIN_YEAR:\n if name in movie_data:\n movie = Movie(title=title,\n year=int_year,\n score=float_score)\n movie_data[name].append(movie)\n\n else:\n movie_data[name] = []\n movie = Movie(title=title,\n year=int_year,\n score=float_score)\n movie_data[name].append(movie)\n\n return movie_data", "def insert_file_to_dictionary():\r\n file = open(sys.argv[1], \"r\")\r\n #movies is my the dictionary\r\n movies = {}\r\n for line in file:\r\n read = line.strip().split(', ')\r\n for i in range(1, len(read)):\r\n if not read[i] in movies:\r\n movies[read[i]] = {read[0]}\r\n else:\r\n movies[read[i]].add(read[0])\r\n return movies", "def filna_dict(mes):\n key = [f'pdf_{count + 1}' for count in range(mes)]\n value = ['stans.pdf' for count in range(mes)]\n filna_tobe_inserted = dict(zip(key, value))\n return filna_tobe_inserted", "def get_stats(filtered_paths : dict) -> dict:\n stats_dict = defaultdict(dict)\n for mag in filtered_paths.keys():\n for spec,paths in filtered_paths[mag].items():\n counter = Counter()\n for path in paths:\n img = cv2.imread(path, -1)\n count = Counter(list(img.ravel()))\n counter += count\n stats_dict[mag][spec] = counter\n print(mag)\n return stats_dict", "def get_dict(fname):\n out_set, tot_count = {}, 0\n with open(fname, 'r') as fid:\n word_arr = fid.read().split('\\n')\n for ele in word_arr:\n if len(ele) > 0:\n out_set[(ele.split()[0])] = tot_count\n tot_count += 1\n return out_set", "def getFilms(character):\n\n ret = []\n for film in character.get('films'):\n number = int(film.rstrip('/').rpartition('/')[2])\n if number not in cache:\n response = requests.get(film)\n response = response.json()\n title = response.get('title')\n cache[number] = title\n ret.append(cache.get(number))\n return ret", "def pos():\n pos_list = []\n for token in doc:\n pos_list.append(token.pos_)\n setList = list(set(pos_list))\n my_dict = {i: pos_list.count(i) for i in setList}\n print(my_dict)", "def _create_dictionary(self, document_set):\n words = self._normalize_words(document_set.words)\n unique_words = frozenset(words)\n return dict((word, idx) for idx, word in enumerate(unique_words))", "def get_popular(lookups):\n return {k: lookups.link_counts[k] for k in lookups.movie_to_idx}", "def create_film_lists_dict(film_list):\n film_lists_dict = {}\n for film in film_list:\n if 'disabled' not in film or not film['disabled']:\n # make lists of film types\n # Note, that this means a film can be in several lists\n if 'tags' in film:\n for tag in film['tags']:\n if tag not in film_lists_dict: \n film_lists_dict[tag] = [film]\n else:\n film_lists_dict[tag].append(film)\n return film_lists_dict", "def createset(inputfile):\n\n movie = set()\n user = set()\n count = 0\n #open and read in data from file\n f = open(inputfile)\n for line in f:\n #adding all unique keys to setMovie\n movie.add(line.split()[1])\n #adding all unique users to setUser\n user.add(line.split()[0])\n count+=1\n f.close()\n return movie,user,count", "def set_keyword_map(self):\n \n ret = defaultdict(list)\n for idx, doc in enumerate(self.docs):\n for token in doc:\n if token in self.dictionary.token2id:\n ret[token].append(idx)\n \n self.keyword_map = ret\n return ret", "def compute_idfs(documents):\n idfs = dict()\n total_num_documents = len(documents)\n words = set(word for sublist in documents.values() for word in sublist)\n \n for word in words:\n num_documents_containing_word = 0\n \n for document in documents.values():\n if word in document:\n num_documents_containing_word += 1\n \n idf = math.log(total_num_documents / num_documents_containing_word)\n idfs[word] = idf\n\n return idfs", "def compute_idfs(documents):\n idf={}\n words={}\n # idf= no.of doc/no. of doc in which it lies\n for doc in documents:\n for wrd in set(documents[doc]):\n if wrd.lower() not in words:\n words[wrd.lower()]=0\n words[wrd.lower()]+=1 \n for word in words:\n idf[word]=len(documents)/words[word]\n return idf", "def getTF_IDFSpace():\n sids,documents = getSongTextInfo()\n texts = [[word for word in document.lower().split()] for document in documents]\n dictionary = corpora.Dictionary(texts)\n corpus = [dictionary.doc2bow(text) for text in texts]\n tfidf = models.TfidfModel(corpus)\n corpus_tfidf = tfidf[corpus]\n songMap = {}\n index = 0\n for doc in corpus_tfidf:\n sid = sids[index]\n rMap = {}\n for item in doc:\n wid = item[0]\n count = item[1]\n rMap[wid] = count\n songMap[sid] = rMap\n index += 1\n return songMap", "def check_for_data(self):\n artist_map = {} # map clementine artist name to albums artist id\n albums_map = {} # map clementine artist name to dict that maps\n # clementine album names to albums album ids\n appdata = load_appdata()\n if appdata:\n artist_map, albums_map = appdata\n return artist_map, albums_map" ]
[ "0.67535233", "0.6218466", "0.6067971", "0.5930042", "0.5639073", "0.55344766", "0.5507547", "0.54807436", "0.54286456", "0.53949004", "0.5374464", "0.5364959", "0.53500414", "0.5269479", "0.5232069", "0.52200186", "0.5092616", "0.5092264", "0.5086292", "0.5074272", "0.50742364", "0.505067", "0.5005856", "0.50003207", "0.50000226", "0.49995992", "0.49777716", "0.49756742", "0.49651682", "0.49482396" ]
0.69884044
0
(set) > (dict) Return a dictionary of popular film locations
def get_popular_locations_dict(film_set): popular_locations = dict() for film in film_set: try: location = film[1].split(', ')[-1] if location in popular_locations.keys(): popular_locations[location] += 1 else: popular_locations[location] = 1 except (TypeError, AttributeError, IndexError): continue return popular_locations
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_films_in_country(film_set, country):\n film_dict = dict()\n for film in film_set:\n try:\n film_locations = film[1].split(', ')\n film_country = film_locations[-1]\n film_city = film_locations[-2]\n\n if film_country == country:\n if film_city in film_dict:\n film_dict[film_city].add(film[0])\n else:\n film_dict[film_city] = {film[0]}\n except (TypeError, IndexError, AttributeError):\n continue\n return film_dict", "def get_popular(lookups):\n return {k: lookups.link_counts[k] for k in lookups.movie_to_idx}", "def get_film_locations(input_year):\n film_set = set()\n with open('data/locations.csv', 'r', encoding=\"utf-8\", errors='ignore') as file:\n line = file.readline()\n while line:\n if line.split(',')[1] == input_year and line.split(',')[1] != 'NO DATA':\n film_set.add(tuple([line.split(',')[0].strip(), line.split(',')[-1].strip()]))\n line = file.readline()\n return film_set", "def films_id(n, dict_votes):\n lst = list(dict_votes.items())[:n]\n lst.sort(key=lambda x: x[1][0], reverse=True)\n rating_set = set(lst)\n return rating_set", "def get_data_from_films_locations_file(path):\n film_locations_data = {}\n with open(path, encoding='utf-8', errors='ignore') as f:\n for line in f:\n line = line.strip()\n line_values = line.split(',')\n film, year, location = line_values[0], line_values[1],\\\n line_values[-1]\n if year in film_locations_data:\n if location not in film_locations_data[year]:\n film_locations_data[year][location] = {film}\n else:\n film_locations_data[year][location].add(film)\n else:\n film_locations_data[year] = {location: {film}}\n return film_locations_data", "def castFilmography (movies, minAppearances):\n actors = {}\n for (k,v) in movies.items():\n for a in v[2:7]:\n actors[a] = actors.get(a, []) + [k]\n return sorted([ [k] + v for (k,v) in actors.items() if len(v) >= minAppearances ])", "def get_film_coordinates(film_dict):\n coordinate_dict = dict()\n for location in film_dict.keys():\n try:\n locator = geopy.Nominatim(user_agent=\"filmGeocoder\", timeout=10)\n coordinates = locator.geocode(location)\n\n coordinate_dict[coordinates.latitude, coordinates.longitude] = film_dict[location]\n except (TypeError, AttributeError, IndexError):\n continue\n\n return coordinate_dict", "def num_of_sets(l):\r\n distinct_sweets = set(l) #let's find all distinct sweets from input list\r\n dict_of = {} #empty dict to store key:value (sweet:number of occurrences)\r\n\r\n for i in distinct_sweets:\r\n dict_of[i] = l.count(i)\r\n \r\n key_min = min(dict_of.keys(), key=(lambda k: dict_of[k]))\r\n return dict_of[key_min]", "def get_location_coordinates(films_set, film_number=0):\n if not film_number:\n film_number = len(films_set)\n\n films_list = sorted(list(films_set))\n print(f'List has {len(films_list)} films with specified year. '\n f'\\nAmount of films to analyze: {film_number} '\n f'\\n------------------------------')\n\n locations_loss = 0\n lost_locations = []\n output_list = []\n coordinates_set = set()\n geoloc = Nominatim(user_agent=\"map\")\n print('Loading...')\n for i in range(film_number):\n if '.' in films_list[i][-1]:\n geo_value = geoloc.geocode(films_list[i][-1]\n [films_list[i][-1].find('.'):], timeout=30)\n else:\n geo_value = geoloc.geocode(films_list[i][-1], timeout=30)\n if geo_value is None or \\\n (geo_value.latitude, geo_value.longitude) in coordinates_set:\n locations_loss += 1\n lost_locations.append(films_list[i])\n continue\n time.sleep(1.1)\n coordinates = (geo_value.latitude, geo_value.longitude)\n coordinates_set.add(coordinates)\n output_list.append([films_list[i][0], coordinates])\n print(f\"Lost {locations_loss} locations overall, due to geopy\", lost_locations)\n return output_list", "def get_films_location(year):\n locations_set = set()\n f = open('locations.list', 'r', encoding='utf-8', errors='ignore')\n for line in f:\n line = line.strip()\n\n try:\n if get_year(line) == str(year):\n name = get_title(line)\n location = get_location(line)\n locations_set.add((name, location))\n except IndexError:\n continue\n return locations_set", "def popular():\r\n d = data_loader.vid_patient_tuples_dict\r\n most_popular_videos = []\r\n for k in sorted(d, key=lambda k: len(d[k]), reverse=True):\r\n most_popular_videos.append(k)\r\n return most_popular_videos", "def histogram_genres(our_data):\n genre_list = []\n for album in our_data:\n genre_list.extend(genre.strip() for genre in album['genre'].split(','))\n genre_dict = {}\n for genre in genre_list:\n if genre in genre_dict:\n genre_dict[genre] += 1\n else:\n genre_dict[genre] = 1\n return genre_dict", "def pos():\n pos_list = []\n for token in doc:\n pos_list.append(token.pos_)\n setList = list(set(pos_list))\n my_dict = {i: pos_list.count(i) for i in setList}\n print(my_dict)", "def _get_genres(self):\n separated = self.movies['genre'].apply(self.separate_genre)\n return {g: True for x in separated for g in x}.keys()", "def tag():\n iso_list = []\n tags = [\"spatial_entity\", \"place\", \"motion\", \"location\", \"signal\", \"qslink\", \"olink\"]\n for token in doc:\n if token.norm_ in tags:\n iso_list.append(token.norm_)\n setList = list(set(iso_list))\n my_dict = {i: iso_list.count(i) for i in setList}\n\n for i in tags:\n if i.lower() not in my_dict:\n my_dict[i] = 0\n print(my_dict)", "def neighbors_for_person(person_id):\n movie_ids = people[person_id][\"movies\"]\n neighbors = set()\n for movie_id in movie_ids:\n for person_id in movies[movie_id][\"stars\"]:\n neighbors.add((movie_id, person_id))\n return neighbors", "def neighbors_for_person(person_id):\n movie_ids = people[person_id][\"movies\"]\n neighbors = set()\n for movie_id in movie_ids:\n for person_id in movies[movie_id][\"stars\"]:\n neighbors.add((movie_id, person_id))\n return neighbors", "def neighbors_for_person(person_id):\n movie_ids = people[person_id][\"movies\"]\n neighbors = set()\n for movie_id in movie_ids:\n for person_id in movies[movie_id][\"stars\"]:\n neighbors.add((movie_id, person_id))\n return neighbors", "def directorsOfMostMovies (movies, count):\n directorCounts = {}\n for movieInfo in movies.values():\n key = movieInfo[1]\n if key not in directorCounts:\n directorCounts[key] = 0\n directorCounts[key] += 1\n return sorted([ (v, k) for (k,v) in directorCounts.items() ], reverse=True)[:count]\n # OR:\n # directors = [ x[1] for x in movies.values() ]\n # directorSet = set(directors)\n # return sorted([ (directors.count(d), d) for d in directorSet ], reverse=True)[:count]", "def mel_gene_set(dict): # this uses the flanking genes, specifically\n\tmel_gene_set = set()\n\tfor k, v in dict.iteritems():\n\t\t#v[0] is up, v[1] is down\n\t\t#print \"this is v:\", v\n\t\tfor mg in v[0]:\n\t\t\tmel_gene_set.add(mg)\n\t\tfor mg in v[1]:\n\t\t\tmel_gene_set.add(mg)\n\treturn mel_gene_set", "def most_popular_artist(our_data):\n counter_dict = {}\n for artist in all_artists(our_data):\n if artist in counter_dict:\n counter_dict[artist] += 1\n else:\n counter_dict[artist] = 1\n maximum_albums = max(counter_dict.values())\n artist_lists = []\n for keys, values in counter_dict.items():\n if values == maximum_albums:\n artist_lists.append(keys) \n return artist_lists", "def get_movie_people_relation(title, people_dict, movie_people_dict):\n for item in title:\n for key in people_dict.keys():\n for movie_title in people_dict[key]:\n if item == movie_title:\n if item in movie_people_dict.keys():\n if key not in movie_people_dict[item]:\n movie_people_dict[item] += ',' + key\n else:\n movie_people_dict[item] = key\n else:\n if item not in movie_people_dict.keys():\n movie_people_dict[item] = ''\n return movie_people_dict", "def uniqueDirectors (movies):\n # note, director guaranteed to be in the second spot in movie information list\n return sorted(set([ x[1] for x in movies.values() ]))", "def actorDirectorPairs (movies, count):\n # TODO: complete this function\n import operator\n directorsDict = {}\n for (k,v) in movies.items():\n if v[1] not in directorsDict:\n directorsDict[v[1]] = []\n for actors in v[2:6]:\n directorsDict[v[1]] += [actors]\n actorDirectorList = []\n for director in directorsDict:\n for actor in set(directorsDict[director]):\n actorDirectorList += [((director, actor), directorsDict[director].count(actor))]\n actorDirectorList = [(y,x) for (x,y) in sorted(actorDirectorList)]\n actorDirectorList = sorted(actorDirectorList, key = operator.itemgetter(0), reverse = True)[:count]\n return actorDirectorList", "def createset(inputfile):\n\n movie = set()\n user = set()\n count = 0\n #open and read in data from file\n f = open(inputfile)\n for line in f:\n #adding all unique keys to setMovie\n movie.add(line.split()[1])\n #adding all unique users to setUser\n user.add(line.split()[0])\n count+=1\n f.close()\n return movie,user,count", "def _get_unique_genres(connection):\n print('---Getting unique genres---')\n genreDict = {}\n cursor = connection.cursor()\n cursor.execute(\"SELECT * FROM shared_genres;\")\n res = cursor.fetchall()\n num_genres = 0\n for genre in res:\n if genre[1] not in genreDict:\n genreDict[genre[1]] = num_genres\n num_genres += 1\n return genreDict", "def get_movies(week):\n movies = {}\n for movie in week.find_all('div', class_='venuefilmbloc'):\n movies[movie.a.strong.text] = \"\\n\".join(movie.span.text.split('; '))\n return movies", "def _build_set(self, n_words):\n # count all words\n counter = Counter()\n utterances, labels = self.read_json()\n for utterance in utterances:\n tokens = nltk.word_tokenize(utterance)\n counter.update(tokens)\n\n # generate an int representation\n count = [['UNK', -1]]\n count.extend(counter.most_common(n_words - 1))\n\n # convert the int representation into a dictionary\n dictionary = dict()\n for word, _ in count:\n dictionary[word] = len(dictionary)\n data = list()\n unk_count = 0\n for word in counter.most_common():\n if word in dictionary:\n index = dictionary[word]\n else:\n index = 0 # dictionary['UNK']\n unk_count += 1\n data.append(index)\n count[0][1] = unk_count\n return dictionary", "def bothTopRatedAndGrossing (movies):\n result = {}\n for (k, v) in movies.items():\n # note, only movies that have all fields are in both\n # (7 for cast + 2 for rating + 2 for gross)\n if len(v) == 11:\n result[k] = v\n return result", "def get_all_movies(self):\n cinemaworld_movies, filmworld_movies = self.get_movies()\n\n if cinemaworld_movies is not None:\n self.get_title_map(cinemaworld_movies, \"cinemaworld\")\n if filmworld_movies is not None:\n self.get_title_map(filmworld_movies, \"filmworld\")\n\n return self.title_map" ]
[ "0.7273116", "0.66782707", "0.6225225", "0.6138734", "0.6040904", "0.5757914", "0.5755134", "0.57111007", "0.56822634", "0.5675025", "0.55174416", "0.5513007", "0.550898", "0.54912525", "0.54415333", "0.541234", "0.541234", "0.541234", "0.53981376", "0.53799325", "0.5363322", "0.5333069", "0.53282857", "0.53256965", "0.53246486", "0.53027916", "0.5301474", "0.52352434", "0.5212506", "0.52012277" ]
0.8439863
0
Iterate through all assignments by ``for i in scope.assignments``.
def __iter__(self) -> Iterator[BaseAssignment]: for assignments in self._assignments.values(): for assignment in assignments: yield assignment
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_assignments(self) -> List :\n return self.assignments", "def referents(self) -> Collection[\"BaseAssignment\"]:\n return self.__assignments", "def iterassign(node:_AssingT) -> Iterator[Optional[List[str]]]:\n for target in node.targets if isinstance(node, ast.Assign) else [node.target]:\n dottedname = node2dottedname(target) \n yield dottedname", "def list_assignments(state):\n # TODO: Add support for single-farm listing\n # TODO: also potentially do this by invoking the update cmd\n click.echo(\"Updating farms...\")\n state.farm_manager.update_all_farms()\n click.echo(\"Successfully updated all farms.\\n\")\n\n click.echo(\"Available assignments:\")\n assignments = state.farm_manager.list_farm_assignments()\n click.echo(\"\\n\".join([\"%s: %s\" % x for x in assignments]))", "def iterate_over_assignment(assignment_funct, max_iterations=12, **args):\n args['knowing_minimum'] = 0\n args['knowing_maximum'] = sys.maxsize\n args['maxtime'] = 16 # in secs\n vars = None\n prob_status = pulp.LpStatusNotSolved\n iterations = 0\n while pulp.LpStatusOptimal != prob_status and pulp.LpStatusInfeasible != prob_status and iterations <= max_iterations:\n prob_status, vars = assignment_funct(**args)\n iterations+=1\n return prob_status, vars", "def canvas_api_assignments(state, course_id):\n\n api = state.canvas_api()\n for assign in api.list_assignments(course_id):\n click.echo(str(assign))", "def pass_assign_for_mentor(cls):\n assignments_list = cls.list_from_sql()\n return assignments_list", "def test_list_assignments_for_tree(self):\n # Enable OS-INHERIT extension\n\n test_plan = {\n # Create a domain with a project hierarchy 3 levels deep:\n #\n # project 0\n # ____________|____________\n # | |\n # project 1 project 4\n # ______|_____ ______|_____\n # | | | |\n # project 2 project 3 project 5 project 6\n #\n # Also, create 1 user and 4 roles.\n 'entities': {\n 'domains': {\n 'projects': {'project': [{'project': 2},\n {'project': 2}]},\n 'users': 1},\n 'roles': 4},\n 'assignments': [\n # Direct assignment to projects 1 and 2\n {'user': 0, 'role': 0, 'project': 1},\n {'user': 0, 'role': 1, 'project': 2},\n # Also an inherited assignment on project 1\n {'user': 0, 'role': 2, 'project': 1,\n 'inherited_to_projects': True},\n # ...and two spoiler assignments, one to the root and one\n # to project 4\n {'user': 0, 'role': 0, 'project': 0},\n {'user': 0, 'role': 3, 'project': 4}],\n 'tests': [\n # List all assignments for project 1 and its subtree.\n {'params': {'project': 1, 'include_subtree': True},\n 'results': [\n # Only the actual assignments should be returned, no\n # expansion of inherited assignments\n {'user': 0, 'role': 0, 'project': 1},\n {'user': 0, 'role': 1, 'project': 2},\n {'user': 0, 'role': 2, 'project': 1,\n 'inherited_to_projects': 'projects'}]}\n ]\n }\n\n self.execute_assignment_plan(test_plan)", "def assignments(self):\n if \"assignments\" in self._prop_dict:\n return AssignmentsCollectionPage(self._prop_dict[\"assignments\"])\n else:\n return None", "def assignments(self):\n if \"assignments\" in self._prop_dict:\n return AssignmentsCollectionPage(self._prop_dict[\"assignments\"])\n else:\n return None", "def variableIter(self):\n for (para, start), variable in self.variables.iteritems():\n yield para, start, variable", "def __iter__(self) -> Iterator[Access]:\n for accesses in self._accesses.values():\n for access in accesses:\n yield access", "def __iter__(self) -> Iterable[MemoryVariable]:\n return iter(self.variables)", "def assign_scope(from_scope, to_scope):\n assigns = []\n to_vars = variables.trainable_variables(to_scope)\n from_vars = variables.trainable_variables(from_scope)\n for dst, src in zip(to_vars, from_vars):\n assigns.append(state_ops.assign(dst, src))\n return control_flow_ops.group(*assigns)", "def iteration(self) -> global___Statement.Iteration:", "def iteration(self) -> global___Statement.Iteration:", "def multiple_eval_for_loops_v1():", "def parameter_assignments(self, parameter_assignments):\n\n self._parameter_assignments = parameter_assignments", "def test_list_effective_assignments_for_tree_with_domain_assignments(self):\n test_plan = {\n # Create a domain with a project hierarchy 3 levels deep:\n #\n # project 0\n # ____________|____________\n # | |\n # project 1 project 4\n # ______|_____ ______|_____\n # | | | |\n # project 2 project 3 project 5 project 6\n #\n # Also, create 1 user and 4 roles.\n 'entities': {\n 'domains': {\n 'projects': {'project': [{'project': 2},\n {'project': 2}]},\n 'users': 1},\n 'roles': 4},\n 'assignments': [\n # An inherited assignment on the domain (which should be\n # applied to all the projects)\n {'user': 0, 'role': 1, 'domain': 0,\n 'inherited_to_projects': True},\n # A direct assignment to project 2\n {'user': 0, 'role': 2, 'project': 2},\n # ...and two spoiler assignments, one to the root and one\n # to project 4\n {'user': 0, 'role': 0, 'project': 0},\n {'user': 0, 'role': 3, 'project': 4}],\n 'tests': [\n # List all effective assignments for project 1 and its subtree.\n {'params': {'project': 1, 'effective': True,\n 'include_subtree': True},\n 'results': [\n # The inherited assignment from the domain should appear\n # only on the part of the subtree we are interested in\n {'user': 0, 'role': 1, 'project': 1,\n 'indirect': {'domain': 0}},\n {'user': 0, 'role': 1, 'project': 2,\n 'indirect': {'domain': 0}},\n {'user': 0, 'role': 1, 'project': 3,\n 'indirect': {'domain': 0}},\n # And finally the direct assignment on project 2\n {'user': 0, 'role': 2, 'project': 2}]}\n ]\n }\n\n self.execute_assignment_plan(test_plan)", "def iterAliases(self):\n return iter(self.alias_to_namespace)", "def __iter__(self):\n return iter(self._vars)", "def enumerate(self):\n\n # Print out a message\n\n print(\"Beginning the enumeration of support sets\\n\")\n\n # Localize the assignment variable table\n\n asgvar = self.assignment_variables\n\n # Initialize set of all vertices as those which have not had their\n # support sets fully enumerated\n\n unfinished = set(asgvar.keys())\n pbar = tqdm.tqdm(total=len(unfinished))\n\n # Initialize support sets to be empty\n\n support = {u: set() for u in unfinished}\n\n # Loop until we are done with the enumeration\n\n while True:\n\n # If unfinished is now empty, break\n\n if len(unfinished) == 0:\n\n # Close the progress bar and leave a newline\n pbar.close()\n print()\n\n # Return the computed support sets\n return support\n\n # Select an unfinished vertex at random\n\n focus = random.sample(unfinished, 1)[0]\n\n # Force this vertex to take an as yet unseen assignment\n\n for seen in support[focus]:\n self.add_aux_clause([-asgvar[focus][seen]])\n\n # Run the solver\n\n result = self.solve()\n self.flush() # Delete aux clauses\n\n if result:\n\n # Update support sets\n\n for vtype, alpha, beta in result:\n if vtype == Formula.ASG_VAR:\n support[alpha].add(beta)\n\n else:\n\n # We are done with this vertex, so remove it from unfinished\n # and lock it to its known assignments\n pbar.update()\n unfinished.remove(focus)\n self.add_clause([asgvar[focus][s] for s in support[focus]])", "def test_list_effective_assignments_for_tree(self):\n test_plan = {\n # Create a domain with a project hierarchy 3 levels deep:\n #\n # project 0\n # ____________|____________\n # | |\n # project 1 project 4\n # ______|_____ ______|_____\n # | | | |\n # project 2 project 3 project 5 project 6\n #\n # Also, create 1 user and 4 roles.\n 'entities': {\n 'domains': {\n 'projects': {'project': [{'project': 2},\n {'project': 2}]},\n 'users': 1},\n 'roles': 4},\n 'assignments': [\n # An inherited assignment on project 1\n {'user': 0, 'role': 1, 'project': 1,\n 'inherited_to_projects': True},\n # A direct assignment to project 2\n {'user': 0, 'role': 2, 'project': 2},\n # ...and two spoiler assignments, one to the root and one\n # to project 4\n {'user': 0, 'role': 0, 'project': 0},\n {'user': 0, 'role': 3, 'project': 4}],\n 'tests': [\n # List all effective assignments for project 1 and its subtree.\n {'params': {'project': 1, 'effective': True,\n 'include_subtree': True},\n 'results': [\n # The inherited assignment on project 1 should appear only\n # on its children\n {'user': 0, 'role': 1, 'project': 2,\n 'indirect': {'project': 1}},\n {'user': 0, 'role': 1, 'project': 3,\n 'indirect': {'project': 1}},\n # And finally the direct assignment on project 2\n {'user': 0, 'role': 2, 'project': 2}]}\n ]\n }\n\n self.execute_assignment_plan(test_plan)", "def __iter__(self):\n yield self._extent.members()\n yield self._intent.members()", "def buildProcessesOutOfAssignments(self):\n assigments = where(self.startsOfDataPaths,\n lambda x: isinstance(x, Assignment)\n )\n for sig, dps in groupedby(assigments, lambda x: x.dst):\n dps = list(dps)\n name = \"\"\n if not sig.hasGenericName:\n name = sig.name\n sig.hidden = False\n \n # render sequential statements in process\n # (conversion from netlist to statements)\n for stm in renderIfTree(dps):\n p = HWProcess(\"assig_process_\" + name)\n if sig._useNopVal and not isEnclosed(stm):\n n = sig._nopVal\n p.statements.append(Assignment(n, sig))\n if isinstance(n, RtlSignal):\n p.sensitivityList.add(n)\n \n p.statements.append(stm)\n sensitivity = discoverSensitivity(stm)\n p.sensitivityList.update(sensitivity)\n for s in p.sensitivityList:\n s.hidden = False\n\n yield p", "def itervaluerefs(self):\n for value in self.itervalues():\n yield ref(value)", "def __iter__(self):\n return iter(vars(self.obj))", "def fetch_current_user_assignments(s):", "def test_list_role_assignments_unfiltered(self):\n test_plan = {\n # Create a domain, with a user, group & project\n 'entities': {'domains': {'users': 1, 'groups': 1, 'projects': 1},\n 'roles': 3},\n # Create a grant of each type (user/group on project/domain)\n 'assignments': [{'user': 0, 'role': 0, 'domain': 0},\n {'user': 0, 'role': 1, 'project': 0},\n {'group': 0, 'role': 2, 'domain': 0},\n {'group': 0, 'role': 2, 'project': 0}],\n 'tests': [\n # Check that we get back the 4 assignments\n {'params': {},\n 'results': [{'user': 0, 'role': 0, 'domain': 0},\n {'user': 0, 'role': 1, 'project': 0},\n {'group': 0, 'role': 2, 'domain': 0},\n {'group': 0, 'role': 2, 'project': 0}]}\n ]\n }\n self.execute_assignment_plan(test_plan)", "def iteridents(self):\n raise NotImplementedError" ]
[ "0.60471636", "0.5899407", "0.5572281", "0.5553273", "0.5537758", "0.55002826", "0.5477298", "0.5473074", "0.5432755", "0.5432755", "0.539908", "0.53967327", "0.53259605", "0.5308212", "0.525584", "0.525584", "0.51709706", "0.51604265", "0.5146417", "0.51436704", "0.51351035", "0.5131847", "0.5125291", "0.51024127", "0.5101826", "0.50932395", "0.50863165", "0.5070139", "0.50657266", "0.50602794" ]
0.7552211
0