query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Accepts a list of items and a rectangular distance DataTable. The item indexes match those of the distance_table dims. We will sort the items s.t. for each item the next one is the nearest one not already chosen.
def greedy_distance_sort(distance_table, items_to_sort): ret = [items_to_sort[0]] while len(ret) < len(distance_table.dims): # find item nearest to the last one in the list last_item_index = items_to_sort.index(ret[-1]) distances = distance_table.get_points(distance_table.dims[last_item_index]) min_value = np.inf min_index = None for i,distance in enumerate(distances): if items_to_sort[i] in ret: continue if distance < min_value: min_value = distance min_index = i ret += [items_to_sort[min_index]] return ret
[ "def match_ref_items(ref_items, items, diff_fun, tol):\n assert len(items) == len(ref_items), 'items and ref_items must be same len'\n assert type(items) is np.ndarray, 'items must be a numpy array'\n assert type(ref_items) is np.ndarray, 'ref_items must be a numpy array'\n\n diff = diff_fun(ref_items, items)\n ref_ind = np.arange(len(items))\n if all(diff < tol):\n return ref_ind, diff\n # sort diff in descending order\n indS = np.argsort(diff)[::-1]\n Nmismatch = np.where(diff[indS] > tol)[0][-1] + 1\n ind_mismatch = indS[0:Nmismatch]\n items_mismatch = items[ind_mismatch]\n ref_items_mismatch = ref_items[ind_mismatch]\n swap_hist = np.arange(Nmismatch)\n # determine dimensionality of items to allow proper tiling to compare items\n # and ref_items\n items_tile_reps = np.repeat(1, items.ndim)\n # Dont need to go to end, just end-1\n for swap_ind in range(Nmismatch):\n # Step through each mismatched item and compare with remaining\n # unmatched ref_items\n curr_item = items_mismatch[swap_ind]\n prop_ref_items = ref_items_mismatch[swap_hist[swap_ind:]]\n # ensure tile repeat number matches the number of remaining\n # unmatched ref_items\n items_tile_reps[0] = Nmismatch-swap_ind\n prop_diff = diff_fun(np.tile(curr_item, items_tile_reps),\n prop_ref_items)\n # swap indices to store item pair with the minimum difference\n swap_target = np.argmin(prop_diff)+swap_ind\n (swap_hist[swap_ind], swap_hist[swap_target]) = \\\n (swap_hist[swap_target], swap_hist[swap_ind])\n ref_ind[ind_mismatch] = ind_mismatch[swap_hist]\n diff = diff_fun(ref_items[ref_ind], items)\n assert all(np.abs(diff) < tol), 'diff must all be less than tol'\n return ref_ind, diff", "def sort_locations(loc1,loc2):\n distancelist = [] #List for both arrays\n for locations in [loc1,loc2]:\n nbrs = NearestNeighbors(n_neighbors=4, algorithm='ball_tree').fit(np.array(locations))\n distances, indices = nbrs.kneighbors(np.array(locations))\n distancelist.append(distances)\n newloc1 = []\n newloc2 = []\n for i in range(len(loc1)):\n index, sucess = match_row(distancelist[1],distancelist[0][i,:])\n if sucess:\n newloc1.append(loc1[i])\n newloc2.append(loc2[index])\n return newloc1, newloc2", "def sort_coord2coord_list():\r\n for index in range(len(coord2coord_list) - 1, 0, -1):\r\n for subindex in range(index):\r\n if coord2coord_list[subindex].dist > coord2coord_list[subindex + 1].dist:\r\n temp = coord2coord_list[subindex]\r\n coord2coord_list[subindex] = coord2coord_list[subindex + 1]\r\n coord2coord_list[subindex + 1] = temp", "def sort_by_distance(data):\n data.sort_values(by = ['DistanceFromUser'], inplace = True)", "def sort_distances(distances):\n\tsorted_distances = sorted(distances, key=lambda by_distance:by_distance[0])\n\n\treturn sorted_distances", "def get_closest_item(self, distance_dict):\n min_item, min_dist = None, 3000\n for key, value in distance_dict.items():\n if value < min_dist:\n min_item, min_dist = key, value\n\n return min_item", "def get_closest_seq_pair_dist_seqan(self, seq_list_1, seq_list_2, distance_units='edit_distance'):\n distances = []\n for seq1 in seq_list_1:\n for seq2 in seq_list_2:\n distance = self.get_dist_between_rep_seqs_seqan(seq1, seq2, distance_units=distance_units)\n distances.append(distance)\n return min(distances)", "def calculate_distances_euclidean(query_vector, data_vectors):\n distances = np.array(\n euclidean_distances(query_vector, data_vectors)[0]) # result is [[ data ]], so get idx 0 to have [ data ]\n\n distances_sorted = distances.argsort() + 1 # argsort will return a sorted list of indices of the original data (+1 because documents are indexed from 1)\n return distances_sorted", "def sort_by_distance(self, lon, lat, points):\n\n # convert 'points' list to just [(lon,lat), ...]\n points = [(x[1],x[2]) for x in points]\n\n # start the result list\n result = []\n\n current = (lon, lat)\n while points:\n result.append(current)\n\n # remove 'current' from 'points' list\n points.remove(current)\n if len(points) < 1:\n break\n\n # figure out which point in 'points' is closest to last result.\n # leave 'index' as the index of closest point\n index = None\n distance = 9999999999.\n (old_x, old_y) = current\n for (i, pt) in enumerate(points):\n (new_x, new_y) = pt\n dist_square = ((new_x-old_x)*(new_x-old_x) +\n (new_y-old_y)*(new_y-old_y))\n if dist_square < distance:\n index = i\n distance = dist_square\n\n # prepare to return the next closest\n current = points[index]\n\n # exit edit mode\n self.btn_AOI_edit()\n\n return result", "def multiple_pops_similarity(each_distance_before,distances_of_pops,number_of_pop):\n each_distance_before = each_distance_before[np.triu_indices(number_of_pop, k = 1)]\n distances_of_pops = np.asarray(distances_of_pops)\n tri = np.zeros((number_of_pop,number_of_pop))\n tri[np.triu_indices(number_of_pop,1)] = distances_of_pops\n \n\n before_result_max = np.where(each_distance_before == np.amax(each_distance_before))\n before_result_min = np.where(each_distance_before == np.amin(each_distance_before))\n after_result_min = np.where(distances_of_pops == np.amin(distances_of_pops))\n \n \n max_elements = []\n \n if len(before_result_min[0])==1 and len(after_result_min[0])==1 and before_result_min == after_result_min:\n for i in before_result_max[0]:\n max_elements.append(distances_of_pops[i])\n \n for pos,row in enumerate(tri[:-1]):\n max_difference = -1\n m = np.min(row[np.nonzero(row)])\n \n for i in row:\n diff=subtract_float(i,m)\n if diff > max_difference:\n max_difference = diff\n \n for next_row in tri[pos+1:]:\n max_next = max(next_row)\n if max_next > m: #if max(next_row) > min(previous_row)\n return 0 \n diff=abs(subtract_float(max_next,m))\n \n \n if diff <= max_difference:\n return 0\n return 1\n else:\n print('eixe polles mikres times')\n return 0", "def sort_by_distance(self, v, others):\n t = [(self.distance_between(v, w), w) for w in others]\n t.sort()\n return [w for (d, w) in t]", "def _sort_positions(\n self, matches: Iterator[PositionResult]\n ) -> Tuple[List[PositionResult], int]:\n results: List[PositionResult] = []\n max_len = None\n min_closest = None\n prev_result = None\n for match in matches:\n item_length = match.last_idx - match.first_idx\n if prev_result is None:\n dist_to_prev = None\n else:\n dist_to_prev = match.first_idx - prev_result.last_idx\n # first set the current match to the choice\n # if it is longer than remainders\n if max_len is None or item_length > max_len:\n max_len = item_length\n results.insert(0, match)\n if isinstance(dist_to_prev, int):\n if min_closest is None or dist_to_prev < min_closest:\n min_closest = dist_to_prev\n # only change current result if the length of the phrase\n # is not less than the max length\n if item_length == max_len:\n results.insert(0, match)\n prev_result = match\n # don't insert twice\n if results[0] != match:\n results.append(match)\n # this maps distance to a guaranteed number and favors words with multiple items\n num_dist = min_closest if min_closest is not None else sys.maxsize\n # above technically returns an optional position, but it's\n # a private method that only runs when the position isn't none\n return results, num_dist # type: ignore", "def get_closest_seq_pair_dist(self, seq_list_1, seq_list_2, temp_dirpath, path_to_needle, distance_units='edit_distance'):", "def sort_by_value_per_weight(items):\n # convert tuples into dataframe to vectorise calculations\n df = pd.DataFrame(items, columns=['index', 'value', 'weight'])\n # calculate value/weight ratio for each item\n df[\"v_w_ratio\"] = df.value / df.weight\n # sort dataframe by value/weight ratio then by weight to get the\n # lightest items first if there are equal weights\n df.sort_values([\"v_w_ratio\", \"weight\"],\n ascending=[False, True], inplace=True)\n # convert table back into list of named tuples\n lst_items = list(iter_named_tuples(df))\n # update items\n return lst_items", "def create_distance_field(entity_list):\n # create grid using grid width and height\n grid = [[1000 for x in range(GRID_WIDTH)] for y in range(GRID_HEIGHT)]\n # iterate through grid positions:\n for x in range(GRID_HEIGHT):\n print('x=', x)\n for y in range(GRID_WIDTH):\n print('y=', y)\n # compare distances to each entity\n for ent in entity_list:\n dist = manhattan_distance(x, y, ent[0], ent[1]) #abs(x - ent[0]) + abs(y - ent[1])\n print(dist)\n if dist < grid[x][y]:\n grid[x][y] = dist\n # mark position as smallest number from entity\n return grid", "def get_distances(game, loc):\n blanks = game.get_blank_spaces()\n # Initialize all distances with max posible distance \n distances = [float(\"inf\") for i in range(game.height * game.width)]\n row, col = loc\n queue = [(row, col)]\n # Initial location is at 0 distance\n distances[row + col * game.height] = 0\n while len(queue) > 0:\n row, col = queue.pop(0)\n dist = distances[row + col * game.height]\n # Iterate over each possible move in every direction \n for dr, dc in directions:\n next_r = row + dr\n next_c = col + dc\n # Check if next location is not out of bounds\n if 0 <= next_r < game.height and 0 <= next_c < game.width:\n index = next_r + next_c * game.height\n # Check if next location is available\n if (next_r, next_c) in blanks:\n #Check if next location has not been found before\n if dist + 1 < distances[index]:\n distances[index] = dist + 1\n #Continue searching from next location\n queue.append((next_r, next_c))\n\n return distances", "def matrix_best_items(df, tag_list):\n # We create a list with all the items we have\n all_tags = tag_list\n\n # This will be the matrix to store the results\n tag_matrix = []\n\n # We iterate through the list of items\n for tag_n in all_tags:\n tag_row = []\n\n # We find the id's of the orders where this item appears\n names_n = list(df[df['tags'] == tag_n]['Name'])\n # For each element, we iterate through all the elements\n for tag_m in all_tags:\n # We find the id's of the orders where this second item appears\n names_m = list(df[df['tags'] == tag_m]['Name'])\n # We calculate the relative frequency of the second item over the times the first item apears\n value = len(set(names_n).intersection(set(names_m))) / len(set(names_n).union(set(names_m)))\n tag_row.append(value)\n tag_matrix.append(tag_row)\n\n matrix = pd.DataFrame(tag_matrix, columns=all_tags)\n matrix['item'] = all_tags\n matrix = matrix.set_index('item')\n return matrix", "def nearest_neighbors(\n input_maps: torch.Tensor,\n candidate_maps: torch.Tensor,\n distances: torch.Tensor,\n num_matches: int,\n) -> Tuple[torch.Tensor, torch.Tensor]:\n\n if num_matches is None or num_matches == -1 or num_matches > input_maps.size(1):\n num_matches = input_maps.size(1)\n\n # Find nearest neighbour of each input element in the candidate map\n topk_values, topk_indices = distances.topk(\n k=1, dim=2, largest=False\n ) # [bsz, input_map_size, 1]\n topk_values = topk_values.squeeze(-1) # [bsz, input_map_size]\n\n # Select num_matches neighbors pairs having the lowest distance value.\n _, min_indices = topk_values.topk(\n k=num_matches, dim=1, largest=False\n ) # [bsz, num_matches]\n\n # Create the filtered input map with num_matches lowest distance values.\n feature_dimension = input_maps.shape[2]\n filtered_input_maps = torch.gather(\n input_maps, 1, min_indices.unsqueeze(-1).expand(-1, -1, feature_dimension)\n ) # [bsz, num_matches, feature_dimension]\n\n # Create candidate maps in the same way as input maps, but using corrispondent candidate values\n selected_candidate_maps = torch.gather(\n candidate_maps, 1, topk_indices.expand(-1, -1, feature_dimension)\n ) # [bsz, input_map_size, feature_dimension]\n filtered_candidate_maps = torch.gather(\n selected_candidate_maps,\n 1,\n min_indices.unsqueeze(-1).expand(-1, -1, feature_dimension),\n ) # [bsz, num_matches, feature_dimension]\n\n return filtered_input_maps, filtered_candidate_maps", "def test_filter_by_distance(self):\n\n threshold = 1\n points = random.uniform(-1,1,size=(100,6))\n points = mathtools.filter_by_distance(points, threshold)\n \n for point in points:\n dif = points[:,0:3]-point[0:3]\n euclidean_distance = sum(dif*dif,1)\n euclidean_distance = euclidean_distance[euclidean_distance>=1e-6] # excluding the evaluated point from list\n nearer_point = argmin(euclidean_distance)\n self.assertTrue(min(euclidean_distance)>=threshold**2,\n msg = \"The points: \"+str(point)+\" and \"+str(points[nearer_point])+\" are too close\"\n )" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the empty list of outputs for this module.
def get_outputs(self): return []
[ "def outputs(self) -> List[Node]:\n return self._outputs", "def get(cls) -> typing.List[Output]:\n return cls._outputs", "def list_output_modules(self):\n try:\n return self._send_command(self._client.list_output_modules)\n except AttributeError:\n return ()\n except speechd.SSIPCommandError:\n return ()", "def cls_list_outputs(cls):\n return [k for k, v in cls.__class_traits__.iteritems() if v.iotype == 'out' and k not in Component.__class_traits__ and not v.vartypename == None]", "def ListOutputModules(self):\n self.PrintHeader(u'Output Modules')\n manager = output_manager.OutputManager\n for name, description in manager.GetOutputs():\n self.PrintColumnValue(name, description, 10)\n self.PrintSeparatorLine()", "def output_tags(cls):\n return [tag for tag,_ in cls.outputs]", "def getTransactionOutputList(self)-> list:\n return self.__transactionOutputList", "def list_output_artifacts(\n self) -> List[materialized_artifact.MaterializedArtifact]:\n return list(self.outputs.values())", "def getIgnoredOutputModules(self):\n\n if hasattr(self.data.output, 'ignoredModules'):\n return self.data.output.ignoredModules\n return []", "def get_output_nodes(self) -> Optional[List[Any]]:\n self.guard_requirements_installed()\n\n # pylint: disable=maybe-no-member\n return self.lpot_model_instance.output_node_names + [\"custom\"]", "def registered_output_names(self):\r\n return self._registered_output_node_names", "def all_outputs(self):\n all_outputs = {}\n for plug in self.outputs.values():\n all_outputs[plug.name] = plug\n for sub in plug.sub_plugs.values():\n all_outputs[sub.name] = sub\n return all_outputs", "def get_output(self):\n\n if self.flag:\n self.flag = False\n return self.objects\n else:\n return False", "def all_output_artifacts(self):\n return utils.unique(self._filter_artifact(False, Artifact), lambda item: item.id)", "def __getOutputs(self, inDictionary):\n outputs = []\n for out in inDictionary['Output']:\n if not isinstance(out, OutStreamEntity):\n outputs.append(out)\n return outputs", "def get_output_details(self):\n return [\n self._get_tensor_details(i, subgraph_index=0)\n for i in self._interpreter.OutputIndices()\n ]", "def all_output_result_files(self):\n return [output for _, output in self.all_artifacts()\n if output.generation_type == output.PER_INPUT]", "def output(self):\n lines = []\n with open(self._temp_file_name) as file:\n line = file.readline()\n while line:\n lines.append(line)\n line = file.readline()\n return lines", "def all_output_analytes(self):\n return [x for x in self.all_output_artifacts() if isinstance(x, Analyte)]" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The view method of this module draws the control panel and the histograms. We need at least one input to be able to draw something.
def view(self, tables): if not tables: return View(self, 'No tables to show.') self.widgets.color.guess_or_remember(('histogram text', tables), ['name']) self.widgets.text.guess_or_remember(('histogram colors', tables), ['name']) self.widgets.shift.guess_or_remember(('histogram shift', tables), '0.2') self.widgets.sort_inside.guess_or_remember(('histogram sort inside', tables), ['similarity']) self.widgets.sort_outside.guess_or_remember(('histogram sort outside', tables), ['sort']) self.widgets.trim.guess_or_remember(('histogram trim', tables), ['no']) self.widgets.trim_thresh.guess_or_remember(('histogram trim thresh', tables), '0') sort_inside_options = [('unsort', 'Keep original order'), ('similarity', 'Put similar curves together')] sort_inside_options += [(x, 'Sort by %s' % x) for x in tables[0].tags.keys()] # Create the control panel view. This will enable users to choose the dimensions. control_panel_view = stack_lines( self.widgets.dims.view('Dimension', self.widgets.apply, options_from_table(tables[0])), self.widgets.text.view('Text by', self.widgets.apply, tables[0].tags.keys()), self.widgets.color.view('Color by', self.widgets.apply, tables[0].tags.keys()), self.widgets.shift.view('Shift for multiple curves', self.widgets.apply), self.widgets.sort_inside.view('Curve sorting', self.widgets.apply, sort_inside_options, multiple=False), self.widgets.sort_outside.view('Plot sorting', self.widgets.apply, [('sort', 'Put plots with many differences first'), ('unsort', 'Keep original order')], multiple=False), self.widgets.trim.view('Trim plots', self.widgets.apply, [('yes', 'Convert values lower than threshold to 0'), ('no', 'Don\'t trim')], multiple=False), self.widgets.trim_thresh.view('Trim threshold', self.widgets.apply), self.widgets.apply.view()) main_views = [] shift = self.widgets.shift.value_as_float() plots_for_legend = OrderedDict() colorer = axes.Colorer() # Check that the user has already chosen dimensions. Otherwise, ask him # to do so. if self.widgets.dims.values.choices: timer = MultiTimer(len(self.widgets.dims.values.choices)) for i, dim in enumerate(self.widgets.dims.values.choices): try: # Go over every dimension and create the histogram: # First create a new figure: fig = self.create_and_adjust_figure(tables) ax = fig.add_subplot(111) # Draw the histogram for every input plots = [] sorted_tables = tables sort_method = self.widgets.sort_inside.values.choices[0] if sort_method == 'unsort': sorted_tables = tables elif sort_method == 'similarity': thresh = None if self.widgets.trim.get_choices()[0] == 'yes': thresh = self.widgets.trim_thresh.value_as_float() # get distances table: distances = datatable.ks_distances(tables, dim, thresh) # sort by distance sorted_tables = greedy_distance_sort(distances, tables) else: # we need to sort by tags: tag_for_sort = self.widgets.sort_inside.values.choices[0] sorted_tables = sorted(tables, key=lambda table: table.tags[tag_for_sort]) for i, table in enumerate(sorted_tables): color_tags = self.widgets.color.values.choices color_key = tuple([table.tags[c] for c in color_tags]) min_x = None if self.widgets.trim.get_choices()[0] =='yes': min_x = self.widgets.trim_thresh.value_as_float() plot = axes.kde1d(ax, table, dim, color=colorer.get_color(color_key), min_x=min_x, shift=shift*i) plots_for_legend[color_key] = plot # Add ticks with table names: if self.widgets.shift.value_as_float() > 0: ax.set_yticks(np.arange(0, len(tables)*shift, shift)) ax.set_yticklabels([t.get_tags(self.widgets.text.values.choices) for t in sorted_tables], size='xx-small') # set axes y range: ax.set_ylim(bottom = -0.1, top=0.8+shift*(len(sorted_tables)-1)) # Make sure we don't create the same widget twice. We create a new widget # for every dimension asked. widget_key = self._normalize_id(dim) if not widget_key in self.widgets: self._add_widget(widget_key, Figure) figure_widget = self.widgets[widget_key] if len(tables) > 1: from scipy.stats import ks_2samp ks, p_ks = ks_2samp(tables[0].get_cols(dim)[0], tables[1].get_cols(dim)[0]) ks_view = View(self, 'ks: %.3f, p_ks: %.10f' % (ks, p_ks)) final_view = stack_lines(ks_view, figure_widget.view(fig)) else: ks, p_ks = 0, 0 final_view = figure_widget.view(fig) # Add the new widget's view main_views.append((ks, p_ks, final_view)) except Exception as e: logging.exception('Exception when drawing histogram') main_views.append((0, 0, View(self, str(e)))) timer.complete_task(dim) # sort by the ks test: main_views = sorted(main_views, key=itemgetter(0), reverse=True) main_views = [v[2] for v in main_views] # create legend: legened_titles = plots_for_legend.keys() print len(legened_titles) max_title_len = max([len(str(t)) for t in legened_titles] + [0]) print max_title_len WIDTH_PER_LETTER = 7 EXTRA_WIDTH = 60 HEIGHT_PER_LINE = 30 EXTRA_HEIGHT = 50 MIN_X = 300 MIN_Y = 100 legend_x = max(MIN_X, EXTRA_WIDTH + WIDTH_PER_LETTER * max_title_len) legend_y = max(MIN_Y, EXTRA_HEIGHT + HEIGHT_PER_LINE * len(legened_titles)) fig = axes.new_figure(legend_x, legend_y) ax = fig.add_subplot(111) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) ax.legend(plots_for_legend.values(), plots_for_legend.keys(), loc='center', mode='expand', frameon=False, prop={'size' : 'xx-small'}) main_views = [self.widgets.legend_figure.view(fig)] + main_views main_view = view.stack_left(*main_views) else: main_view = View(None, 'Please select dimensions') # combine the control panel and the main view togeteher: return self.widgets.layout.view(main_view, control_panel_view)
[ "def draw(self, view):\n super().draw()", "def show_plot(self, e):\n plots = plotting.Input(self.name)\n #if user pick in Plot Units section 'Rate' and 'Spectrum', plot:\n if self.var.get() == 'Rate':\n if e == 'spec':\n plots.plot_spectrum_rate()\n #Rate and Time Profile:\n elif e == 'time':\n plots.rate_vs_time_plotting()\n #Rate and Time Spectrogram:\n elif e == 'specgr':\n plots.plot_spectrogram_rate()\n #if 'Counts' and 'Spectrum', plot:\n if self.var.get() == 'Counts':\n if e == 'spec':\n plots.plot_spectrum_counts()\n #if 'Counts' and 'Time Profile', plot:\n elif e == 'time':\n plots.counts_vs_time_plotting()\n #if 'Counts' and 'Spectrogram', plot:\n elif e == 'specgr':\n plots.plot_spectrogram_counts()\n #if 'Flux' and 'Spectrum', plot:\n if self.var.get() == 'Flux':\n if e == 'spec':\n plots.plot_spectrum_flux()\n #if 'Flux' and 'Time Profile', plot:\n elif e == 'time':\n plots.flux_vs_time_plotting()\n #if 'Flux' and 'Spectrogram', plot:\n elif e == 'specgr':\n plots.plot_spectrogram_flux()", "def graphic_window(self):", "def draw(self): \n self.drawPanel()\n self.drawPanelContents()\n self.changed = True", "def view_handler(self, e):\n self.toggle_view(e) # configures the window to reflect the view mode\n self.show_graph() # replots the graph", "def visualize(self):\n plt.show()", "def draw(self) -> None:\n\n \"\"\"\n TODO: Add logic for handling multiple draw functions\n \"\"\"\n pass", "def _init_plots(self):\n handle_dict = {}\n nans = np.zeros((1, 2), dtype=float)\n nans.fill(np.nan)\n n_steps = self.data_config['sequence_length'] - 1\n ########################################################################\n # Configuration dictionaries\n ########################################################################\n for config in [self.run_config, self.train_config, self.model_config, self.data_config]:\n plot_config(self.vis, config)\n ########################################################################\n # Total free energy, conditional log likelihood, KL divergence\n ########################################################################\n handle_dict['fe'] = plot_line(self.vis, nans, np.ones((1, 2)), legend=['Train', 'Val'],\n title='Total Free Energy', xlabel='Epochs',\n ylabel='Free Energy (Nats)', xformat='log', yformat='log')\n handle_dict['cll'] = plot_line(self.vis, nans, np.ones((1, 2)), legend=['Train', 'Val'],\n title='Total Conditional Log Likelihood', xlabel='Epochs',\n ylabel='Conditional Log Likelihood (Nats)',\n xformat='log', yformat='log')\n handle_dict['kl'] = plot_line(self.vis, nans, np.ones((1, 2)), legend=['Train', 'Val'],\n title='Total KL Divergence', xlabel='Epochs',\n ylabel='KL Divergence (Nats)', xformat='log', yformat='log')\n ########################################################################\n # Per step free energy, conditional log likelihood, KL divergence\n ########################################################################\n step_legend = []\n for split in ['Train', 'Val']:\n for step_num in range(1, n_steps + 1):\n step_legend.append(split + ', Step ' + str(step_num))\n handle_dict['fe_step'] = plot_line(self.vis,\n nans.repeat(n_steps, 1),\n np.ones((1, 2 * n_steps)),\n legend=step_legend,\n title='Per Step Free Energy',\n xlabel='Epochs',\n ylabel='Free Energy (Nats)',\n xformat='log', yformat='log')\n handle_dict['cll_step'] = plot_line(self.vis,\n nans.repeat(n_steps, 1),\n np.ones((1, 2 * n_steps)),\n legend=step_legend,\n title='Per Step Conditional Log Likelihood',\n xlabel='Epochs',\n ylabel='Conditional Log Likelihood (Nats)',\n xformat='log', yformat='log')\n handle_dict['kl_step'] = plot_line(self.vis,\n nans.repeat(n_steps, 1),\n np.ones((1, 2 * n_steps)),\n legend=step_legend,\n title='Per Step KL Divergence',\n xlabel='Epochs',\n ylabel='KL Divergence (Nats)',\n xformat='log', yformat='log')\n ########################################################################\n # Latent distribution parameter magnitudes\n ########################################################################\n it_legend = []\n for split in ['Train', 'Val']:\n for it_num in range(self.train_config['inference_iterations']+1):\n it_legend.append(split + ', Iteration ' + str(it_num))\n handle_dict['post_mean'] = plot_line(self.vis,\n nans.repeat(self.train_config['inference_iterations']+1, 1),\n np.ones((1, 2 * (self.train_config['inference_iterations']+1))),\n legend=it_legend,\n title='Approx. Posterior Mean Magnitude',\n xlabel='Epochs', ylabel='Mean Mag.',\n xformat='log', yformat='log')\n handle_dict['post_log_var'] = plot_line(self.vis,\n nans.repeat(self.train_config['inference_iterations']+1, 1),\n np.ones((1, 2 * (self.train_config['inference_iterations']+1))),\n legend=it_legend,\n title='Approx. Posterior Log Variance Magnitude',\n xlabel='Epochs', ylabel='Log Variance Mag.',\n xformat='log', yformat='log')\n handle_dict['prior_mean'] = plot_line(self.vis,\n nans.repeat(self.train_config['inference_iterations']+1, 1),\n np.ones((1, 2 * (self.train_config['inference_iterations']+1))),\n legend=it_legend,\n title='Prior Mean Magnitude',\n xlabel='Epochs', ylabel='Mean Mag.',\n xformat='log', yformat='log')\n handle_dict['prior_log_var'] = plot_line(self.vis,\n nans.repeat(self.train_config['inference_iterations']+1, 1),\n np.ones((1, 2 * (self.train_config['inference_iterations']+1))),\n legend=it_legend,\n title='Prior Log Variance Magnitude',\n xlabel='Epochs', ylabel='Log Variance Mag.',\n xformat='log', yformat='log')\n ########################################################################\n # Inference gradient magnitudes\n ########################################################################\n it_legend = []\n for split in ['Train', 'Val']:\n for it_num in range(self.train_config['inference_iterations']+1):\n it_legend.append(split + ', Iteration ' + str(it_num))\n handle_dict['mean_grad'] = plot_line(self.vis,\n nans.repeat(self.train_config['inference_iterations']+1, 1),\n np.ones((1, 2 * (self.train_config['inference_iterations']+1))),\n legend=it_legend,\n title='Mean Gradient Magnitude',\n xlabel='Epochs', ylabel='Mean Gradient Mag.',\n xformat='log', yformat='log')\n handle_dict['log_var_grad'] = plot_line(self.vis,\n nans.repeat(self.train_config['inference_iterations']+1, 1),\n np.ones((1, 2 * (self.train_config['inference_iterations']+1))),\n legend=it_legend,\n title='Log Variance Gradient Magnitude',\n xlabel='Epochs', ylabel='Log Variance Gradient Mag.',\n xformat='log', yformat='log')\n ########################################################################\n # Model parameter gradient magnitudes\n ########################################################################\n handle_dict['param_grad'] = plot_line(self.vis, nans, np.ones((1, 2)),\n legend=['Inf.', 'Gen.'],\n title='Parameter Gradient Mag.',\n xlabel='Epochs', ylabel='Parameter Gradient',\n xformat='log', yformat='log')\n ########################################################################\n # Inference improvement\n ########################################################################\n it_legend = []\n for split in ['Train', 'Val']:\n for it_num in range(1, self.train_config['inference_iterations']+1):\n it_legend.append(split + ', Iteration ' + str(it_num))\n handle_dict['inf_improvement'] = plot_line(self.vis,\n nans.repeat(self.train_config['inference_iterations'], 1),\n np.ones((1, 2*self.train_config['inference_iterations'])),\n legend=it_legend,\n title='Inference Improvement',\n xlabel='Epochs', ylabel='Relative Improvement (%)',\n xformat='log', yformat='linear')\n ########################################################################\n # Misc.\n ########################################################################\n it_legend = []\n for split in ['Train', 'Val']:\n for it_num in range(self.train_config['inference_iterations']+1):\n it_legend.append(split + ', Iteration ' + str(it_num))\n handle_dict['lr'] = plot_line(self.vis, nans, np.ones((1, 2)), legend=['Inf.', 'Gen.'],\n title='Learning Rates', xlabel='Epochs',\n ylabel='Learning Rate', xformat='log', yformat='log')\n handle_dict['out_log_var'] = plot_line(self.vis,\n nans.repeat(self.train_config['inference_iterations']+1, 1),\n np.ones((1, 2 * (self.train_config['inference_iterations']+1))),\n legend=it_legend,\n title='Output Log Variance',\n xlabel='Epochs', ylabel='Output Log Variance',\n xformat='log', yformat='linear')\n ########################################################################\n return handle_dict", "def draw(self, **kwargs):\n if self.orientation_ == \"h\":\n # Make the plot\n self.ax.barh(np.arange(len(self.ranks_)), self.ranks_, color=self.color)\n\n # Add ticks and tick labels\n self.ax.set_yticks(np.arange(len(self.ranks_)))\n if self.show_feature_names_:\n self.ax.set_yticklabels(self.features_)\n else:\n self.ax.set_yticklabels([])\n\n # Order the features from top to bottom on the y axis\n self.ax.invert_yaxis()\n\n # Turn off y grid lines\n self.ax.yaxis.grid(False)\n\n elif self.orientation_ == \"v\":\n # Make the plot\n self.ax.bar(np.arange(len(self.ranks_)), self.ranks_, color=self.color)\n\n # Add ticks and tick labels\n self.ax.set_xticks(np.arange(len(self.ranks_)))\n if self.show_feature_names_:\n self.ax.set_xticklabels(self.features_, rotation=90)\n else:\n self.ax.set_xticklabels([])\n\n # Turn off x grid lines\n self.ax.xaxis.grid(False)\n\n else:\n raise YellowbrickValueError(\"Orientation must be 'h' or 'v'\")", "def draw(self):\r\n self._clear(self.mainWindow)\r\n self.drawBoard()\r\n self.createControls()\r\n self.createPlayerInfo()\r\n self.createGameLog()", "def _draw_histogram(self):\n self.range = npy.arange(0, 100)\n all_data = [item for sublist in self.data for item in sublist]\n plt.hist(all_data)\n plt.show()", "def draw(self):\n\t\t# Create figure\t\t\n\t\tfig = Figure(figure=self.figure, ax=self.axes, dataset=self.dataset, map_options=self.map_options, presets=self.presets)\n\t\tfig.plot_data()\n\t\tself.figure.tight_layout()\n\t\tself.figure.canvas.draw()", "def draw_control(self):\n \n # check control\n if self.control is None:\n return\n \n # draw into buffer\n if self._use_buffer:\n \n # init DC\n dc = wx.MemoryDC()\n dc.SelectObject(self._dc_buffer)\n \n # init canvas\n canvas = self._make_canvas(dc)\n \n # draw control\n self.control.draw(canvas)\n \n # reset overlay\n if not self._dc_overlay_empty:\n self._dc_overlay.Reset()\n \n # delete DC\n dc.SelectObject(wx.NullBitmap)\n del dc\n \n # update screen\n self.Refresh(eraseBackground=False)\n self.Update()", "def draw_graph(self, dev, txt):\r\n \"\"\"x-axis reps bias_volt and y-axis reps cont_curr.\"\"\"\r\n if txt != '':\r\n self.firstbox.device.text = \"Summary of: \" + dev \r\n f = open(tst.get_path(), 'r')\r\n s = f.read()\r\n bias_v = []\r\n cont_i = []\r\n\r\n if len(txt) != 1:\r\n i1 = s.find(dev) if s.find(dev)!= -1 else s.find(dev[0].upper() + dev[1])\r\n final_bias_v = tst.get_device(dev).get_stat2()\r\n i2 = s.find(str(final_bias_v), i1)\r\n arr = s[i1:i2].split(',')\r\n\r\n i_bias_v = 1\r\n i_cont_i = 3\r\n \r\n while i_cont_i < len(arr):\r\n bias_v.append(float(arr[i_bias_v]))\r\n cont_i.append(float(arr[i_cont_i][:arr[i_cont_i].find('\\n')])*10**11)\r\n i_bias_v += 3\r\n i_cont_i += 3\r\n\r\n ##if I need to implement button functionality for columns and rows, add if conditions like \"if len(txt) == 1\" \r\n \r\n if len(self.firstbox.real_graph.plots) == 1:\r\n self.firstbox.real_graph.remove_plot(self.firstbox.real_graph.plots[0])\r\n self.plot = MeshLinePlot(color=[1,1,1,1])\r\n self.firstbox.real_graph.add_plot(self.plot)\r\n self.plot.points = []\r\n \r\n for i, (x, y) in enumerate(zip(bias_v, cont_i)):\r\n self.plot.points.append((x,y))", "def create_plot_widget(self):\n from traitsui.api import View, Item\n from enable.api import ComponentEditor\n\n view = View(Item('plot', editor=ComponentEditor(), show_label=False))\n ui = self.edit_traits(view=view, parent=None, kind='subpanel')\n\n return ui.control", "def drawPanelContents(self):\n self.drawItems()\n self.drawTextbox()", "def consoleUI():\n import argparse\n parser = argparse.ArgumentParser(description=\"Annotation viewer for visual side by side comparisons\")\n # Required arguments\n parser.add_argument(\"queryfile\", help=\"Path to query file\", type=argparse.FileType('r'))\n parser.add_argument(\"referencefile\", help=\"Path to reference file\", type=argparse.FileType('r'))\n # Optional Arguments\n parser.add_argument(\"-l\",\"--line\", help=\"Goto line\", nargs=1, type=int)\n parser.add_argument(\"-z\",\"--zoom\", help=\"Zoom level (bp)\", nargs=1, type=int)\n parser.add_argument(\"-f\",\"--features\", help=\"Nearby feature display size\", nargs=1, type=int)\n # Parse\n args = parser.parse_args()\n\n # Setup variables\n line = 0\n if args.line:\n line = args.line[0]\n zoom = 10000\n if args.zoom:\n zoom = int((args.zoom[0])/2) # Divide the value by two as view size is the size either side\n features = 5\n if args.features:\n features = args.features[0]+1\n\n # Start program\n controlPane(args.queryfile, args.referencefile, line, zoom, features)", "def draw_all(self):\n pass", "def add_histogram_panel(self):\n\n self.ax_hist = plt.axes(cfg.position_histogram_t1_mri)\n self.ax_hist.set_xticks(cfg.xticks_histogram_t1_mri)\n self.ax_hist.set_yticks([])\n self.ax_hist.set_autoscaley_on(True)\n self.ax_hist.set_prop_cycle('color', cfg.color_histogram_t1_mri)\n self.ax_hist.set_title(cfg.title_histogram_t1_mri, fontsize='small')" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds an externally defined loss to collection of losses.
def add_loss(loss): tf.add_to_collection(LOSSES, loss)
[ "def add_loss(self, losses, inputs=None):\n if context.in_eager_mode():\n raise RuntimeError('Layer.add_loss not supported in Eager mode.')\n losses = _to_list(losses)\n if not losses:\n return\n self._losses += losses\n if inputs is not None:\n inputs = _to_list(inputs)\n if not inputs:\n inputs = None\n if inputs is not None:\n # We compute an ID that uniquely identifies the list of tensors.\n # This ID is order-sensitive.\n inputs_hash = _object_list_uid(inputs)\n else:\n inputs_hash = None\n if inputs_hash not in self._per_input_losses:\n self._per_input_losses[inputs_hash] = []\n self._per_input_losses[inputs_hash] += losses\n _add_elements_to_collection(losses, ops.GraphKeys.REGULARIZATION_LOSSES)", "def loss(self, value: float) -> None:\n self.scores['loss'].append(value)", "def update_loss(self, loss):\n self.loss += loss\n self.num_loss_attempts += 1", "def add_loss(self, avg_batch_loss: float, num_instances: int) -> None:\n self.losses.append(avg_batch_loss * num_instances)\n self.batch_sizes.append(num_instances)", "def set_loss_fn(self, fn):\r\n\t\tself.loss_fn = fn", "def _CreateWeightLoss(self):\n self.AssertInitialized()\n with self._BlockScope():\n return [tf.nn.l2_loss(v) for v in self._variables]", "def add_loss_summaries():\n losses = tf.get_collection(\"summary_loss\")\n \n loss_averages = tf.train.ExponentialMovingAverage(0.95, name='avg')\n loss_averages_op = loss_averages.apply(losses)\n\n for loss_op in losses:\n tf.scalar_summary(loss_op.op.name +' (raw)', loss_op)\n tf.scalar_summary(loss_op.op.name, loss_averages.average(loss_op))\n\n return loss_averages_op", "def get_loss_fn(self):\n return utils.misc.losses(self.config)", "def add_lrelu(self, leak=.2):\n with tf.variable_scope(self._get_layer_str()):\n t1 = .5 * (1 + leak)\n t2 = .5 * (1 - leak)\n out = t1 * self.get_output() + \\\n t2 * tf.abs(self.get_output())\n self.outputs.append(out)\n return self", "def add_wd(op, wd):\n params = get_params(op)\n for param in params:\n weight_decay = tf.multiply(tf.nn.l2_loss(param), wd)\n tf.add_to_collection(tf.GraphKeys.LOSSES, weight_decay)\n return op", "def loss(self):\n return np.mean(self.scores['loss'])", "def _create_loss(self):\n\n def loss_fn(outputs, labels, weights):\n prob = tf.reduce_sum(outputs[0] * labels[0], axis=2)\n mask = tf.reduce_sum(labels[0], axis=2)\n log_prob = tf.math.log(prob + 1e-20) * mask\n loss = -tf.reduce_mean(tf.reduce_sum(log_prob, axis=1))\n return loss + sum(self.model.losses)\n\n return loss_fn", "def custom_loss(layer):\n def loss(y_true, y_pred):\n return K.mean(K.square(y_pred - y_true) + K.square(layer), axis=-1)\n\n # Return a function\n return loss", "def update(self, trainer):\n loss_handler = trainer.loss_handler\n self.loss_avg = float(loss_handler.get(\"loss_m\", self._default_loss_value, is_avg_value=True))\n self.loss_gen = float(\n loss_handler.get(\"loss_recon\", self._default_loss_value, is_avg_value=True) + \n loss_handler.get(\"loss_soft\", self._default_loss_value, is_avg_value=True)\n )\n if not torch.is_tensor(self.loss_avg):\n self.loss_avg = torch.tensor(self.loss_avg)\n if not torch.is_tensor(self.loss_gen):\n self.loss_gen = torch.tensor(self.loss_gen)", "def CreateWeightLoss(self):\n losses = list(itertools.chain(\n itertools.chain.from_iterable(\n t.CreateWeightLoss() for t in self._subblocks),\n self._CreateWeightLoss()))\n return losses", "def UpdateLoss(self, points: float):\n self.elo -= rounded_int(points)\n self.record.AddLoss()", "def _compute_loss(self, _block_id):\n raise NotImplementedError()", "def loss_criterion(self) -> torch.nn.Module:\n\n pass", "def lp_loss(generated, gt, l_num, batch_size_tf):\n lp_loss=tf.reduce_sum(tf.abs(generated - gt)**l_num)/(2*tf.cast(batch_size_tf,tf.float32))\n tf.add_to_collection('losses', lp_loss)\n\n loss = tf.add_n(tf.get_collection('losses'), name='total_loss')\n return loss" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a tensor whose value represents the total loss. Notice that the function adds the given losses to the regularization losses.
def get_total_loss(add_regularization_losses=True, name="total_loss"): losses = get_losses() if add_regularization_losses: losses += get_regularization_losses() return tf.add_n(losses, name=name)
[ "def _compute_regular_loss(self):\n regular_loss = self._l2_loss() + self._l1_loss() + self._cross_l_loss()\n return tf.reduce_sum(regular_loss)", "def get_total_loss(splits=[''], collection='outputs', with_summaries=True, verbose=0): \n losses = []\n for split in splits:\n full_loss = 0.\n loss_collections = [x for x in tf.get_default_graph().get_all_collection_keys() if \n x.endswith('_loss') and x.startswith(split)]\n ## sum losses\n for key in loss_collections:\n collected = tf.get_collection(key)\n loss = tf.add_n(collected) / float(len(collected))\n full_loss += loss\n if with_summaries:\n base_name = key.split('_', 1)[0]\n tf.summary.scalar(key, loss, collections=[collection], family='train_%s' % base_name)\n\n ## Add regularization loss if any \n reg_losses = tf.losses.get_regularization_losses(scope='train/dev0/%s' % split)\n if len(reg_losses):\n regularization_loss = tf.add_n(reg_losses)\n full_loss += regularization_loss\n if with_summaries:\n tf.summary.scalar('%sregularization_loss' % split, regularization_loss, collections=[collection])\n\n ## Summary for the total loss in the current scope\n if with_summaries:\n tf.summary.scalar('%stotal_loss' % split, full_loss, collections=[collection]) \n \n ## Add losses and corresponding variables\n train_vars = tf.trainable_variables(scope=split)\n losses.append((full_loss, train_vars, split))\n if verbose == 2:\n print(' > \\033[33min %s scope:\\033[0m' % (split if split else \"global\"))\n print(' ', len(reg_losses), 'regularization losses found')\n if len(loss_collections):\n print('\\n'.join([\" *%s*: %s tensors\" % (x, len(tf.get_collection(x)))\n for x in loss_collections]))\n else:\n print(' \\033[31mWarning:\\033[0m No losses found with base name', split)\n print(' Trainable variables: [%s]' % ', '.join(list(map(lambda x: x.name, train_vars))))\n return losses", "def _create_loss(self):\n\n def loss_fn(outputs, labels, weights):\n prob = tf.reduce_sum(outputs[0] * labels[0], axis=2)\n mask = tf.reduce_sum(labels[0], axis=2)\n log_prob = tf.math.log(prob + 1e-20) * mask\n loss = -tf.reduce_mean(tf.reduce_sum(log_prob, axis=1))\n return loss + sum(self.model.losses)\n\n return loss_fn", "def get_total_loss(self, inference_loss):\n reg_losses = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)\n if len(reg_losses) > 0:\n tf.summary.scalar(\n 'inference_loss', inference_loss, family='sublosses')\n reg_loss = tf.add_n(reg_losses)\n tf.summary.scalar('reg_loss', reg_loss, family='sublosses')\n loss = inference_loss + reg_loss\n else:\n loss = inference_loss\n return loss", "def add_loss_summaries():\n losses = tf.get_collection(\"summary_loss\")\n \n loss_averages = tf.train.ExponentialMovingAverage(0.95, name='avg')\n loss_averages_op = loss_averages.apply(losses)\n\n for loss_op in losses:\n tf.scalar_summary(loss_op.op.name +' (raw)', loss_op)\n tf.scalar_summary(loss_op.op.name, loss_averages.average(loss_op))\n\n return loss_averages_op", "def reg_loss(self):\n \n loss = 0.0\n \n for xlayer in self.layers.values():\n loss += xlayer.reg_loss()\n \n return loss", "def lp_loss(generated, gt, l_num, batch_size_tf):\n lp_loss=tf.reduce_sum(tf.abs(generated - gt)**l_num)/(2*tf.cast(batch_size_tf,tf.float32))\n tf.add_to_collection('losses', lp_loss)\n\n loss = tf.add_n(tf.get_collection('losses'), name='total_loss')\n return loss", "def custom_loss(layer):\n def loss(y_true, y_pred):\n return K.mean(K.square(y_pred - y_true) + K.square(layer), axis=-1)\n\n # Return a function\n return loss", "def loss(self) -> float:\n\n rews = self.transform_rewards()\n value_loss = self.value_loss(rews)\n return torch.cat(value_loss).sum()", "def loss_funtion(self):\n\n if self.logits is None:\n raise ValueError('Logits not defined!')\n\n with tf.name_scope(\"ctc_loss\"):\n loss = tf.nn.ctc_loss(self.label_sparse_placeholder, self.logits, tf.cast(self.input_seq_len_placeholder, tf.int32))\n self.loss = tf.reduce_mean(loss, name='ctc_loss_mean')\n\n return self.loss", "def loss(self) -> float:\n\n rews = self.transform_rewards()\n policy_loss = self.policy_loss(rews)\n return torch.cat(policy_loss).sum()", "def loss(self):\n return np.mean(self.scores['loss'])", "def make_loss_function(network_apply_fun, basic_loss_fun, regularization_fun):\n\n def total_loss_fun(params, batch):\n \"\"\"\n Maps network parameters and training batch to a loss value.\n\n Args:\n batch: a dictionary with keys ['inputs', 'index', 'labels']\n 'inputs': sequence of inputs with shape (batch_size, max_sequence_length)\n 'index' : 1d-array storing length of the corresponding input sequence\n 'labels': 1d-array storing label of corresponding input sequence\n\n Returns:\n loss: scalar loss averaged over batch\n \"\"\"\n\n all_time_logits = network_apply_fun(params, batch['inputs'])\n end_logits = select(all_time_logits, batch['index'] - 1)\n\n return basic_loss_fun(end_logits,\n batch['labels']) + regularization_fun(params)\n\n return total_loss_fun", "def calculate_loss(self, activations, labels):\n\n # get the regularisation for each layer in the model\n regularisation = 0.0\n for layer in self.layers:\n regularisation += layer.get_regularisation()\n\n loss, gradients = self.loss_function(activations, labels)\n return loss + regularisation, gradients", "def loss_fct(samples, labels, reg_factor):\n loss = []\n loss_sum = []\n for t in range(len(theta)):\n for i in range(len(Y)):\n #Calculate the loss over samples and labels.\n sum_1 = ((-labels[i]*np.log(logistic(theta[t], \n np.asmatrix(np.array([X[0][i],X[1][i],X[2][i],X[3][i]])).T))\n - (1-labels[i])*np.log(1-logistic(theta[t], \n np.asmatrix(np.array([X[0][i],X[1][i],X[2][i],X[3][i]])).T)))) \n loss.append(sum_1)\n #Add the sum of the regularization term.\n sum_2 = reg_factor/2*(np.power(theta[t][0],2) \n + np.power(theta[t][1],2) \n + np.power(theta[t][2],2) + np.power(theta[t][3],2))\n loss_sum.append(sum(loss)+sum_2)\n loss = []\n return loss_sum", "def reference_loss_func(loss_sum_or_avg: torch.Tensor, num_measurements: torch.Tensor, take_avg_loss: bool):\n loss_sum_or_avg = loss_sum_or_avg.clone().detach()\n if take_avg_loss:\n loss_sum_or_avg *= num_measurements\n nm_sum = num_measurements.sum()\n if nm_sum.eq(0):\n return torch.tensor(float('nan'))\n return loss_sum_or_avg.sum() / nm_sum", "def total_loss(self, f, y):\n f = (np.reshape(f,(f.shape[0],1)))\n f = f.astype(np.float64)\n y = (np.reshape(y,(y.shape[0],1)))\n y = y.astype(np.float64)\n\n hinge_loss = np.sum(np.maximum(0, 1 - f*y))\n l2_loss = (0.5*self.w_decay_factor*(np.linalg.norm(self.w))**2)\n # Implementation here.\n #pass\n\n total_loss = hinge_loss + l2_loss\n #print(total_loss)\n return total_loss", "def entropic_loss(pnl) -> torch.Tensor:\n return -torch.mean(-torch.exp(-pnl))", "def multiTaskLoss(self, loss: _S2T) -> torch.Tensor:\n return sum(v * self.cmgr.get(\"task.\" + k, 1) for k, v in loss.items())" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return logp function that accepts dictionary with unused variables as input
def loose_logp(model, vars): return model.compile_fn( model.logp(vars=vars, sum=False), inputs=model.value_vars, on_unused_input="ignore", )
[ "def log_op():\n prepare_logs(scalars)\n return {\"scalars\": scalars}", "def log_wealth_optim(f, pnl):\n return -np.mean(np.log(1 + f * pnl))", "def log_p_m_x(log_Bs, myTheta):\n print(\"TODO\")", "def log_gap(function_name):\n def return_function(*args):\n if isinstance(args[0], np.ndarray) and len(args) == 1:\n # all the arguments are given in the first argument\n args = args[0].tolist()\n return np.log(eval(function_name)(*args) - optimal_values[function_name])\n return return_function", "def p_log_p(p: torch.FloatTensor) -> torch.FloatTensor:\n return p * mask_log(p, mask=p != 0)", "def log2(x):\n pass", "def log_metadata(func):\n @wraps(func)\n def wrapped(*a, **kw):\n\n # Fetch function metadata.\n current_params = locals()\n func_name = func.__name__\n\n # Order the current_params dictionary\n # Because I like stuff alphabetical. \n current_params = OrderedDict(sorted(current_params.items(), key=lambda t: t[0]))\n\n logging.info(\"\")\n logging.info(\"FUNCTION: {}\".format(func_name.upper()))\n logging.info(\" PARAMETER : VALUE \")\n #for param, value in current_params['kw'].iteritems(): #python 2\n for param, value in current_params['kw'].items():\n logging.info(\" {} : {}\".format(param, value))\n logging.info(\"\")\n\n return func(*a, **kw)\n\n return wrapped", "def log_p(observed_data: torch.FloatTensor,\n log_alpha: torch.FloatTensor) -> torch.FloatTensor:\n alpha = log_alpha.exp()\n return ((torch.log(observed_data) * (alpha - 1.0)).sum(-1) +\n torch.lgamma(alpha.sum(-1)) -\n torch.lgamma(alpha).sum(-1))", "def log(p):\n\tif p < 0: raise ValueError('p < 0: ' + str(p))\n\tif p == 0: return -999\n\telse: return math.log(p)", "def from_dict(d):\n log = CallLog()\n keys = d['args'].keys()\n for k, v in zip(zip(*d['args'].values()), d['values']):\n args = dict([(key, val) for key, val in zip(keys, k)])\n log.insert(v, **args)\n return log", "def likefxn1(params, x):\n\n mu, k, a, b = params\n return -np.sum(np.log(pihm_pmf(x, mu, k, a, b)))", "def log_data_likelihood(y, explan, explan_bar, params, num_pts, t, pi_bit):\n # type: (object, object, object, object, object, object) -> object\n if params[-1] <= 0:\n print params\n temp_1 = 0.5 * num_pts * np.log(params[-1])\n temp_2 = np.sum((y - params[0] - params[1] * (explan - explan_bar))**2) / (2. * params[-1])\n return -t * (pi_bit + temp_1 + temp_2)", "def logkv(_logger, msgdict, level=\"info\", exception=None):\n try:\n # Get the appropriate method of the logger instance\n logfunc = getattr(_logger, level)\n\n # Get the name of function which called logkv()\n current_frame = inspect.currentframe()\n call_frame = inspect.getouterframes(current_frame, 2)\n msgdict.update({\"__funcname__\": call_frame[1][3]})\n if exception:\n msgdict.update(exception.info())\n except Exception:\n raise Exception(\"Error in logkv()\")\n\n delim = \", \"\n msg = delim.join(['%s=\"%s\"' % (k, v) for k, v in msgdict.items()])\n logfunc(msg)", "def log_parameters(self):\n for tag, value in self.named_parameters():\n tag = tag.replace(\".\", \"/\")\n self.logger.experiment.add_histogram(tag, value, self.current_epoch)", "def log_parameters(self, equation):\n if hasattr(equation, 'parameters') and equation.parameters is not None:\n logger.info(\"Physical parameters that take non-default values:\")\n logger.info(\", \".join(\"%s: %s\" % (k, float(v)) for (k, v) in vars(equation.parameters).items()))", "def log_posterior(f):\n return self._log_likelihood(np.hstack((0.0, f))) + self._log_prior_laplace(np.hstack((0.0, f)))", "def loglike(self, nodeinput=None):\n if nodeinput is None:\n nodeinput = {}\n problist = []\n for n in self.iterator:\n if n.name in nodeinput:\n problist.append(n.logprob(valueinput=nodeinput[n.name]))\n else:\n problist.append(n.logprob())\n r = np.sum(problist)\n return r", "def log_func(function):\n @wraps(function)\n def do(*args, **kwargs):\n logger.debug('[%s]: ', str(function.__name__))\n return function(*args, **kwargs)\n return do", "def log_verbose(*values):\n #log_print(' ', *values)\n return" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Some sanity checks on split line (that time and clk are integers).
def check_cycle_line(self, line): try: time = int(line[0]) except: self.logger.die('first col (time) in sim output not int') try: clk = int(line[1], 2) except: self.logger.die('second col (clk) in sim output not bin') self.logger.info('emulator pass, time=%s, clk=%s' % (time, clk)) return time, clk
[ "def _parseTimeLine(lineno, line):\n m = re.match(RE_ALL, line)\n if m is None:\n return InvalidTimeTrackingEntry(\n lineno=lineno,\n line=line,\n errorMessage=\"Bad format\")\n else:\n trigram = m.group('trigram')\n\n dt = m.group('date')\n try:\n date = datetime.datetime.strptime(dt,'%d/%m/%Y')\n except:\n return InvalidTimeTrackingEntry(\n lineno=lineno,\n line=line,\n errorMessage=\"Error with the date '%s'. Format is 03/12/2017\" % dt)\n\n duration = minutes(m.group('duration'))\n if duration is None:\n return InvalidTimeTrackingEntry(\n lineno=lineno,\n line=line,\n errorMessage=\"Invalid duration '%d'. Format is 10h or 1h30 or 30m\" % duration)\n\n issue = m.group('issue')\n if issue[0] != '#':\n return InvalidTimeTrackingEntry(\n lineno=lineno,\n line=line,\n errorMessage= \"Issue must start with #. Found '%s'\" % issue)\n else:\n try:\n issueNb = int(issue[1:])\n except:\n return InvalidTimeTrackingEntry(\n lineno=lineno,\n line=line,\n errorMessage=\"Issue specification is incorrect.\"\n \" Should be like #23. Found '%s'\" \\\n % issue )\n return ValidTimeTrackingEntry(\n lineno=lineno,\n line=line,\n trigram=trigram,\n date=date,\n duration=duration,\n issueNb = issueNb\n )\n\n\n\n # timeTrackingEntries = []\n # nKOTimeLines = []\n # for (no, line) in nTimeLines:\n # m = re.match(RE_ALL, line)\n # if m:\n # te = ValidTimeTrackingEntry(\n # lineno=no,\n # line=line,\n # trigram = m.group('trigram'),\n # date = m.group('date'),\n # duration = m.group('duration'),\n # issueNb = m.group('issue')\n # )\n # timeTrackingEntries += [te]\n # else:\n # nKOTimeLines += [(no, line)]\n # return (timeTrackingEntries, nKOTimeLines)", "def test_split_line(self):\n text = \" 1 2 3 4 5 6 7 8 9 0 \"\n for size, prefix, expect in (\n (3, 0, [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"0\"]),\n (3, 3, [\"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"0\"]),\n (4, 0, [\"1\", \"2 3\", \"4\", \"5\", \"6 7\", \"8\", \"9\", \"0\"]),\n (2, 7, [\"3\", \"4\", \"\", \"5\", \"6\", \"\", \"7\", \"8\", \"\", \"9\", \"0\"]),\n ):\n self.assertEqual(gfs._split_line(text, size, prefix), expect)\n # MAV line\n text = \"HR 06 09 12 15 18 21 00 03 06 09 12 15 18 21 00 03 06 09 12 18 00 \"\n line = gfs._split_line(text)\n self.assertEqual(len(line), 21)\n self.assertEqual(line[0], \"06\")\n self.assertEqual(line[-1], \"00\")\n # MEX line\n text = \"FHR 24 36| 48 60| 72 84| 96 108|120 132|144 156|168 180|192\"\n line = gfs._split_line(text, size=4)\n self.assertEqual(len(line), 15)\n self.assertEqual(line[0], \"24\")\n self.assertEqual(line[-1], \"192\")", "def split_time(time_str):\n components = []\n digits = []\n for b in time_str:\n if grammar.is_digit(b):\n digits.append(b)\n if len(digits) > 2:\n raise ValueError(\"Can't read time from %s\" % time_str)\n else:\n if len(digits) < 1:\n raise ValueError(\"Missing time-value in %s\" % time_str)\n components.append(int(join_bytes(digits)))\n digits = []\n if len(components) == 3 or b != grammar.COLON:\n break\n if digits:\n components.append(int(join_bytes(digits)))\n if (len(components) != 3):\n raise ValueError(\"Can't read time from %s\" % time_str)\n return tuple(components)", "def parseLine(line):\n tokens = line.split(':')\n # print(tokens)\n stamp=\"\"\n temp=-999.0\n humt=-999.0\n pres=-999.0\n lght=-999.0\n clock=False\n thermometer=False\n barometer=False\n hygrometer=False\n firmware=\"\"\n hardware=\"\"\n devName=\"\"\n for t in tokens:\n if t == 'DATA ':\n pass # ignore header\n elif t[0:1] == 'C':\n stamp = datetime.strptime(t[1:], '%Y%m%d%H%M%S').replace(tzinfo=pytz.UTC)\n elif t[0:1] == 'T':\n temp = float(t[1:])\n elif t[0:1] == 'H':\n humt = float(t[1:])\n elif t[0:1] == 'P':\n pres = float(t[1:])\n elif t[0:1] == 'L':\n lght = float(t[1:])\n elif t[0:1] == 'F':\n firmware = t[1:]\n elif t[0:1] == 'D':\n devList = t[1:]\n # print(devList)\n clock = devList[0:1] == 'C'\n thermometer = devList[1:2] == 'T'\n hygrometer = devList[2:3] == 'H'\n barometer = devList[3:4] == 'P'\n elif t[0:1] == 'W':\n hardware = t[1:]\n elif t[0:1] == \"N\":\n devName = t[1:]\n return stamp,temp,humt,pres,lght,firmware,hardware,devName,clock,thermometer,hygrometer,barometer", "def lineToComparableNumber(line):\n \n # str used in reporting errors.\n lineInfoStr = \" Line was: {}\".format(line)\n \n # Check the number of fields.\n fields = line.split(\",\")\n\n numFieldsExpected = 7\n if len(fields) != numFieldsExpected:\n log.error(\"Line does not have {} data fields.\".\\\n format(numFieldsExpected) + \\\n lineInfoStr)\n shutdown(1)\n\n timestampStr = fields[0] \n openStr = fields[1]\n highStr = fields[2]\n lowStr = fields[3]\n closeStr = fields[4]\n volumeStr = fields[5]\n openIntStr = fields[6]\n\n dateStr = None\n timeStr = None\n \n if len(timestampStr) == 10:\n # Format of timestamp is 'MM/DD/YYYY'.\n dateStr = timestampStr\n timeStr = \"00:00\"\n elif len(timestampStr) == 16:\n # Format of timestamp is 'MM/DD/YYYY HH:MM'.\n timestampFields = timestampStr.split(\" \")\n \n if len(timestampFields) != 2:\n log.error(\"Format of the timestamp was not \" + \\\n \"'MM/DD/YYYY' or 'MM/DD/YYYY HH:MM'.\" + \\\n lineInfoStr)\n shutdown(1)\n \n dateStr = timestampFields[0]\n timeStr = timestampFields[1]\n else:\n # Invalid number of characters for the timestamp.\n log.error(\"Invalid number of characters for the timestamp.\" + \\\n lineInfoStr)\n shutdown(1)\n \n dateFields = dateStr.split(\"/\")\n if len(dateFields) != 3:\n log.error(\"Format of the date was not 'MM/DD/YYYY'.\" + \\\n lineInfoStr)\n shutdown(1)\n\n monthStr = dateFields[0]\n dayStr = dateFields[1]\n yearStr = dateFields[2]\n\n if len(monthStr) != 2:\n log.error(\"Month in the date is not two characters long.\" + \\\n lineInfoStr)\n shutdown(1)\n if len(dayStr) != 2:\n log.error(\"Day in the date is not two characters long.\" + \\\n lineInfoStr)\n shutdown(1)\n if len(yearStr) != 4:\n log.error(\"Year in the date is not four characters long.\" + \\\n lineInfoStr)\n shutdown(1)\n\n try:\n monthInt = int(monthStr)\n if monthInt < 1 or monthInt > 12:\n log.error(\"Month in the date is not between 1 and 12.\" + \\\n lineInfoStr)\n shutdown(1)\n except ValueError as e:\n log.error(\"Month in the date is not a number.\" + \\\n lineInfoStr)\n shutdown(1)\n\n try:\n dayInt = int(dayStr)\n if dayInt < 1 or dayInt > 31:\n log.error(\"Day in the date is not between 1 and 31.\" + \\\n lineInfoStr)\n shutdown(1)\n except ValueError as e:\n log.error(\"Day in the date is not a number\")\n shutdown(1)\n\n try:\n yearInt = int(yearStr)\n except ValueError as e:\n log.error(\"Year in the date is not a number\")\n shutdown(1)\n\n\n\n timeFields = timeStr.split(\":\")\n if len(timeFields) != 2:\n log.error(\"Format of the time was not 'HH:MM'.\" + \\\n lineInfoStr)\n shutdown(1)\n\n hourStr = timeFields[0]\n minuteStr = timeFields[1]\n\n if len(hourStr) != 2:\n log.error(\"Hour in the timestamp is not two characters long.\" + \\\n lineInfoStr)\n shutdown(1)\n if len(minuteStr) != 2:\n log.error(\"Minute in the timestamp is not two characters long.\" + \\\n lineInfoStr)\n shutdown(1)\n \n try:\n hourInt = int(hourStr)\n if hourInt < 0 or hourInt > 23:\n log.error(\"Hour in the timestamp is not in range [00, 23].\" + \\\n lineInfoStr)\n shutdown(1)\n except ValueError as e:\n log.error(\"Hour in the timestamp is not a number.\" + \\\n lineInfoStr)\n shutdown(1)\n\n try:\n minuteInt = int(minuteStr)\n if minuteInt < 0 or minuteInt > 59:\n log.error(\"Minute in the timestamp is not in range [00, 59].\" + \\\n lineInfoStr)\n shutdown(1)\n except ValueError as e:\n log.error(\"Minute in the timestamp is not a number.\" + \\\n lineInfoStr)\n shutdown(1)\n\n\n numericalValue = int(yearStr + monthStr + dayStr + hourStr + minuteStr)\n\n log.debug(\"Convert line '{}' to numericalValue: '{}'\".\\\n format(line, numericalValue))\n \n return numericalValue", "def test_nonconsecutive_line(self):\n self.st.append( (2,0) ) # next place in col 0 should be 1\n self.o.state = self.st\n self.assertTrue(self.o.timer == 0, \"timer is wrong\")\n self.assertTrue(self.o.state == (), \"state is wrong\")\n self.assertEqual(self.o.board.count(0), self.o.nbl*self.o.nbc,\n \"board is wrong\")", "def test_parse_time_errors(self):\n for err_time_str in (\"3.4.5 ms\", \".\", \"\", \"asdf\", \" 0 h z \", \"nm\"):\n with self.assertRaises(\n ValueError,\n msg=f'parsing \"{err_time_str}\" should have raised ValueError',\n ):\n _ = parse_time(err_time_str)", "def SplitSample(sample):\n sample = sample.strip()\n index = sample.rfind('\\n')\n power = sample[:index]\n time = sample[index + 1:]\n return power, int(time)", "def test_line_outofrange(self):\n self.st.append( (4,0) )\n self.o.state = self.st\n self.assertTrue(self.o.timer == 0, \"timer is wrong\")\n self.assertTrue(self.o.state == (), \"state is wrong\")\n self.assertEqual(self.o.board.count(0), self.o.nbl*self.o.nbc,\n \"board is wrong\")", "def __splitTime(sec):\n minute, sec = divmod(sec, 60)\n hour, minute = divmod(minute, 60)\n return hour, minute, sec", "def test_timedatectl_nodata(self):\n self.assertEqual(jc.parsers.timedatectl.parse('', quiet=True), {})", "def _readTimeLines(filename):\n with open(filename) as f:\n lines = f.readlines()\n lines = [line.strip() for line in lines]\n nLines = _numeredLines(lines)\n\n nTimeLines = []\n nLinesSkipped = []\n for (no,line) in nLines:\n if _isTimeLine(line):\n nTimeLines += [(no,line)]\n else:\n nLinesSkipped += [(no,line)]\n return (nTimeLines, nLinesSkipped)", "def should_count_spines(line):\n return line != \"\" and line != config.MEASURE_SYMBOL", "def test_validate_line_durations_with_valid_arguments(\n line_durations: Optional[List[float]],\n valid_rhythmic_patterns: List[List[float]],\n n_measures: int\n) -> None:\n validate_line_durations(\n line_durations, valid_rhythmic_patterns, n_measures\n )", "def test_parse_1minute_wind_from_line(self):\n\n for i in range(len(WIND_LINES_5MINUTE)):\n this_wind_tuple = hfmetar_io._parse_1minute_wind_from_line(\n WIND_LINES_5MINUTE[i])\n this_wind_array = numpy.asarray(this_wind_tuple)\n\n self.assertTrue(numpy.allclose(\n this_wind_array, WIND_ARRAYS_5MINUTE[i], atol=TOLERANCE,\n equal_nan=True))", "def check_time_correct(self):\r\n if self.get_hour() == '' or self.get_min() == '' or len(str(self.get_hour())+str(self.get_min())) != 4:\r\n messagebox.showerror(\"Ok\", \"Please enter a valid time. Use the format HH:MM\")\r\n self.refresh()\r\n else:\r\n if int(self.get_hour()) >= 24 or int(self.get_min()) > 59:\r\n messagebox.showerror(\"Ok\", \"Please enter a valid time. Use the format HH:MM\")\r\n self.refresh()\r\n else:\r\n self.selection()", "def test_parse_elapsed_time_hr_min_sec(self):\n result = rclone.parse_time_spent(\"Elapsed time: 1h18m27.9s\")\n self.assertEqual(result, 4708)", "def _splitLine(self, line):\n # Confirm the line starts correctly\n match = self.__prefixRegex.search(line)\n if match:\n # Get the indentation, line text, and current value\n self.__indentSize = line[:line.find(\"(\")]\n text = \"({0})\".format(match.group(0))\n value = line.strip().replace(text, \"\")\n comment = None\n\n # Strip comments as needed\n commentMatch = self.__commentRegex.search(value)\n if commentMatch:\n comment = commentMatch.group(0)\n value = value.replace(comment, \"\")\n\n # Make it a number for math(s) operations\n value = self._convertToNumber(value)\n return [text, value, comment]\n return False", "def test_time_valid_init(generic_task):\n assert generic_task.get_time_valid() == '0000'" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse a message response sent by the Redis datastore on a subscribed channel.
def parse_response(self): return self._subscription.parse_response()
[ "def channelMessageReceived(self, channel, message, subchannel):", "def __unpack__(self):\n for item in self.pubsub.listen():\n message = item.get('data')\n if item['type'] == 'message':\n yield message", "def _parse(self):\n\t\t\n\t\tself.reply_msg = MessageHandler.fire_handlers(self)", "def __on_request_response__(self, ch, method, props, body):\r\n\t\ttry:\r\n\t\t\tself.last_message = json.loads(body)\r\n\t\texcept ValueError:\r\n\t\t\tprint 'encountered an error while decoding the message'\r\n\t\t\tself.last_message = body\r\n\r\n\t\tself.response = 'received'", "def get_messages(self, channel):\n\n def datetime_to_ts(date):\n return (date - datetime(1970, 1, 1)).total_seconds()\n\n def ts_to_datetime(ts):\n return datetime.fromtimestamp(float(ts))\n try:\n _channel = self.get_channel(channel)\n except ValueError as e:\n logger.error(\"channel %s at %s not found\" %\n (channel.name, self.server))\n return None\n logger.info(\"Fetching message from %s (%s)\" %\n (channel.name, self.server))\n if 'is_group' in _channel and _channel['is_group']:\n api_uri = 'groups.history'\n else:\n api_uri = 'channels.history'\n\n if channel.cursor_ts == 0:\n channel.cursor_ts = datetime_to_ts(channel.cursor)\n\n try:\n raw = self.connection.api_call(\n api_uri,\n channel=_channel['id'],\n oldest=channel.cursor_ts)\n except Exception as e:\n logger.exception(e)\n return\n resp = json.loads(json.dumps(raw))\n old_cursor = channel.cursor_ts\n scrap_counter.labels('slack', channel.name).inc()\n for message in resp['messages']:\n d = message['ts']\n message_date = ts_to_datetime(d) # FIXME: can we safely remove this unused variable ?\n\n if d <= old_cursor:\n continue\n if d > old_cursor:\n old_cursor = d\n if message['type'] == 'message':\n try:\n user = self.get_user(message['user'])\n userName = user['name']\n except:\n userName = message['username']\n msg = \"%s@%s | %s\" % \\\n (userName, channel.name, BeautifulSoup(message['text'], \"html.parser\").text)\n self.enqueue(queue=channel.queue, message=msg)\n read_msg_counter.labels('slack', channel.name).inc()\n channel.cursor_ts = old_cursor", "def decode_response(response):\n\n if u'result' in response:\n return ConnectionResponse(response)\n\n if 'method' in response and response['method'] == 'connection/complete':\n return ConnectionCompleteEvent(response)\n\n # Could not decode return st\n return response", "async def _received_message(self, message):\n # return True if we should reconnect\n message = from_json(message)\n\n operation = message['op']\n data = message['d']\n sequence = message['s']\n\n if sequence is not None:\n self.sequence = sequence\n \n if operation:\n return await self._special_operation(operation, data)\n \n # self.DISPATCH\n event = message['t']\n client = self.client\n try:\n parser = PARSERS[event]\n except KeyError:\n Task(client.events.error(client,\n f'{self.__class__.__name__}._received_message',\n f'Unknown dispatch event {event}\\nData: {data!r}'),\n KOKORO)\n \n return False\n \n try:\n if parser(client, data) is None:\n return False\n except BaseException as err:\n Task(client.events.error(client, event, err), KOKORO)\n return False\n \n if event == 'READY':\n self.session_id = data['session_id']\n #elif event=='RESUMED':\n #pass\n \n return False", "def getChannelResponse(self):\n \n return self.channel_response", "def consume(self, message: Dict):", "def ParseResponse(msg):\n # Parse the result\n try:\n data = serializer.LoadJson(msg)\n except KeyboardInterrupt:\n raise\n except Exception as err:\n raise ProtocolError(\"Error while deserializing response: %s\" % str(err))\n\n # Validate response\n if not (isinstance(data, dict) and\n KEY_SUCCESS in data and\n KEY_RESULT in data):\n raise ProtocolError(\"Invalid response from server: %r\" % data)\n\n return (data[KEY_SUCCESS], data[KEY_RESULT],\n data.get(KEY_VERSION, None)) # pylint: disable=E1103", "def _callback(msg):\n print('subscription message data: ', msg.data.decode('utf-8'))\n if msg.attributes:\n print('subscription message attributes:\\n')\n pprint(msg.attributes)\n msg.ack()", "def parse_msg(msg):\n subject = msg.get(\"Subject\")\n return {\n \"subject\": subject,\n \"sender\": msg.get(\"Sender\"),\n \"date\": msg.get(\"Date\"),\n \"size\": len(bytes(msg)),\n }", "def subscribe(self, channel, clientid, request):\n return True, \"\"", "def _nextMessage( self ):\n # receive an update / skip\n try:\n msg = self.sock.recv(1024)\n except SocketError, se:\n # If there was no data on the socket\n # --> not a real error, else kill socket and start a new one\n if se.errno != 11:\n progress(\"Connection failed: \"+str(se))\n self.sock.close()\n self.sock = None\n return ''\n # Use previously buffered data\n msg = self.buf + msg\n # End of dictionary should be end of message\n f = msg.find(\"}\")\n if f<0:\n self.buf = msg\n return ''\n # Pull out the first dictionary\n self.buf = msg[f+1:]\n return msg[:f+1]", "def _parse(self):\n self._chan = self.line[2]\n try:\n sender = re.findall(r\":(.*?)!(.*?)@(.*?)\\Z\", self.line[0])[0]\n except IndexError:\n self._host = self.line[0][1:]\n self._nick = self._ident = self._reply_nick = \"*\"\n return\n self._nick, self._ident, self._host = sender\n self._reply_nick = self._nick\n\n if self._msgtype in [\"PRIVMSG\", \"NOTICE\"]:\n if self.chan.lower() == self.my_nick:\n # This is a privmsg to us, so set 'chan' as the nick of the\n # sender instead of the 'channel', which is ourselves:\n self._chan = self._nick\n self._is_private = True\n self._msg = \" \".join(self.line[3:])[1:]\n if self._msgtype == \"PRIVMSG\":\n self._parse_args()\n self._parse_kwargs()", "def parse_message(message):\n return {\n \"msg\": message.message,\n \"sender\": message.sender.name,\n \"sent_on\": message.sent_on.strftime(\"%b %d %y - %H:%M\"),\n }", "def parse_event(self, event):\n # how do I do what event it is without a type\n if \"type\" not in event:\n return\n # look for chat messages\n if (event[\"type\"] == \"message\") & (\"text\" in event):\n print(event)\n # grab message info\n try:\n msg = event[\"text\"]\n sender = event[\"user\"]\n channel = event[\"channel\"]\n except KeyError as e:\n print(\"Got a malformed message packet\", e)\n return\n \n print(u\"From {0}@{1}\".format(sender, channel))\n msg_parsed = self.parse_txt(msg)\n try:\n self.craft_response(msg_parsed, sender, channel)\n except IndexError:\n # woops, message was too short we index errored\n return", "def parse_reply(self, message):\n message = Message(message)\n if self.topic_key or message.recipient_id != self.id:\n # We already know the topic key or the message wasn't for us,\n # disregard.\n return False\n\n topic_key = self._asymmetric_crypto.decrypt(\n message.encrypted_topic_key, message.encryption_key\n )\n self.topic_key = topic_key\n return True", "def handle_reply(self, msg):\n print msg", "def _get_message(self, service):\r\n while True:\r\n try:\r\n data = self._get_next_message(service)\r\n except UssServiceReponseError:\r\n # Check next response, this was not ours.\r\n continue\r\n return data" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the file descriptor used for passing to the select call when listening on the message queue.
def get_file_descriptor(self): return self._subscription.connection and self._subscription.connection._sock.fileno()
[ "def get_channel_handler_by_fd(self, sock_fileno):\r\n with self.channel_fds_lock:\r\n if self.channel_fds.get(sock_fileno):\r\n return self.channel_fds[sock_fileno].handler\r\n return None", "def get_connection_poller():\r\n if hasattr(select, \"epoll\"):\r\n return select.epoll()\r\n else:\r\n return _Select()", "def get_node_descriptor(self):\n self._start_process(sync=True)\n\n return self.__node_descriptor", "def get_fd(fileobj):\n if IS_WINDOWS:\n import msvcrt\n return msvcrt.open_osfhandle(fileobj.fileno(), os.O_TEXT)\n return fileobj.fileno()", "def termfd(self):\n for fd in (2, 1, 0):\n if os.isatty(fd):\n return fd\n raise Exception(\"No TTY could be found\")", "def fileno(self):\n return self._device.fileno()", "def get_socket(self, addr):\n return self.connections[addr].sock", "def get_open_fds():\n #\n import resource\n import fcntl\n #\n fds = []\n soft , hard = resource.getrlimit(resource.RLIMIT_NOFILE)\n for fd in range ( 0 , soft ) :\n try:\n flags = fcntl.fcntl(fd, fcntl.F_GETFD)\n except IOError:\n continue\n fds.append ( fd )\n return tuple ( fds )", "def fileno(self):\n return self._fileno", "def file_handle(self):\n return self._fh", "def fileno(self) -> int:\n return self._file.fileno()", "def poll(fd, mask, core=None):\n return (core or Core.local()).poll(fd, mask)", "def create_fd(self, inodeid):\n newfd = openfd(self.nextid, inodeid)\n self.nextid += 1\n return newfd.id", "def _select(self):\n readable = []\n for sock in self.serverTransport:\n readable.append(sock.handle.fileno())\n writable = []\n print(\"33339999\")\n try:\n res = select.select(readable, writable, readable)\n except Exception as e:\n res = None\n print(\"333399991%s\" % [res, e])\n else:\n print(\"333399992%s\" % [res])\n return res", "def preferred_disk_dedicated_io_thread(self):\n return self._preferred_disk_dedicated_io_thread", "def socket_path(self):\n return self._shell._socket_path", "def recv(f):\n return Command.from_buf(f.read(HID_buf_size))", "def get_host_socket(self):\n return self.host_socket", "def _get_process_fd_limit(cls, pid):\n with open('/proc/{}/limits'.format(pid)) as f:\n limits = f.read()\n match = re.search(r'^Max open files\\s+(\\d+)\\s+\\d+\\s+files',\n limits, flags=re.MULTILINE)\n if not match:\n raise Exception('Cannot parse /proc/{}/limits'.format(pid))\n return int(match.group(1))", "def get_max_fileno(default: int=2048):\n limit = resource.getrlimit(resource.RLIMIT_NOFILE)[1]\n if limit == resource.RLIM_INFINITY:\n return default\n return limit" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Begins a new game by taking in a list of ters and a list of civs. Play out a series of turns and end the game when one player reaches the victory points.
def New_Game(board, players, victory): for civ in players: print(civ.start) for home in civ.start: for ter in board: if home==ter: ter.owner=civ turn = 1 return take_turn(board,players,turn,victory,orders=[])
[ "def start(self):\r\n adventure = input(\"Would you like to go to the beach or the forest?\")\r\n if adventure == \"beach\":\r\n Beach(self.player).start()\r\n elif adventure == \"forest\":\r\n Forest(self.player).start()\r\n else:\r\n print(\"Hmmm, I don't know where that is. Let's try again\")\r\n self.start()\r\n if self.continue_game():\r\n self.start()", "def continue_game(self):\n self.game()", "def start_game(self):\n while not self._is_win_or_tie():\n self._do_turn()", "def start_game(self):\n\n self.time_up.start()\n self.pig.start_game()", "async def start_games(self):\n now = datetime.utcnow()\n conn = self.bot.pool\n games_id, start_time = await self.get_next_games()\n # games_id = 22\n if games_id:\n # sql = \"SELECT start_time FROM rcs_events WHERE event_id = $1\"\n # start_time = await conn.fetchval(sql, games_id)\n if start_time - now < timedelta(minutes=10):\n to_insert = []\n counter = 0\n async for clan in self.bot.coc.get_clans(clans):\n async for member in clan.get_detailed_members():\n counter += 1\n to_insert.append((counter,\n games_id,\n member.tag[1:],\n clan.tag[1:],\n member.get_achievement(\"Games Champion\").value,\n 0, None\n ))\n sql = (\"INSERT INTO uw_clan_games \"\n \"(event_id, player_tag, clan_tag, starting_points, current_points, max_reached) \"\n \"SELECT x.event_id, x.player_tag, x.clan_tag, x.starting_points, \"\n \"x.current_points, x.max_reached \"\n \"FROM unnest($1::uw_clan_games[]) as x\")\n await conn.execute(sql, to_insert)\n self.bot.logger.info(f\"{counter} players added to UW Clan Games event. Game on!\")", "def launch():\n\n Game.separator(1)\n print 'Welcome to Rock-Paper-Scissor'\n Game.separator(1)\n print 'Please type s to start'\n\n player, srv_addr = Game.init()\n\n Game.connect(player, srv_addr)\n\n Game.share_graphs(player)\n\n playing(player)\n\n while Game.play_again(player):\n playing(player)", "def main():\n for i in range(3):\n put_beeper_slot()\n turn_left()\n move()\n turn_right()\n if front_is_clear():\n move()", "def _take_turns(self):\n # Beginning with the first player,\n # alternate turns between players until the game ends\n self.current_player_id = 1 # the id of the current player\n user_command = '' # the command entered by the user\n while(self.board.is_game_over() is False):\n if self.current_player_id == self.computer_player_id: \n self.board.take_best_move(self.computer_player_id)\n # End turn and allow the user to take a turn\n self.current_player_id = self.user_player_id\n else:\n # Display the board\n self.board.display()\n # Remind the user whether they are X's or O's\n if self.user_player_id == 1:\n print \"You are X's\"\n else:\n print \"You are O's\"\n # Ask user to input the coordinates of her mark, or to press q to quit\n user_command = raw_input('<enter \"{rowNum}, {columnNum}\" or \"q\" to quit>: ')\n print \"\"\n # Process the user command\n if user_command.lower().strip() == 'q':\n # End the game\n break\n else:\n # Mark the board for the user\n self._mark_board_for_user(user_command)\n # Display final board \n self.board.display()\n # Determine winner\n self.winner_id = self.board.get_winner()", "def start_game(self):\n self.turn_cycle = cycle(self.turn_order)\n self.current_player_id = next(self.turn_cycle)\n self.game_started = True", "def game_start():\n\n game_intro()\n input(\"\\nPress Enter to start the game\")\n clear_screen()\n\n # store each games' function inside a list to iterate like a controller\n stage_list = [game_stage1, game_stage2, game_stage3]\n\n # game controller\n for each_game_stage in stage_list:\n score, result = each_game_stage()\n\n set_player_score(score)\n\n # check each stage if they really fail the test or not (2 fails out of 3)\n if is_player_failed():\n game_fail()\n break\n print(result)\n\n return", "def _main(self):\n\n\t\twhile self.active == True:\n\t\t\talive_players = [x for x in self.players.itervalues() if x.alive]\n\t\t\t\n\t\t\tif len(alive_players) <= 1:\n\t\t\t\tself._end()\n\t\t\telse: \n\t\t\t\tself.last_alive = alive_players\n\t\t\tif time.time() - self.start_time > 600:\n\t\t\t\tself._end()\n\t\t\twith self.action_list_lock:\n\t\t\t\tturns_submitted = len(self.completed_turns[self.turn])\n\t\t\tif turns_submitted == len(alive_players):\n\t\t\t\t\tself._resolve_turn()\n\t\t\telif time.time() - self.last_turn_time > 2:\n\t\t\t\t\tself._resolve_turn()\n\t\t\telse:\n\t\t\t\tcontinue", "def step(self):\n #Get random player\n players = [random.choice(list(self.G.nodes()))]\n # if this player has at least two neighbors, go into a truel; otherwise, go into a duel\n if len(self.G[players[0]]) > 1:\n players.extend(_random_subset(list(self.G[players[0]]), 2))\n #print(\"Truel: \", players)\n players = self.sequential_truel(players)\n\n elif len(self.G[players[0]]) == 1:\n players.extend(_random_subset(list(self.G[players[0]]), 1))\n #print(\"Duel: \", players)\n players = self.random_duel(players)\n\n #Clear list after done\n players = []", "def run_tournament(self):\r\n self.notify_tournament_start()\r\n while not self.check_end():\r\n round_results = self.run_round()\r\n self.remaining_players = [self.id_dict[winner_id] for winner_id in round_results['winners']]\r\n self.round_results.append(self.remaining_players)\r\n self.cheating_players.update([self.id_dict[cheater_id] for cheater_id in round_results['cheaters']])\r\n self.failed_players.update([self.id_dict[failed_id] for failed_id in round_results['failed']])\r\n\r\n self.notify_tournament_end()", "def playDarts(tortle):\n player1_score = 0\n player2_score = 0\n for i in range(10):\n throwDart(tortle)\n if isInCircle(tortle, (0,0), 1):\n player1_score += 1\n throwDart(tortle)\n if isInCircle(tortle, (0,0), 1):\n player2_score += 1\n print('Player 1 has ' + str(player1_score) + ' point(s). Player 2 has '+ str(player2_score) + ' point(s).')\n if player1_score > player2_score:\n print(\"Player 1 is the winner!\")\n elif player2_score > player1_score:\n print(\"Player 2 is the winner!\")\n else:\n print(\"Neither player has one; it's a draw!\")", "def main():\n config = read_config()\n\n civ_pop = int(config['people']['civilians'])\n mil_pop = int(config['people']['troops'])\n civ_hit_rate = int(config['people']['civilianHitRate'])\n mil_hit_rate = int(config['people']['troopHitRate'])\n mil_killed = 0\n\n print(\"storming Area-51\")\n print(\"civilian hit rate set to :\" + config['people']['civilianHitRate'])\n print(\"military hit rate set to :\" + config['people']['troopHitRate'])\n\n # First call of fight,\n result, mil_killed, civ_pop = fight(mil_pop, civ_pop, mil_killed, civ_hit_rate, mil_hit_rate)\n\n # Only if the civialans have won the first fight will it generate the rest of the base\n # no point running code that will never be used.\n if result == FightResult.WIN:\n alien_spawn = int(config['base']['aliensSpawn'])\n alien_alignment = config['aliens']['alignment']\n\n floor_min = int(config['base']['floorMinimum'])\n floor_max = int(config['base']['floorMaximum'])\n\n number_of_floors = random.randrange(floor_min, floor_max + 1)\n current_floor = 1\n while current_floor <= number_of_floors and civ_pop > 0:\n civ_pop, current_floor = building_fight(alien_alignment, alien_spawn, civ_hit_rate, civ_pop, config,\n current_floor, mil_hit_rate, mil_killed)", "def main():\n run_game(even)", "def start(self, override_dice=[]):\n self.started = True\n player_counter = 0\n for player in self.players:\n assigned_color = self.colors[player_counter]\n self.status[assigned_color] = {}\n self.status[assigned_color]['active'] = True\n self.status[assigned_color]['has_won'] = False\n player.startGame(assigned_color)\n player_counter += 1\n while self.have_winner() == None and not self.all_eliminated():\n for player in self.players:\n if self.is_active(player.color):\n doubles = True\n doubles_count = 0\n while doubles:\n if override_dice != []:\n new_dice = override_dice\n else:\n new_dice = Dice().result\n if len(new_dice) == 4:\n #print(\"Game::start: player has a double\")\n #print(\"Game::start: current double count: \"+str(doubles_count))\n doubles_count += 1\n if doubles_count == 3:\n player.doublesPenalty()\n self.move_back_furthest_pawn(player.color)\n return ##debugging\n break\n if not self.board.all_out(player.color):\n new_dice = new_dice[:2]\n elif len(new_dice) == 2:\n doubles = False\n moves = player.doMove(self.board, new_dice)\n rc = RuleChecker(self.board, new_dice, player.color)\n for move in moves:\n try:\n is_bonus = move.distance in rc.tvals.bonus\n except AttributeError: #is an EnterPiece\n is_bonus = False\n valid = rc.single_move_check(move, is_bonus_move=is_bonus)\n if not valid:\n self.eliminate_player(player)\n break\n if not self.is_active(player.color):\n continue\n else:\n if not rc.multi_move_check(moves):\n self.eliminate_player(player)\n continue\n self.board = rc.b_final", "def start_game(self):\n\n player1 = Player(input(\"Who is the first player? \"), 'X')\n player2 = Player(input(\"Who is the second player? \"), 'O')\n\n self.players = [player1, player2]\n self.current_player = random.choice(self.players)\n\n print(\"-----------------------------------------------------------------------------------------------\")\n print(f\"Welcome to the game {player1.name} and {player2.name}, good luck!\")\n print(f\"{player1.name} will be {player1.badge}s and {player2.name} will be {player2.badge}s.\")\n print(\"To make a move enter a letter followed by a number to indicate the square you want to play in.\")\n print(\"-----------------------------------------------------------------------------------------------\")\n\n self.grid.print_grid()", "def pursue(self):\r\n last_attacker = self.db.last_attacker\r\n players = [obj for obj in self.location.contents if utils.inherits_from(obj, BASE_CHARACTER_TYPECLASS) and not obj.is_superuser]\r\n if players:\r\n # we found players in the room. Maybe we caught up with some,\r\n # or some walked in on us before we had time to pursue them.\r\n # Switch to battle mode.\r\n self.battle_mode = True\r\n self.roam_mode = False\r\n self.pursue_mode = False\r\n else:\r\n # find all possible destinations.\r\n destinations = [ex.destination for ex in self.location.exits\r\n if ex.access(self, \"traverse\")]\r\n # find all players in the possible destinations. OBS-we cannot\r\n # just use the player's current position to move the Enemy; this\r\n # might have changed when the move is performed, causing the enemy\r\n # to teleport out of bounds.\r\n players = {}\r\n for dest in destinations:\r\n for obj in [o for o in dest.contents\r\n if utils.inherits_from(o, BASE_CHARACTER_TYPECLASS)]:\r\n players[obj] = dest\r\n if players:\r\n # we found targets. Move to intercept.\r\n if last_attacker in players:\r\n # preferably the one that last attacked us\r\n self.move_to(players[last_attacker])\r\n else:\r\n # otherwise randomly.\r\n key = players.keys()[random.randint(0, len(players) - 1)]\r\n self.move_to(players[key])\r\n else:\r\n # we found no players nearby. Return to roam mode.\r\n self.battle_mode = False\r\n self.roam_mode = True\r\n self.pursue_mode = False", "def _start(self):\n beginner = random.choice((1, 2)) # game begins from random player\n if beginner == 1:\n self._players[1].set_symbol('x')\n self._players[2].set_symbol('o')\n self.current_player = 1\n else:\n self._players[2].set_symbol('x')\n self._players[1].set_symbol('o')\n self.current_player = 2\n print('current player: {}'.format(str(self._players[self.current_player])))" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes in an old board and a list of 3term tuples which describe player investments. It then calculates which player had the greatest investment in each territory and changes owners. Finally, it counts up the values of each territory and supplies the owner with the appropriate points.
def eval_orders(board,orders): contests = [] for order in orders: #in case a player has no orders if order==[]: orders.remove([]) for ter in board: for player in orders: for order in player: territory=order[0] contender = order[2] bid = order[1] if ter.name==territory.name: if ter not in contests: contests.append(ter) if bid>ter.highest: ter.highest=bid ter.leader=contender elif bid==ter.highest: ter.leader=ter.owner for ter in contests: #actual function if ter.leader!=None: ter.owner=ter.leader for elem in board: if elem.name==ter.name: board.remove(elem) board.append(ter) for ter in board: if ter.owner!=None: ter.owner.score+=ter.value return board
[ "def formWorstLineup(team):\n players = list(map(lambda Batter: Batter.transitionMatrixSimple(), team.batters))\n averagePlayer = team.averagePlayer().transitionMatrixSimple()\n availablePositions = set(range(9))\n worstLineup = [team.averagePlayer()] * 9\n for bestRemaining in range(4):\n worstRemaining = 8 - bestRemaining\n # Expected runs, best placement, worst placement\n worstPerforming = (10, 0, 0)\n for bestPos in availablePositions:\n for worstPos in availablePositions:\n if bestPos != worstPos:\n matrices = [averagePlayer] * 9\n matrices[bestPos] = players[bestRemaining]\n matrices[worstPos] = players[worstRemaining]\n scoreDistribution = simulateMarkovChain(matrices)[:, 216]\n expRuns = 0\n for i in range(21):\n expRuns += i * scoreDistribution[i]\n if expRuns < worstPerforming[0]:\n worstPerforming = (expRuns, bestPos, worstPos)\n availablePositions.remove(worstPerforming[1])\n availablePositions.remove(worstPerforming[2])\n worstLineup[worstPerforming[1]] = team.batters[bestRemaining]\n worstLineup[worstPerforming[2]] = team.batters[worstRemaining]\n worstLineup[availablePositions.pop()] = team.batters[4]\n return worstLineup", "def _update_vorp(self, ap=None, pp=None):\n # should maybe cancel this.. it takes time to compute and we have lots\n # of thresholds now. It may be called more often than is necessary.\n if ap is None:\n ap = self.ap\n if pp is None:\n pp = self.pp\n\n positions = [\n pos\n for pos in list(self.n_roster_per_team.keys())\n if pos not in [\"FLEX\", \"BENCH\"]\n ]\n\n for pos in positions:\n # also implement: maximum players on roster\n # TODO: implement that max in the WAIV designation as well (elsewhere)\n # maximum probably won't matter for most drafts, so de-prioritize it\n # while your draft is in an hour :E\n\n pos_picked = (\n pp[pp.index.get_level_values(\"pos\") == pos] if not pp.empty else pp\n )\n n_pos_picked = len(pos_picked.index)\n n_waiv_picked = len(pos_picked[pos_picked.tier == \"FA\"].index)\n # if any managers picked waiver-tier players, then we can shed\n # the next-worst bench player from our calculations\n # we can still shed all WAIV players since this case raises the value of the threshold\n posdf = ap[ap.index.get_level_values(\"pos\") == pos] if not ap.empty else ap\n # pos_draftable = self.ap[(self.ap.pos == pos) & (self.ap.tier != 'FA')]\n pos_draftable = posdf[posdf.tier != \"FA\"]\n n_pos_draftable = len(pos_draftable.index) - n_waiv_picked\n vorp_baseline = 0\n if n_pos_draftable <= 0:\n # no more \"draftable\" players -- vorp should be zero for top\n vorp_baseline = ap[ap.index.get_level_values(\"pos\") == pos][\n \"value\"\n ].max()\n else:\n frac_through_bench = (\n n_pos_picked * 1.0 / (n_pos_picked + n_pos_draftable)\n )\n backup_mask = pos_draftable[\"tier\"] == \"BU\"\n # we also need to include the worst starter in our list to make it agree\n # with VOLS before any picks are made\n worst_starters = pos_draftable[~backup_mask].sort_values(\n \"value\", ascending=True\n )\n ls_index = None # index of worst starter in position\n # fw_index = None # index of best wavier option in position (assuming ADP)\n if not worst_starters.empty:\n ls_index = worst_starters.index[0]\n # if len(best_waivers) > 0:\n # fw_index = best_waivers.index[0]\n pos_baseline = pos_draftable.loc[[ls_index]]\n n_pos_baseline = len(pos_baseline.index)\n if n_pos_baseline == 0:\n # this can happen, e.g. with kickers who have no \"backup\" tier players\n ap.loc[ap.index.get_level_values(\"pos\") == pos, \"vorp\"] = ap[\n \"value\"\n ]\n continue\n index = int(frac_through_bench * n_pos_baseline)\n if index >= len(pos_baseline):\n print(\"warning: check index here later\")\n index = len(pos_baseline - 1)\n vorp_baseline = (\n pos_baseline[\"value\"].sort_values(ascending=False).iloc[index]\n )\n ap.loc[ap.index.get_level_values(\"pos\") == pos, \"vorp\"] = (\n ap[\"value\"] - vorp_baseline\n )", "def leaderboard_change(\n df: pd.DataFrame, leaderboard_func: Callable = get_wins_leaderboard\n) -> pd.DataFrame:\n\n # Get current leaderboard\n current_leaderboard = leaderboard_func(df).reset_index()\n\n # Get leaderboard from last week\n last_week_df = exclude_most_recent_week(df)\n last_week_leaderboard = leaderboard_func(last_week_df).reset_index()\n\n # Merge the leaderboards on 'team_owner'\n leaderboard_change = (\n current_leaderboard.drop(columns=[\"outcome\"])\n .merge(\n last_week_leaderboard.drop(columns=[\"outcome\"]),\n on=\"team_owner\",\n suffixes=(\"_current\", \"_last\"),\n )\n .set_index(\"team_owner\")\n )\n\n # Subtract the two weeks to find the change in leaderboard postioning\n leaderboard_change[\"change\"] = (\n leaderboard_change.index_last - leaderboard_change.index_current\n )\n\n return leaderboard_change", "def formBestLineup(team):\n players = list(map(lambda Batter: Batter.transitionMatrixSimple(), team.batters))\n averagePlayer = team.averagePlayer().transitionMatrixSimple()\n availablePositions = set(range(9))\n bestLineup = [team.averagePlayer()] * 9\n for bestRemaining in range(4):\n worstRemaining = 8 - bestRemaining\n # Expected runs, best placement, worst placement\n bestPerforming = (0, 0, 0)\n for bestPos in availablePositions:\n for worstPos in availablePositions:\n if bestPos != worstPos:\n matrices = [averagePlayer] * 9\n matrices[bestPos] = players[bestRemaining]\n matrices[worstPos] = players[worstRemaining]\n scoreDistribution = simulateMarkovChain(matrices)[:, 216]\n expRuns = 0\n for i in range(21):\n expRuns += i * scoreDistribution[i]\n if expRuns > bestPerforming[0]:\n bestPerforming = (expRuns, bestPos, worstPos)\n availablePositions.remove(bestPerforming[1])\n availablePositions.remove(bestPerforming[2])\n bestLineup[bestPerforming[1]] = team.batters[bestRemaining]\n bestLineup[bestPerforming[2]] = team.batters[worstRemaining]\n bestLineup[availablePositions.pop()] = team.batters[4]\n return bestLineup", "def retrieve_player_stats(player1,player2,date,r,sur,year):\n\t#COMMON OPPONENTS APPROACH\n\t#print(\"Retrieving data about {} with respect to {} for matches before {}...\".format(player1,player2,date))\n\t\n\t#TIME DISCOUNTING\n\t#we try to give higher weight to most recent matches\n\t#to do so, we select the rows of interest AND the difference (in years) from the present date which will serve as weight\n\n\t####\n\t#games played by player1 in the most recent 5 years\n\tg1=df[((df[\"winner_name\"]==player1) | (df[\"loser_name\"]==player1)) & ((df[\"tourney_date\"]<date) | (\\\n\t\t(df[\"tourney_date\"]==date) & (df[\"round\"]<r))) & (year-df[\"year\"]<=5)]\n\t\n\tow=list(g1.loc[(g1.winner_name==player1, 'loser_name')].values[:])\n\tol=list(g1.loc[(g1.loser_name==player1, 'winner_name') ].values[:])\n\to1=set(ow+ol) #player 1 opponents\n\n\t#games played by player2\n\tg2=df[((df[\"winner_name\"]==player2) | (df[\"loser_name\"]==player2)) & ((df[\"tourney_date\"]<date) | (\\\n\t\t(df[\"tourney_date\"]==date) & (df[\"round\"]<r))) & (year-df[\"year\"]<=5)]\n\t\n\tow=list(g2.loc[(df.winner_name==player2, 'loser_name')].values[:])\n\tol=list(g2.loc[(df.loser_name==player2, 'winner_name') ].values[:])\n\to2=set(ow+ol) #player 2 opponents\n\n\t#list of common opponents \n\tco=[x for x in o1 if x in o2]\n\t#print(\"Common opponents in the last 5 years:\")\n\t#print(co)\n\n\tcolumn_names=[\"fs\",\"w1sp\",\"w2sp\",\"wsp\",\"wrp\",\"tpw\",\"aces\",\"df\",\"bpc\",\"bps\",\"bpo\",\"bpw\",\"tmw\",\"data_amount\",\"opponent\",]\n\taverages=pd.DataFrame(columns=column_names) #df to be filled with one row per opponent\n\t\n\tif len(co)>=5:\n\t\t\n\t\tcount=0\n\t\t#now evaluate average statistics of player1 wrt to each common opponent, then we'll do the average\n\t\tfor o in co:\n\t\t\t#print(\"Matches of {} vs {}...\".format(player1,o))\n\t\t\ttot_w=0\n\t\t\ttot_l=0\n\n\t\t\t#select matches of player 1 vs opponent o\n\t\t\tm=df[((((df[\"winner_name\"]==player1) & (df[\"loser_name\"]==o))) | ((df[\"winner_name\"]==o) & (df[\"loser_name\"]==player1))) & \\\n\t\t\t((df[\"tourney_date\"]<date) | ((df[\"tourney_date\"]==date) & (df[\"round\"]<r))) & (year-df[\"year\"]<=5)]\n\t\t\tif m.shape[0] > 0:\n\t\t\t\t#we have min 2 past matches against opponent o\n\t\t\t\t#won matches\n\t\t\t\tw=m[m[\"winner_name\"]==player1].loc[:,['w_fs', 'w_w1s', 'w_w2s', 'w_wsp', 'w_wrp', 'w_tpw', 'w_apg', 'w_dfpg', 'w_bppg', 'w_bps', 'l_bppg', 'l_bps', 'loser_name',\\\n\t\t\t\t'tourney_date','surface']].rename(columns={'w_fs':'fs','w_w1s':'w1s','w_w2s':'w2s','w_wsp':'wsp','w_wrp':'wrp','w_tpw':'tpw','w_apg':'apg','w_dfpg':'dfpg','w_bppg':'bppg',\\\n\t\t\t\t'w_bps':'bps','l_bppg':'bpo','l_bps':'l_bps','loser_name':'opponent', 'tourney_date':'date','surface':'s'})\n\t\t\t\tif w.shape[0]>0:\n\t\t\t\t\tw[\"bpc\"]=w.apply(lambda row: 1-row[\"l_bps\"],axis=1)\n\t\t\t\t\t#set year difference param.\n\t\t\t\t\tw[\"year_diff\"]=w.apply(lambda row: int(date.year-row[\"date\"].year), axis=1)\n\n\t\t\t\t\ttot_w=w.shape[0]\n\t\t\t\tw=w.drop(\"l_bps\", axis=1)\n\n\t\t\t\t#lost matches\n\t\t\t\tl=m[m[\"loser_name\"]==player1].loc[:,['l_fs', 'l_w1s', 'l_w2s', 'l_wsp', 'l_wrp', 'l_tpw', 'l_apg', 'l_dfpg', 'l_bppg', 'l_bps', 'w_bppg', 'w_bps', 'winner_name',\\\n\t\t\t\t'tourney_date','surface']].rename(columns={'l_fs':'fs','l_w1s':'w1s','l_w2s':'w2s','l_wsp':'wsp','l_wrp':'wrp','l_tpw':'tpw','l_apg':'apg','l_dfpg':'dfpg','l_bppg':'bppg',\\\n\t\t\t\t'l_bps':'bps','w_bppg':'bpo','w_bps':'w_bps','winner_name':'opponent','tourney_date':'date','surface':'s'})\n\t\t\t\tif l.shape[0]>0:\n\t\t\t\t\tl[\"bpc\"]=l.apply(lambda row: 1-row[\"w_bps\"],axis=1)\n\t\t\t\t\t\n\t\t\t\t\tl[\"year_diff\"]=l.apply(lambda row: int(date.year-row[\"date\"].year), axis=1)\n\n\t\t\t\t\ttot_l=l.shape[0]\n\t\t\t\t\t\n\t\t\t\tl=l.drop(\"w_bps\", axis=1)\n\n\t\t\t\t#join the two datframes, so that we have all the matches\n\t\t\t\tj = pd.concat([w, l],sort=False)\n\t\t\t\t#weight for surface\n\t\t\t\tj[\"s_ref\"]=j.apply(lambda row: sur,axis=1) #reference surface of match under study\n\t\t\t\tj[\"s_w\"]=j.apply(surface_weighting,axis=1) #surface weight of each previous match\n\t\t\t\tj=j.drop(\"s\", axis=1) #not useful anymore\n\n\t\t\t\t#assign weight which decreases as year_diff is higher\n\t\t\t\tj[\"discounting\"]=j.apply(time_discount,axis=1)\n\t\t\t\t#further multiply time weights by surface weights\n\t\t\t\tj[\"discounting\"]=j.apply(lambda row: row[\"discounting\"]*row[\"s_w\"],axis=1)\n\t\t\t\tj=j.drop(\"s_ref\", axis=1)\n\t\t\t\tj=j.drop(\"s_w\", axis=1)\n\t\t\t\tj=j.drop(\"year_diff\", axis=1)\n\n\t\t\t\t#print(j)\n\t\t\t\ttot_weights=j[\"discounting\"].sum()\n\t\t\t\t#normalize weights to sum to 1\n\t\t\t\tj[\"discounting\"]=j.apply(lambda row: row[\"discounting\"]/j[\"discounting\"].sum(),axis=1)\n\t\t\t\t#print(j)\n\t\t\t\t#weight all the matches for the discounting param\n\t\t\t\t#hence, multiply columns 0-11 for column \"discounting\"\n\t\t\t\tj.update(j.iloc[:, 0:11].mul(j.discounting, 0))\n\t\t\t\tj[\"bpc\"]=j.apply(lambda row: row[\"bpc\"]*row[\"discounting\"],axis=1)\n\t\t\t\t#now to have the weghted average of each stat, sum all the column\n\t\t\t\tavg=list(j.sum(axis=0,numeric_only=True)[0:12])\n\t\t\t\tavg.append(tot_w/(tot_w+tot_l)) #append % of matches won against o\n\t\t\t\t#UNCERTAINTY\n\t\t\t\t#print(\"Uncertainty: 1/{}\".format(tot_weights))\n\t\t\t\tavg.append(tot_weights) #add \"data amount\" CHANGED FROM BEFORE!!\n\t\t\t\tavg.append(o)\n\t \t\t\n\t \t\t#NOW we have data for past matches of player1 against common opponent o\n\t\t\t\t#add to dataframe, go to next one\n\t\t\t\taverages.loc[count]=avg\n\t\t\t\tcount+=1\n\n\t\t\t\t#print(j)\n\t\t\t\n\t\t\t\n\t#at the end of the loop, return the dataframe\n\t#in the outer function, compute general uncertainties with data of the two players combined, \n\t#then evaluate average statistics btw all the common opponents for each player - finally, build the ultimate feature vector\n\t#print(averages)\n\treturn averages", "def updateRanks(winner, loser, decr_uncertainty=0.002, min_uncertainty=0.05):\n # Check that both competitors are valid.\n try:\n isValidCompetitor(winner)\n isValidCompetitor(loser)\n except:\n raise TypeError(\"Invalid competitor\")\n\n # Determine the favored competitor.\n favored = None\n favored_rank = 0\n unfavored_rank = 0\n if winner[\"rank\"] > loser[\"rank\"]:\n favored = winner[\"id\"]\n favored_rank = winner[\"rank\"]\n unfavored_rank = loser[\"rank\"]\n else:\n favored = loser[\"id\"]\n favored_rank = loser[\"rank\"]\n unfavored_rank = winner[\"rank\"]\n\n # Update winner's rank\n uncertainty = 0.10 # Default uncertainty value.\n if \"uncertainty\" in winner:\n uncertainty = winner[\"uncertainty\"]\n if uncertainty > (min_uncertainty + decr_uncertainty):\n winner[\"uncertainty\"] = uncertainty - decr_uncertainty\n else:\n winner[\"uncertainty\"] = min_uncertainty\n if favored == winner[\"id\"]:\n winner[\"rank\"] = favored_rank + (uncertainty * unfavored_rank)\n else:\n winner[\"rank\"] = unfavored_rank + (uncertainty * favored_rank)\n\n # Update loser's rank\n uncertainty = 0.10 # Default uncertainty value.\n if \"uncertainty\" in loser:\n uncertainty = loser[\"uncertainty\"]\n if uncertainty > (min_uncertainty + decr_uncertainty):\n loser[\"uncertainty\"] = uncertainty - decr_uncertainty\n else:\n loser[\"uncertainty\"] = min_uncertainty\n if favored == loser[\"id\"]:\n loser[\"rank\"] = favored_rank - (uncertainty * favored_rank)\n else:\n loser[\"rank\"] = unfavored_rank - (uncertainty * unfavored_rank)\n\n return winner, loser", "def largest_gold_difference(olympic_medal_table):\n \n # (i)\n without_totals = olympic_medal_table.loc[:151,] # 151 included.\n without_totals = without_totals.set_index(\"team_name\") # Set \"team_name\" as index.\n diff = without_totals[\"no_summer_golds\"] - without_totals[\"no_winter_golds\"]\n return diff.idxmax()\n \n \n # (ii)", "def final_penguins_num2(game, ice, my_arrival_turn=-1, groups=[]):\n if ice in game.get_my_icebergs():\n status = \"mine\"\n elif ice in game.get_neutral_icebergs():\n status = \"neutral\"\n else:\n status = \"enemy\"\n my_penguin_amount = ice.penguin_amount\n if status == \"enemy\":\n my_penguin_amount *= -1\n last_group_turns_till_arrival = 0\n groups_toward_ice = [g for g in game.get_all_penguin_groups() if g.destination.equals(ice)]\n groups_toward_ice.sort(key=lambda g: some(g, groups))\n \n temp = groups_toward_ice[:]\n for g in temp:\n if g not in groups:\n total_d = calc_real_dis(g.source, ice)\n else:\n total_d = calc_illuse_dis(g.source, ice)\n kizuz = [grp for grp in game.get_all_penguin_groups() if grp.source.equals(ice) and grp.destination.equals(g.source)]\n for k in kizuz:\n if g not in groups:\n g_turn_till_arrival = real_turn_teal_arrival(g)\n else:\n g_turn_till_arrival = illusion_turn_teal_arrival(g)\n if real_turn_teal_arrival(k) + g_turn_till_arrival >= total_d: \n kiz = g.penguin_amount - k.penguin_amount\n if kiz < 0:\n kiz = 0\n g.penguin_amount = kiz\n groups_toward_ice[groups_toward_ice.index(g)].penguin_amount = kiz\n\n for g in groups_toward_ice:\n if g in game.get_my_decoy_penguin_groups():\n continue\n if g not in groups:\n g_turn_till_arrival = real_turn_teal_arrival(g)\n else:\n g_turn_till_arrival = illusion_turn_teal_arrival(g)\n \n if status == \"mine\":\n my_penguin_amount += (g_turn_till_arrival - last_group_turns_till_arrival) * ice.penguins_per_turn\n elif status == \"enemy\": # or status==\"neutral\":\n my_penguin_amount -= (g_turn_till_arrival - last_group_turns_till_arrival) * ice.penguins_per_turn\n \n if g in game.get_enemy_penguin_groups():\n my_penguin_amount -= g.penguin_amount\n else:\n my_penguin_amount += g.penguin_amount\n \n if my_penguin_amount > 0:\n status = \"mine\"\n elif my_penguin_amount == 0:\n status = \"neutral\"\n else:\n status = \"enemy\"\n last_group_turns_till_arrival = g_turn_till_arrival\n \n return my_penguin_amount, last_group_turns_till_arrival, status", "def RankPlayers(players):\r\n #Weights:\r\n WIN_PER = 10\r\n AVG_PTS = 4 \r\n AVG_DIFF = 1\r\n TM_WIN_PER = -3\r\n GP = -1\r\n OPP_WIN_PER = 3 \r\n ranks = []\r\n initorder = []\r\n\r\n for i in range(len(players)): #Creating Rank List\r\n ranks.append([players[i][0]])\r\n initorder.append(players[i][0])\r\n players[i][6] = players[i][6] / players[i][3] #Average teammate gp \r\n players[i][8] = players[i][8] / players[i][3] #average opp gp\r\n for _ in range(10): #win %, GP rank, avgPts %, team win %, Teammate GP Rank, opp win %, Opp GP Rank, Wins, Losses, Avg Diff\r\n ranks[i].append(0)\r\n #Easy transfer Data\r\n ranks[i][1] = round(players[i][1]/players[i][3],3)\r\n ranks[i][3] = round(players[i][4]/10,3)\r\n ranks[i][4] = players[i][5]\r\n ranks[i][6] = players[i][7]\r\n ranks[i][8] = players[i][1]\r\n ranks[i][9] = players[i][2]\r\n ranks[i][10] = players[i][9]/10 #Dividing by 10 to get a good multiplier\r\n\r\n #GP rank normalized\r\n players.sort(key=lambda x: x[3], reverse=True) #descending order as to create negative percentile\r\n for i in range(len(players)):\r\n ranks[initorder.index(players[i][0])][2] = round(1/(players[i][3]/players[0][3]),2)\r\n if players[i][3] < 5: #Not enough samples\r\n ranks[initorder.index(players[i][0])].append(10)\r\n elif players[i][3] < 10: #Still not enough samples\r\n ranks[initorder.index(players[i][0])].append(4)\r\n else: #Enough games played\r\n ranks[initorder.index(players[i][0])].append(0)\r\n\r\n #Teammate GP rank normalized\r\n players.sort(key=lambda x: x[6]) \r\n for i in range(len(players)):\r\n ranks[initorder.index(players[i][0])][5] = round((i+1)/len(players),2)\r\n\r\n #opp GP rank normalized\r\n players.sort(key=lambda x: x[8]) #ascending order as to create positive precentile\r\n for i in range(len(players)):\r\n ranks[initorder.index(players[i][0])][7] = round((i+1)/len(players),2)\r\n \r\n for i in range(len(ranks)):\r\n rawscore = ranks[i][1] * WIN_PER + ranks[i][11] * GP + ranks[i][3] * AVG_PTS + ranks[i][4] * TM_WIN_PER + ranks[i][6] * OPP_WIN_PER + ranks[i][10] * AVG_DIFF\r\n ranks[i].append(rawscore)\r\n #THEORETICAL MAX SCORE: 19.5\r\n ranks[i][1] = ranks[i][1] * 100 #Adjusting to readable format\r\n ranks[i][4] = ranks[i][4] * 100\r\n ranks[i][6] = ranks[i][6] * 100\r\n ranks[i][3] = ranks[i][3] * 10\r\n ranks[i][10] = ranks[i][10] * 10\r\n ranks[i][2] = len(ranks) - int(round(ranks[i][2] * len(ranks),0)) \r\n ranks[i][5] = len(ranks) - int(round(ranks[i][5] * len(ranks),0)) + 1\r\n ranks[i][7] = len(ranks) - int(round(ranks[i][7] * len(ranks),0)) + 1\r\n\r\n ranks.sort(key=lambda x: x[2],reverse=True) #Fixing GP Rank\r\n for i in range(len(ranks)):\r\n ranks[i][2] = i + 1\r\n\r\n #Final Ranking\r\n ranks.sort(key=lambda x: x[12],reverse=True) \r\n data={'Name':[i[0] for i in ranks], 'WINS':[i[8] for i in ranks], 'LOSSES':[i[9] for i in ranks],\r\n 'WIN %': [i[1] for i in ranks],'GP Rank':[i[2] for i in ranks],\r\n \"AVG PTS\":[i[3] for i in ranks],\"AVG DIFF\":[i[10] for i in ranks],\r\n \"AVG TM WIN %\":[i[4] for i in ranks],\"AVG TM GP Rank\":[i[5] for i in ranks],\"AVG OPP WIN %\":[i[6] for i in ranks],\"AVG OPP GP Rank\":[i[7] for i in ranks],\r\n \"Ranking Score\":[i[12] for i in ranks]}\r\n #Note: Rankings of GP, TM GP, and OPP GM: 1 means most games played, last means least games played\r\n result=pd.DataFrame(data=data)\r\n result=round(result,4)\r\n result.index += 1\r\n print(result) \r\n\r\n result = result.drop([\"WIN %\", \"GP Rank\", \"AVG TM GP Rank\", \"AVG OPP GP Rank\", \"Ranking Score\"], axis=1)\r\n result.to_csv(\"Standings/IndividualRankings.csv\")\r\n\r\n return None", "def convert(players, timea, timeb, event):\n#w_result = [2pt att, 'name', 2pt made, 'name', 3pt att, 'name', 3pt made, 'name', fg att, 'name', \n# fg made, 'name', fta, 'name', ft made, 'name', oreb, 'name', dreb, 'name', assist, 'name', \n# tov, 'name', steal, 'name', foul 'name', block, 'name', points, 'name']\n w_result = [0,'',0,'',0,'',0,'',0,'',0,'',0,'',0,'',0,'',0,'',0,'',0,'',0,'',0,'',0,'',0,'']\n#opp_result = [2pt att, 2pt made, 3pt att, 3pt made, fg att, fg made, fta, ftm, oreb, \n# dreb, assist, tov, steal, foul, block, points]\n opp_result = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\n \n players.append('team')\n\n for p in players:\n if p in event:\n willy = p\n break\n else:\n willy = None\n players.remove('team')\n\n \n #field goals\n if \"jumpshot\" in event or \"layup\" in event or \"dunk\" in event or \"tip-in\" in event:\n if \"3-pt.\" in event:\n if \"made\" in event:\n if willy is not None:\n #made 3pt.\n for i in range(4,10+1,2):\n w_result[i] = 1\n for i in range(5,11+1, 2):\n w_result[i] = willy\n w_result[-2] = 3\n w_result[-1] = willy\n return [sorted(players)] + [timea, timeb] + w_result + opp_result\n else:\n #made 3pt.\n for i in range(2,5+1):\n opp_result[i] = 1\n opp_result[-1] = 3\n return [sorted(players)] + [timea, timeb] + w_result + opp_result\n \n else:\n if willy is not None:\n #missed 3pt.\n w_result[4] = w_result[8] = 1\n w_result[5] = w_result[9] = willy\n return [sorted(players)] + [timea, timeb] + w_result + opp_result\n else:\n #missed 3pt.\n opp_result[2] = opp_result[4] = 1\n return [sorted(players)] + [timea, timeb] + w_result + opp_result\n \n else:\n if \"made\" in event:\n if willy is not None:\n #made 2pt\n for i in [0,2,8,10]:\n w_result[i] = 1\n for i in [1,3,9,11]:\n w_result[i] = willy\n w_result[-2] = 2\n w_result[-1] = willy\n return [sorted(players)] + [timea, timeb] + w_result + opp_result\n else:\n #made 2pt\n for i in [0,1,4,5]:\n opp_result[i] = 1\n opp_result[-1] = 2\n return [sorted(players)] + [timea, timeb] + w_result + opp_result\n else:\n if willy is not None:\n #missed 2pt\n w_result[0] = w_result[8] = 1\n w_result[1] = w_result[9] = willy\n return [sorted(players)] + [timea, timeb] + w_result + opp_result\n else:\n #missed 2pt\n opp_result[0] = opp_result[4] = 1\n return [sorted(players)] + [timea, timeb] + w_result + opp_result\n #free throws \n if \"freethrow\" in event:\n if \"made\" in event:\n if willy is not None:\n #made FT\n w_result[12] = w_result[14] = w_result[-2] = 1\n w_result[13] = w_result[15] = w_result[-1] = willy\n return [sorted(players)] + [timea, timeb] + w_result + opp_result\n else:\n #made FT\n opp_result[6] = opp_result[7] = opp_result[-1] = 1\n return [sorted(players)] + [timea, timeb] + w_result + opp_result\n else:\n if willy is not None:\n #missed FT\n w_result[12] = 1\n w_result[13] = willy\n return [sorted(players)] + [timea, timeb] + w_result + opp_result\n else:\n #missed FT\n opp_result[6] = 1\n return [sorted(players)] + [timea, timeb] + w_result + opp_result\n \n #rebounds\n if \"rebound\" in event:\n if \"offensive\" in event:\n if willy is not None:\n #oreb\n w_result[16] = 1\n w_result[17] = willy\n return [sorted(players)] + [timea, timeb] + w_result + opp_result\n else:\n #oreb\n opp_result[8] = 1\n return [sorted(players)] + [timea, timeb] + w_result + opp_result\n else:\n if willy is not None:\n #dreb\n w_result[18] = 1\n w_result[19] = willy\n return [sorted(players)] + [timea, timeb] + w_result + opp_result\n else:\n #dreb\n opp_result[9] = 1\n return [sorted(players)] + [timea, timeb] + w_result + opp_result\n \n if \"assist\" in event:\n if willy is not None:\n #assist\n w_result[20] = 1\n w_result[21] = willy\n return [sorted(players)] + [timea, timeb] + w_result + opp_result\n else:\n #assist\n opp_result[10] = 1\n return [sorted(players)] + [timea, timeb] + w_result + opp_result\n \n if \"turnoverby\" in event:\n if willy is not None:\n #turnover\n w_result[22] = 1\n w_result[23] = willy\n return [sorted(players)] + [timea, timeb] + w_result + opp_result\n else:\n #turnover\n opp_result[11] = 1\n return [sorted(players)] + [timea, timeb] + w_result + opp_result\n \n if \"stealby\" in event:\n if willy is not None:\n #steal\n w_result[24] = 1\n w_result[25] = willy\n return [sorted(players)] + [timea, timeb] + w_result + opp_result\n else:\n #steal\n opp_result[12] = 1\n return [sorted(players)] + [timea, timeb] + w_result + opp_result\n \n if \"foulby\" in event:\n if willy is not None:\n #foul\n w_result[26] = 1\n w_result[27] = willy\n return [sorted(players)] + [timea, timeb] + w_result + opp_result\n else:\n #foul\n opp_result[13] = 1\n return [sorted(players)] + [timea, timeb] + w_result + opp_result\n \n if \"blockby\" in event:\n if willy is not None:\n #block\n w_result[28] = 1\n w_result[29] = willy\n return [sorted(players)] + [timea, timeb] + w_result + opp_result\n else:\n #block\n opp_result[14] = 1\n return [sorted(players)] + [timea, timeb] + w_result + opp_result\n else:\n return [sorted(players)] + [timea, timeb] + w_result + opp_result", "def create_last_place_tie_teams_three_way(self):\n\n max = 6\n tie_amount = 10.0\n for i in range(1, max + 1):\n user = self.get_user(username=str(i))\n self.fund_user_account(user)\n\n lineup = Lineup()\n if i <= 3:\n # for 1, 2, 3\n lineup.test_fantasy_points = tie_amount\n else:\n # teams 4, 5, 6 should have unique test_fantasy_points\n lineup.test_fantasy_points = tie_amount + i\n\n lineup.user = user\n lineup.draft_group = self.draftgroup\n lineup.save()\n\n bm = BuyinManager(lineup.user)\n bm.buyin(self.contest_pool, lineup)\n Entry.objects.filter(contest_pool=self.contest_pool).update(contest=self.contest)\n self.contest.status = Contest.COMPLETED\n self.contest.save()", "def get_opp_stat(team_wins, team_losses, stat):\n return team_wins['L{}'.format(stat)].sum() + team_losses['W{}'.format(stat)].sum()", "def get_turnout():\n df = pd.read_excel(\"tabular/GG18 Voter TurnOut By Precinct By Party Revised.xlsx\", header=4)\n df = df[df[\"District\"] != \"---\"]\n df[\"MATCH\"] = df[\"County\"] + \" \" + df[\"District\"].apply(lambda x: x[1:]) + \"-\" + df[\"Precinct\"]\n cols = [\"County\", \"MATCH\", \"Total Voted Dem\", \"Total Voted Rep\", \"Total Voted Ind\", \"Active Registered Ind\"]\n df = df[cols]\n\n df20 = pd.read_excel(\"tabular/PG20 Turnout By Precinct by Party Revised.xlsx\", header=3)\n df20 = df20[df20[\"Precinct\"] != \"---- ---\"]\n df20[\"MATCH\"] = df20[\"County\"] + \" \" + df20[\"Precinct\"].apply(lambda x: x.replace(' ', '')[1:])\n cols = [\"County\", \"MATCH\", \"Total Voted Dem\", \"Total Voted Rep\", \"Total Voted Ind\", \"Active Registered Ind\"]\n df20 = df20[cols]\n\n swapped_PG_df = pd.concat([df[df.County != \"Prince George's\"], df20[df20.County == \"Prince George's\"]])\n\n counties = set(swapped_PG_df.County)\n for county in counties:\n if county != \"Prince George's\":\n assert df[df.County == county].MATCH.nunique() == swapped_PG_df[swapped_PG_df.County == county].MATCH.nunique()\n else:\n assert df20[df20.County == county].MATCH.nunique() == swapped_PG_df[swapped_PG_df.County == county].MATCH.nunique()\n df[[\"Total Voted Dem\", \"Total Voted Rep\"]] = df[[\"Total Voted Dem\", \"Total Voted Rep\"]].astype(int)\n return swapped_PG_df", "def get_position_team_set_score_away(self, surface):\n return 0, 0", "def guess_elo(players, new_player):\n\n elo_scores = np.array(list(map(lambda x: x.elo, players)))\n\n weights = np.array(list(map(\n lambda x: survey_weight(x, new_player), players)))\n\n if sum(weights) == 0:\n return new_player.elo\n else:\n weights = weights / sum(weights)\n\n return sum(weights * elo_scores)", "def calculate_draft_bot_score(self):\n # TODO: set year\n weekly_stats = WeeklyStats.objects.filter(player=self) \\\n .order_by('week__number')\n if not weekly_stats:\n self.total_pts = 0\n self.first_half_pts = 0\n self.second_half_pts = 0\n self.save()\n return\n\n first_half, second_half = weekly_stats[:8], weekly_stats[8:]\n first_half_pts = sum([stat.total_score for stat in first_half])\n second_half_pts = sum([stat.total_score for stat in second_half])\n total_pts = first_half_pts + second_half_pts\n print(\"{} scored {} pnts last year\".format(self.full_name,\n total_pts))\n print(\"{} in first_half\".format(first_half_pts))\n print(\"{} in second_half\".format(second_half_pts))\n self.total_pts = total_pts\n self.first_half_pts = first_half_pts\n self.second_half_pts = second_half_pts\n\n # arbitrary starting number\n draft_bot_pts = 100\n if self.total_pts < 25:\n\n self.draft_bot_score = 0\n self.save()\n return\n\n draft_bot_pts += self.total_pts\n if self.first_half_pts > self.second_half_pts and \\\n abs(self.first_half_pts - self.second_half_pts) > 50:\n draft_bot_pts -= 15\n\n if self.first_half_pts and self.second_half_pts == 0:\n draft_bot_pts -= 25\n\n # yikes this is ugly\n # draft point adjustments based on position / age\n if self.position == \"RB\":\n\n # MAX_DRAFT_PENALTY: 20\n\n # young dudes run faster\n if self.age <= 27:\n draft_bot_pts += 20\n # old dudes do not\n elif self.age > 30:\n draft_bot_pts -= 20\n else:\n draft_bot_pts -= 5\n\n elif self.position == \"WR\":\n # MAX_DRAFT_PENALTY: 15\n\n # young wrs not quite as good\n # if they showed no production, give a stronger penalty\n if self.age < 25:\n if self.total_pts < 50:\n draft_bot_pts -= 10\n else:\n draft_bot_pts -= 5\n\n # these seem like prime years\n elif 24 < self.age < 31:\n draft_bot_pts += 15\n\n # early 30s still pretty decent\n elif 30 < self.age < 34:\n draft_bot_pts += 5\n\n # old dudes bad\n else:\n draft_bot_pts -= 15\n\n elif self.position == \"QB\":\n # MAX_DRAFT_PENALTY: 15\n # TODO: this should likely be higher\n\n # young qbs, not as consistent?\n # only penalty if they didnt do great prior season\n if self.age < 25 and self.total_pts < 100:\n draft_bot_pts -= 15\n\n # prime years, get a boost\n elif 24 < self.age < 36:\n draft_bot_pts += 15\n\n # really old dudes are bad\n else:\n draft_bot_pts -= 15\n\n elif self.position == \"TE\":\n if self.age < 25:\n if self.total_pts < 50:\n draft_bot_pts -= 10\n else:\n draft_bot_pts -= 5\n elif 24 < self.age < 31:\n draft_bot_pts += 15\n elif 30 < self.age < 34:\n draft_bot_pts += 5\n else:\n draft_bot_pts -= 15\n\n self.draft_bot_score = draft_bot_pts\n print(\"draft bot score = {}\".format(self.draft_bot_score))\n self.save()", "def get_rpi(season_games, team):\n def get_wp(team):\n \"\"\" Return team win percentage \"\"\"\n team_wins = season_games[season_games['Wteam'] == team]\n team_losses = season_games[season_games['Lteam'] == team]\n return float(len(team_wins)) / float(len(team_losses) + len(team_wins))\n\n def get_opponents(team):\n \"\"\" Return list of all opponents \"\"\"\n team_wins = season_games[season_games['Wteam'] == team]\n team_losses = season_games[season_games['Lteam'] == team]\n opponents = [] # to be a list of all game opponents\n [opponents.append(t) for t in team_wins['Lteam']]\n [opponents.append(t) for t in team_losses['Wteam']]\n return opponents\n\n def get_owp(team):\n \"\"\" Return float average opponent win percentage \"\"\"\n opponents = get_opponents(team)\n opponent_wps = [get_wp(t) for t in opponents]\n return float(np.sum(opponent_wps)) / float(len(opponents))\n\n def get_oowp(team):\n \"\"\" Return float opponent's average opponent win percentage \"\"\"\n opponents = get_opponents(team)\n opponent_owps = [get_owp(t) for t in opponents]\n return float(np.sum(opponent_owps)) / float(len(opponents))\n\n wp = get_wp(team)\n owp = get_owp(team)\n oowp = get_oowp(team)\n return (wp * 0.25) + (owp * 0.50) + (oowp * 0.25)", "def get_position_team_score_away(self, surface):\n return 0, 0", "def calc_annual_investment(devs, param, grid_data, dem_buildings):\n\n observation_time = param[\"observation_time\"]\n interest_rate = param[\"interest_rate\"]\n q = 1 + param[\"interest_rate\"]\n\n # Calculate capital recovery factor\n CRF = ((q**observation_time)*interest_rate)/((q**observation_time)-1)\n\n \n # Calculate annuity factor for generation devices\n for device in devs.keys():\n \n # Get device life time\n life_time = devs[device][\"life_time\"]\n\n # Number of required replacements\n n = int(math.floor(observation_time / life_time))\n \n # Inestment for replcaments\n invest_replacements = sum((q ** (-i * life_time)) for i in range(1, n+1))\n\n # Residual value of final replacement\n res_value = ((n+1) * life_time - observation_time) / life_time * (q ** (-observation_time))\n\n # Calculate annualized investments \n if life_time > observation_time:\n devs[device][\"ann_factor\"] = (1 - res_value) * CRF \n else:\n devs[device][\"ann_factor\"] = ( 1 + invest_replacements - res_value) * CRF \n \n \n \n\n # Pipe costs\n \n length = 0\n inv_pipes = 0\n \n life_time = param[\"pipe_lifetime\"]\n\n # Sum up investment costs for each edge\n for item in grid_data[\"edges\"]:\n length = length + grid_data[\"edges\"][item][\"length\"]\n d_h = grid_data[\"edges\"][item][\"diameter_heating\"]\n d_c = grid_data[\"edges\"][item][\"diameter_cooling\"]\n # binary variables to check if a pipe is needed at this edge (some buildings don't have cooling demand)\n x_h = d_h > 0\n x_c = d_c > 0 \n inv_pipes = inv_pipes + ((x_h or x_c) * 0.5 * param[\"inv_ground\"] + x_h * (param[\"inv_pipe_isolated_fix\"] + param[\"inv_pipe_isolated\"] * d_h**2) + x_c * param[\"inv_pipe_PE\"] * d_c**2) * 2 * grid_data[\"edges\"][item][\"length\"]\n \n # Number of required replacements\n n = int(math.floor(observation_time / life_time)) \n # Inestment for replcaments\n invest_replacements = sum((q ** (-i * life_time)) for i in range(1, n+1))\n # Residual value of final replacement\n res_value = ((n+1) * life_time - observation_time) / life_time * (q ** (-observation_time))\n \n if life_time > observation_time:\n param[\"tac_pipes\"] = (CRF * inv_pipes * (1 - res_value) + param[\"cost_om_pipe\"] * inv_pipes) / 1000 # kEUR, annualized pipe costs\n else:\n param[\"tac_pipes\"] = (CRF * inv_pipes * (1 + invest_replacements - res_value) + param[\"cost_om_pipe\"] * inv_pipes) / 1000\n \n param[\"length_pipes\"] = length # m, one-way length of heating network\n\n\n \n\n # substation costs\n \n life_time = param[\"sub_lifetime\"]\n max_loads = []\n for item in dem_buildings[\"heating\"]:\n if item != \"sum\":\n max_loads.append(np.max(dem_buildings[\"heating\"][item]))\n max_loads.append(np.max(dem_buildings[\"cooling\"][item]))\n \n inv_subs = sum((max_loads[k] > 0) * param[\"inv_sub_fix\"] + param[\"inv_sub_var\"] * max_loads[k] for k in range(len(max_loads)))\n \n # Number of required replacements\n n = int(math.floor(observation_time / life_time)) \n # Inestment for replcaments\n invest_replacements = sum((q ** (-i * life_time)) for i in range(1, n+1))\n # Residual value of final replacement\n res_value = ((n+1) * life_time - observation_time) / life_time * (q ** (-observation_time))\n \n if life_time > observation_time:\n param[\"tac_subs\"] = (CRF * inv_subs * (1 - res_value) + param[\"cost_om_sub\"] * inv_subs) # kEUR, annualized substation costs\n else:\n param[\"tac_subs\"] = (CRF * inv_subs * (1 + invest_replacements - res_value) + param[\"cost_om_sub\"] * inv_subs)\n \n\n \n \n # Pump investment and operation/maintenance costs\n \n if param[\"switch_pump\"]:\n \n life_time = param[\"pump_lifetime\"]\n \n inv_pump = param[\"inv_pump\"] * (param[\"pump_cap_heating\"] + param[\"pump_cap_cooling\"]) #kEUR, pump investment costs\n \n # Number of required replacements\n n = int(math.floor(observation_time / life_time)) \n # Inestment for replcaments\n invest_replacements = sum((q ** (-i * life_time)) for i in range(1, n+1))\n # Residual value of final replacement\n res_value = ((n+1) * life_time - observation_time) / life_time * (q ** (-observation_time))\n \n if life_time > observation_time:\n param[\"tac_pump\"] = (CRF * inv_pump * (1 - res_value) + param[\"cost_om_pump\"] * inv_pump) # kEUR, annualized pump investment and maintenance costs\n else:\n param[\"tac_pump\"] = (CRF * inv_pump * (1 + invest_replacements - res_value) + param[\"cost_om_pump\"] * inv_pump) \n \n \n # add Pump electricity costs\n param[\"pump_costs_el\"] = param[\"pump_energy\"] * param[\"pump_electricity_costs\"]\n param[\"tac_pump\"] += param[\"pump_costs_el\"]\n \n else:\n \n param[\"tac_pump\"] = 0\n \n \n #print(\"pumpe Strom\" + str(param[\"tac_pump\"]))\n \n \n # Sum up distribution costs\n param[\"tac_distr\"] = param[\"tac_pipes\"] + param[\"tac_subs\"] + param[\"tac_pump\"]\n \n \n print(param[\"tac_distr\"])\n \n\n return devs, param", "def reinforce3(winner,history,moveScoreDict,winWeight = 1,loseWeight=-1,drawWeight=0):\n if winner==1:\n winPlayer = \"X\"\n losePlayer = \"O\"\n drawPlayer1 = \"-\"\n drawPlayer2 = \"-\"\n elif winner==2:\n winPlayer = \"O\"\n losePlayer = \"X\"\n drawPlayer1 = \"-\"\n drawPlayer2 = \"-\"\n elif winner==3:\n winPlayer = \"-\"\n losePlayer = \"-\"\n drawPlayer1 = \"X\"\n drawPlayer2 = \"O\"\n gamma = 0.05\n if winPlayer != \"-\":\n for i,(b,m) in enumerate(history[winPlayer]):\n moveScoreDict[b][\"timesSeen\"] += 1\n moveScoreDict[b][\"scores\"][m] += winWeight*(gamma**(len(history[winPlayer])-1-i))\n \n if losePlayer != \"-\":\n for i,(b,m) in enumerate(history[losePlayer]):\n moveScoreDict[b][\"timesSeen\"] += 1\n moveScoreDict[b][\"scores\"][m] += loseWeight*(gamma**(len(history[losePlayer])-1-i))\n\n if drawPlayer1 != \"-\":\n for i,(b,m) in enumerate(history[drawPlayer1]):\n moveScoreDict[b][\"timesSeen\"] += 1\n moveScoreDict[b][\"scores\"][m] += drawWeight*(gamma**(len(history[drawPlayer1])-1-i))\n if drawPlayer2 != \"-\":\n for i,(b,m) in enumerate(history[drawPlayer2]):\n moveScoreDict[b][\"timesSeen\"] += 1\n moveScoreDict[b][\"scores\"][m] += drawWeight*(gamma**(len(history[drawPlayer2])-1-i))\n return moveScoreDict" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Caclculates Relative Synonymous codon usage (RSCU) wij = RSCUij/ RSCU i,max
def compute_rscu_weights(df_codcount): aa_groups = df_codcount.groupby('Amino_Acid') aa = df_codcount['Amino_Acid'].unique() #make a list of all amino acids to iterate over df_list = [] for a in aa: d=aa_groups.get_group(a) d['RSCU'] = d['Obs_Freq'].values/d['Obs_Freq'].mean() #obs/expected freq d['Relative_Adaptive_Weights'] = d['RSCU'].values/d['RSCU'].max() d['optimal'] = [True if rscu==d['RSCU'].max() else False for rscu in d['RSCU'].values] #marks optimal codon df_list.append(d) return pd.concat(df_list)
[ "def ricci_scalar(self):\n R_0101 = self.covariant_riemann()\n q_inv = self.induced_metric(inverse=True)\n return 2 * R_0101 * (q_inv[0,0]*q_inv[1,1] - q_inv[0,1]**2)", "def rs(self):\n return self.rads/self.rad_schw", "def shear_Reuss(self):\r\n s = self.Sij\r\n return 15 / (4 * (s[0, 0] + s[1, 1] + s[2, 2]) - 4 * (s[0, 1] + s[1, 2] + s[0, 2]) + 3 * (s[3, 3] + s[4, 4] + s[5, 5]))", "def eval_rmsre(dataset,xc,psp):\n rmsre = 0.\n N = 0\n for mol in build_computed_mol_list(dataset):\n sre = eval_sre_molecule(dataset,mol,xc,psp)\n if not (sre is None):\n rmsre+=sre\n N+=1\n if N>0 : rmsre = rmsre/N\n return np.sqrt(rmsre)", "def _get_shrink_target_const_corr(self, X: np.ndarray, S: np.ndarray) -> np.ndarray:\n n = len(S)\n var = np.diag(S)\n sqrt_var = np.sqrt(var)\n covar = np.outer(sqrt_var, sqrt_var)\n r_bar = (np.sum(S / covar) - n) / (n * (n - 1))\n F = r_bar * covar\n np.fill_diagonal(F, var)\n return F", "def compute_photon_statistics(rs,inv, rs_Cxx, rs_constants ):\n \n [ntimes, nalts] = rs.var_raw_molecular_counts.shape\n ones_array = np.ones((ntimes,nalts))\n Cmm = ones_array * np.transpose(rs_Cxx.Cmm[:nalts])\n Cmc = ones_array * np.transpose(rs_Cxx.Cmc[:nalts])\n Cam = ones_array * rs_Cxx.Cam\n if hasattr(rs_Cxx,'Cam_i2a'):\n Cam_i2a = ones_array * rs_Cxx.Cam_i2a\n Cmm_i2a = ones_array * np.transpose(rs_Cxx.Cmm_i2a[:nalts])\n\n \n cpol_gain = rs_constants['combined_to_cross_pol_gain_ratio']\n \n var_mol = rs.var_raw_molecular_counts\n var_comb= rs.var_raw_combined_hi_counts\n var_cp = rs.var_raw_cross_pol_counts\n if hasattr(rs,'var_raw_molecular_i2a_counts'):\n var_mol_i2a = rs.var_raw_molecular_i2a_counts\n if hasattr(rs,'var_raw_combined_1064_counts'):\n var_combined_1064_counts = rs.var_raw_combined_1064_counts\n\n Scp = rs.cross_pol_counts\n Sc = rs.combined_hi_counts\n Sm = rs.molecular_counts\n \n if hasattr(rs,'var_raw_molecular_i2a_counts'):\n var_mol_i2a = rs.var_raw_molecular_i2a_counts\n Sm_i2a = rs.molecular_i2a_counts\n\n # variance of the scatttering ratio\n mol_f = Sm - Cam * Sc\n mol_f_sqrd = mol_f**2\n aero_f = Cmm * Sc - Cmc * Sm\n \n \n SR_i2_std = np.sqrt(\n var_comb*((Cmm/mol_f-Cam*aero_f/mol_f_sqrd)**2\n + (cpol_gain * Scp * Cmm * Cam / mol_f_sqrd)**2) \n +var_mol * ((aero_f/mol_f_sqrd -Cam/mol_f)**2\n + (cpol_gain * Scp * Cmm / mol_f_sqrd)**2)\n +var_cp *(cpol_gain * Cmm/mol_f)**2)\n if hasattr(rs_Cxx,'Cam_i2a') and hasattr(rs,'molecular_i2a_counts'):\n mol_i2a_f = Sm - Cam * Sc\n mol_i2a_f_sqrd = mol_f**2\n aero_i2a_f = Cmm * Sc - Cmc * Sm\n\n SR_i2a_std = np.sqrt(\n var_comb*((Cmm_i2a/mol_f-Cam_i2a*aero_i2a_f/mol_i2a_f_sqrd)**2\n + (cpol_gain * Scp * Cmm_i2a * Cam_i2a / mol_i2a_f_sqrd)**2) \n +var_mol_i2a * ((aero_i2a_f/mol_i2a_f_sqrd -Cam_i2a/mol_i2a_f)**2\n + (cpol_gain * Scp * Cmm_i2a / mol_i2a_f_sqrd)**2)\n +var_cp *(cpol_gain * Cmm_i2a/mol_i2a_f)**2)\n #note SR is computed from average of i2 and i2a determinations\n SR_std =0.5 * np.sqrt(SR_i2_std**2 + SR_i2a_std**2)\n\n else: #if no i2a channel total scattering ratio is computed from i2 channel\n SR_std = SR_i2_std\n \n #Signal to noise ratio of molecular count\n SN_mol = Sm/np.sqrt((Cam/Cmm)**2 * var_comb +1/Cmm**2 * var_mol)\n \n if hasattr(rs_Cxx,'Cam_i2a') and hasattr(rs,'molecular_i2a_counts'):\n SN_i2a_mol = Sm_i2a/np.sqrt((Cam_i2a/Cmm_i2a)**2 * var_comb +1/Cmm_i2a**2 * var_mol_i2a)\n setattr(inv,'SN_i2a_mol',SN_i2a_mol)#FIXME add to another layer somewhere\n #standard deviation of backscatter cross section\n setattr(inv,'std_beta_a_backscat',SR_std * inv.beta_r_backscat)\n #standard deviation of the backscatter ratio\n setattr(inv,'SR_std',SR_std)#FIXME add to mean layer\n #signal-to-noise ratio for beta_a_backscatter\n setattr(inv,'SN_beta_a_backscat', inv.beta_a_backscat / (SR_std * inv.beta_r_backscat))\n #signal-to-noise ratio for the molecular count profile\n setattr(inv,'SN_mol',SN_mol)#FIXME add to mean layer\n return", "def gw_corr_res(self, sn2w):\n v_pab = self.pb.get_ac_vertex_array()\n sn2res = [np.zeros_like(n2w, dtype=self.dtype) for n2w in sn2w ]\n for s,ww in enumerate(sn2w):\n x = self.mo_coeff[0,s,:,:,0]\n for nl,(n,w) in enumerate(zip(self.nn[s],ww)):\n #for nl,(n,w) in enumerate(zip(self.nn,ww)):\n lsos = self.lsofs_inside_contour(self.ksn2e[0,s,:],w,self.dw_excl)\n zww = array([pole[0] for pole in lsos])\n si_ww = self.si_c(ww=zww)\n xv = dot(v_pab,x[n])\n #print(__name__, 's,n,w', s,n,w)\n for pole,si in zip(lsos, si_ww.real):\n xvx = dot(xv, x[pole[1]])\n contr = dot(xvx, dot(si, xvx))\n #print(pole[0], pole[2], contr)\n sn2res[s][nl] += pole[2]*contr\n return sn2res", "def resistivity(self):\n A = self. w * self.t # Cross-sectional area of cpw\n rho = self.resistance() * (A / self.l)\n return rho", "def calc_S(self, U):\n if not self.populated:\n self.populate_arrays(U) \n\n return self.metric() + self.penalty()", "def host_usage_effect(self, host):\n\n\t\tnum_sum = 0\n\t\ta_sum = 0\n\t\tb_sum = 0\n\n\t\tfor codon in self.rscu_table:\n\t\t\tif codon_to_aa[codon] != 'M' and codon_to_aa[codon] != 'W' and codon_to_aa[codon] != '*':\n\t\t\t\tnum_sum += self.rscu_table[codon] * host.rscu_table[codon]\n\t\t\t\ta_sum += self.rscu_table[codon]**2\n\t\t\t\tb_sum += host.rscu_table[codon]**2\n\t\trab = num_sum/math.sqrt(a_sum * b_sum)\n\t\tdab = (1-rab)/2\n\t\treturn dab", "def get_resid_wave_eq_first_order(u):\n #See autograd docs for jacobian documentation. \n #This code treats u as a vector valued function of the arguments x,t\n #So have to compute two jacobians, one for each. Consider changing depending on efficiency. \n #Is one jacobian w.r.t single vector [x,t] much faster than two jacobians w.r.t. (x,t)?\n\n #Jx is vector valued function of params,x,t\n #Jx(params,x,t) is d([u,ut,ux])/dx(params,x,t)\n Jx=jacobian(u, 1)\n Jt=jacobian(u, 2)\n\n\n elementwise_error=lambda params,x,t: np.array([\\\n Jx(params,x,t)[0]-Jt(params,x,t)[0]-u(params,x,t)[2]+u(params,x,t)[1], \\\n Jx(params,x,t)[1]-Jt(params,x,t)[2], \\\n Jx(params,x,t)[2]-Jt(params,x,t)[1]\n ])\n\n #elementwise_error=lambda params,x,t: np.array([\\\n # Jx(params,x,t)[0], 0., 0.])\n\n resid=lambda params,x,t: np.linalg.norm((elementwise_error(params,x,t)), ord=2)\n return resid", "def compute_score(list_scu):\n\tsum_scu = 0\n\tfor scu in list_scu:\n\t\tsum_scu += scu_dict[scu]\n\treturn sum_scu", "def eval_sre_molecule(dataset,mol,xc,psp):\n sre = None\n eps = eval_relative_error(dataset,mol,xc,psp)\n if not (eps is None):\n sre = sum(eps**2)/3.\n return sre", "def compute_ACI(wave,sr):\n j_bin= wave.shape[0] \n spectro, _ = compute_spectrogram(wave,sr)\n #times = range(0, spectro.shape[1], j_bin) # relevant time indices\n times = range(0, spectro.shape[1]-10, j_bin) # alternative time indices to follow the R code\n\n jspecs = [np.array(spectro[:,i:i+j_bin]) for i in times] # sub-spectros of temporal size j\n\n aci = [sum((np.sum(abs(np.diff(jspec)), axis=1) / np.sum(jspec, axis=1))) for jspec in jspecs] \t# list of ACI values on each jspecs\n main_value = sum(aci)\n temporal_values = aci\n\n return main_value, temporal_values # return main (global) value, temporal values", "def modifiedRician(I, Ic, Is):\n mr = 1.0 / Is * np.exp(-1.0 * (I + Ic) / Is) * special.iv(0, 2.0 * np.sqrt(I * Ic) / Is)\n return mr", "def strain_rate_tensor(self, u):\r\n r = dolfin.SpatialCoordinate(self._mesh)[0]\r\n ur = u[0]\r\n uz = u[1]\r\n ur_r = ur.dx(0)\r\n ur_z = ur.dx(1)\r\n uz_r = uz.dx(0)\r\n uz_z = uz.dx(1)\r\n return dolfin.sym(\r\n dolfin.as_tensor(\r\n [\r\n [ur_r, 0, 0.5 * (uz_r + ur_z)],\r\n [0, ur / r, 0],\r\n [0.5 * (uz_r + ur_z), 0, uz_z]\r\n ]))", "def get_recan_rate(self):\n try:\n ischemic_df = self.df[self.df['stroke_type_es'].isin([1])] # Ischemic stroke: stroke_type_es = 1\n recan_rate_df = ischemic_df[ischemic_df['recanalization_procedures_es'].isin([1,2,3])]\n ischemic_pts = ischemic_df.groupby(['site_id']).size().reset_index(name=\"tmp_patients\")\n if not recan_rate_df.empty:\n recan_rate_pts = recan_rate_df.groupby(['site_id']).size().reset_index(name='# recanalization rate out of total ischemic incidence')\n tmp = pd.merge(recan_rate_pts, ischemic_pts, how=\"left\", on=\"site_id\")\n tmp['% recanalization rate out of total ischemic incidence'] = tmp.apply(lambda x: round((x['# recanalization rate out of total ischemic incidence']/x['tmp_patients'])*100, 2) if x['tmp_patients'] > 0 else 0, axis=1)\n tmp.drop(['tmp_patients'], axis=1, inplace=True)\n self.stats_df = pd.merge(self.stats_df, tmp, how=\"left\", on=\"site_id\")\n else:\n self.stats_df['# recanalization rate out of total ischemic incidence'] = 0\n self.stats_df['% recanalization rate out of total ischemic incidence'] = 0\n \n logging.info('Atalaia: Recanalization rate: OK')\n except:\n logging.info('Atalaia: Recanalization rate: ERROR')", "def shape_icc(M):\r\n # setup size\r\n sizeM = M.shape\r\n #k - num raters; n - num subjects\r\n k = sizeM[-1]\r\n n = sizeM[-2]\r\n Npix = np.prod(sizeM[0:-2]) #Npix = Ny * Nx * ... = total # of pixels in each shape\r\n\r\n M = np.reshape(M,[Npix, n, k]) #vectorize each shape into an Npix-length column array\r\n M = np.single(M) #in case M is logical, need it to be single to do floating-point ops on it\r\n\r\n # compute means\r\n u1 = np.squeeze(np.mean(M, axis =1)) # Npix x k\r\n u2 = np.mean(M, axis =2) # Npix x n\r\n u = np.mean(u1, axis =1) # Npix x 1\r\n\r\n SS = 0\r\n for ii in np.arange(n):\r\n for jj in np.arange(k):\r\n d = np.abs(M[:,ii,jj] - u)\r\n SS = SS + (np.sum(d) ** 2)\r\n\r\n MSR = 0\r\n for ii in np.arange(n):\r\n d = abs(u2[:,ii] - u)\r\n MSR = MSR + sum(d[:]) ** 2\r\n MSR = k/(n-1) * MSR\r\n\r\n MSC = 0\r\n for jj in np.arange(k): \r\n d = abs(u1[:,jj] - u)\r\n MSC = MSC + (sum(d[:]) ** 2)\r\n MSC = n/(k-1) * MSC\r\n\r\n MSE = (SS - (n-1)*MSR - (k-1)*MSC) / ((n-1)*(k-1))\r\n icc = (MSR - MSE) / (MSR + (k-1)*MSE + k/n*(MSC-MSE))\r\n \r\n #from ICC(A,1) - in IRR package\r\n ns = n\r\n nr = k\r\n coeff = (MSR - MSE)/(MSR + (nr - 1) * MSE + \r\n (nr/ns) * (MSC - MSE))\r\n r0 = 0\r\n a = (nr * r0)/(ns * (1 - r0))\r\n b = (nr * r0 * (ns - 1))/(ns * (1 - r0)) \r\n Fvalue = MSR/(a * MSC + b * MSE)\r\n\r\n alpha = 1 - 0.95\r\n a = (nr * coeff)/(ns * (1 - coeff))\r\n b = 1 + (nr * coeff * (ns - 1))/(ns * (1 - coeff))\r\n v = (a * MSC + b * MSE)**2/((a * MSC)**2/(nr - 1) + (b * MSE)**2/((ns - 1) * (nr - 1)))\r\n #p.value <- pf(Fvalue, df1, df2, lower.tail = FALSE)\r\n #FL <- qf(1 - alpha/2, ns - 1, v)\r\n #FU <- qf(1 - alpha/2, v, ns - 1)\r\n\r\n FL = sstats.f.ppf(1 - alpha/2, ns - 1, v)\r\n FU = sstats.f.ppf(1 - alpha/2, v, ns - 1)\r\n\r\n lbound = (ns * (MSR - FL * MSE))/(FL * (nr * MSC + (nr * ns - nr - ns) * MSE) + ns * MSR)\r\n ubound = (ns * (FU * MSR - MSE))/(nr * MSC + (nr * ns - nr - ns) * MSE + ns * FU * MSR)\r\n\r\n return icc, Fvalue, lbound, ubound", "def coulomb(self,r):\n\t\teps=self.eps(r)\n return 1/(r * eps)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructs a version of 'fn' that applies to smaller batches.
def batchify(fn, chunk): if chunk is None: return fn def ret(inputs): return torch.cat([fn(inputs[i:i+chunk]) for i in range(0, inputs.shape[0], chunk)], 0) return ret
[ "def batch_apply(fn, inputs, batch_size):\n\n batched_inputs, pad_size = batchify(inputs, batch_size)\n results = np.concatenate([fn(batch) for batch in batched_inputs])\n if pad_size:\n results = results[:-pad_size]\n return results", "def batch_apply_func_to_df(df, func, batch_size=250):\n in_dfs = [df[i:i + batch_size] for i in range(0, df.shape[0], batch_size)]\n out_dfs = []\n for batch_df in tqdm(in_dfs):\n out_dfs.append(func(batch_df))\n df = pd.concat(out_dfs)\n return df", "def set_batch_input_fn(self, fn):\n assert fn is None or callable(fn)\n self._batch_input_fn = fn\n return self", "def map(builder, fn, *args, **kwargs):\n builder._tensor = fn(builder._tensor, *args, **kwargs)\n return builder", "def pool_metatile_batch(pool, fn, metatiles, size):\n pool.map(fn,metatile_batches(metatiles, size))", "def sum_over_batch_size(loss_function):\n def wrapper(*args, **kwargs):\n batch_loss = fn.sum(loss_function(*args, **kwargs))\n batch_loss.data /= np.size(args[0].data)\n return batch_loss\n return wrapper", "def batched(f: Callable[..., Any]) -> Callable[..., Any]:\n\n @wraps(f)\n def batched_wrapper(self, *args, batch_size: Optional[int] = None, **kwargs):\n def get_batched(bs: Optional[int], seq: Sequence[Any]) -> List[List[Any]]:\n if isinstance(seq, str):\n seq = [seq]\n if isinstance(seq, list):\n return [seq[i : i + bs] for i in range(0, len(seq), bs)] # noqa\n if isinstance(seq, tuple):\n return list(zip(*[get_batched(bs, s) for s in seq]))\n elif isinstance(seq, TensorWrapper):\n return [seq.slice_batch(slice(i, i + bs)) for i in range(0, len(seq), bs)] # noqa\n else:\n raise TypeError(f\"Unsupported type {type(seq)} for batched attribution computation.\")\n\n if batch_size is None:\n out = f(self, *args, **kwargs)\n return out if isinstance(out, list) else [out]\n batched_args = [get_batched(batch_size, arg) for arg in args]\n len_batches = len(batched_args[0])\n assert all(len(batch) == len_batches for batch in batched_args)\n output = []\n zipped_batched_args = zip(*batched_args) if len(batched_args) > 1 else [(x,) for x in batched_args[0]]\n for i, batch in enumerate(zipped_batched_args):\n logger.debug(f\"Batching enabled: processing batch {i + 1} of {len_batches}...\")\n out = f(self, *batch, **kwargs)\n output += out if isinstance(out, list) else [out]\n return output\n\n return batched_wrapper", "def set_batch_target_fn(self, fn):\n assert fn is None or callable(fn)\n self._batch_target_fn = fn\n return self", "def pool_map(func, args, batch_size, verbose=False, pool=None):\n\n ret = None\n tic = time.time()\n local_pool = pool or PopenPoolExecutor()\n if verbose:\n logger.info(\"mapping begin\")\n for i in range(0, len(args), batch_size):\n if verbose:\n logger.info(\"mapping %d/%d elapsed %.2f\", i, len(args), time.time() - tic)\n tmp = np.array(local_pool.map(func, args[i : i + batch_size]))\n ret = tmp if ret is None else np.concatenate((ret, tmp))\n if verbose:\n logger.info(\"mapping done\")\n if not pool:\n local_pool.close()\n return ret", "def vectorized(func):\n\tfrom inspect import signature\n\timport types\n\tnew_func = types.FunctionType(\n\t\tfunc.__code__,\n\t\tfunc.__globals__,\n\t\tfunc.__name__,\n\t\tfunc.__defaults__,\n\t\tfunc.__closure__\n\t)\n\t# Construct the annotations:\n\timport pyarrow as pa\n\n\tnew_annotations = {}\n\tsig = signature(func)\n\tsig.parameters\n\tfor param in sig.parameters:\n\t\tnew_annotations[param] = pa.lib.ChunkedArray\n\n\tnew_func.__annotations__ = new_annotations\n\treturn new_func", "def batch_apply(fn, *args, unshape_inputs=False, **kwargs):\n \n if len(args) == 0:\n # TODO remove the cases and only use the unified implementation\n return batch_apply_legacy(kwargs, fn, separate_arguments=True, unshape_inputs=unshape_inputs)\n elif len(kwargs) == 0:\n return batch_apply_legacy(args, fn, separate_arguments=True, unshape_inputs=unshape_inputs)\n else:\n # TODO test\n reference_tensor = find_tensor([args, kwargs], min_dim=2)\n if not isinstance(reference_tensor, TENSOR):\n raise ValueError(\"couldn't find a reference tensor\")\n \n batch, time = reference_tensor.shape[:2]\n reshape_to = lambda tensor: tensor.view((batch * time,) + tensor.shape[2:])\n reshape_from = lambda tensor: tensor.view((batch, time,) + tensor.shape[1:])\n \n reshaped_args = rmap(reshape_to, args)\n reshaped_kwargs = rmap(reshape_to, kwargs)\n output = fn(*reshaped_args, **reshaped_kwargs)\n \n if unshape_inputs:\n rmap(reshape_from, reshaped_args)\n rmap(reshape_from, reshaped_kwargs)\n \n return rmap(reshape_from, output)", "def _create_train_loop_fn(train_step_fn, options: StandardTrainerOptions):\n if options.use_tf_while_loop:\n loop_fn = loop_fns.create_tf_while_loop_fn(train_step_fn)\n if options.use_tpu_summary_optimization:\n loop_fn = loop_fns.LoopFnWithSummaries(loop_fn)\n else:\n loop_fn = tf.function(loop_fn)\n else:\n if options.use_tf_function:\n train_step_fn = tf.function(train_step_fn)\n loop_fn = loop_fns.create_loop_fn(train_step_fn)\n return loop_fn", "def map(self, function: Callable, batched: bool = False, batch_size: int = 1000):\n info = copy.deepcopy(self._info)\n info.features = None\n ex_iterable = MappedExamplesIterable(\n self._ex_iterable, function=function, batched=batched, batch_size=batch_size\n )\n return iterable_dataset(\n ex_iterable=ex_iterable,\n info=info,\n split=self._split,\n format_type=self._format_type,\n shuffling=copy.deepcopy(self._shuffling),\n )", "def _maybe_process_in_chunks(process_fn, **kwargs):\n\n def __process_fn(img):\n num_channels = img.shape[2] if len(img.shape) == 3 else 1\n if num_channels > 4:\n chunks = []\n for index in range(0, num_channels, 4):\n if num_channels - index == 2:\n # Many OpenCV functions cannot work with 2-channel images\n for i in range(2):\n chunk = img[:, :, index + i : index + i + 1]\n chunk = process_fn(chunk, **kwargs)\n chunk = np.expand_dims(chunk, -1)\n chunks.append(chunk)\n else:\n chunk = img[:, :, index : index + 4]\n chunk = process_fn(chunk, **kwargs)\n chunks.append(chunk)\n img = np.dstack(chunks)\n else:\n img = process_fn(img, **kwargs)\n return img\n\n return __process_fn", "def _poolmap(f, X, nprocs=multiprocessing.cpu_count(), chunksize=None):\n with multiprocessing.Pool(processes=nprocs) as pool:\n out = pool.map(f, X, chunksize=chunksize)\n return out", "def do_with_threads(self, size, func, *args):\n pool = [threading.Thread(target=func, args=args) for i in range(size)]\n for thread in pool:\n thread.start()\n return pool", "def map_fn(fn,\n elems,\n dtype=None,\n parallel_iterations=None,\n back_prop=True,\n swap_memory=False,\n infer_shape=True,\n name=None):\n if not callable(fn):\n raise TypeError(\"fn must be callable.\")\n\n if isinstance(elems, sparse_tensor.SparseTensor):\n raise TypeError(\n \"To perform a map on the values of a sparse tensor use either \"\n \" SparseTensor(input.indices, fn(input.values), input.dense_shape) or \"\n \" SparseTensor(input.indices, map_fn(fn, input.values), \"\n \"input.dense_shape)\")\n\n in_graph_mode = not context.executing_eagerly()\n # Set the default number of parallel_iterations depending on graph/eager mode.\n if in_graph_mode and not parallel_iterations:\n parallel_iterations = 10\n elif not in_graph_mode and not parallel_iterations:\n parallel_iterations = 1\n\n if not in_graph_mode and parallel_iterations > 1:\n logging.log_first_n(logging.WARN, \"Setting parallel_iterations > 1 has no \"\n \"effect when executing eagerly. Consider calling map_fn\"\n \" with tf.contrib.eager.defun to execute fn in \"\n \"parallel.\", 1)\n parallel_iterations = 1\n\n input_is_sequence = nest.is_sequence(elems)\n input_flatten = lambda x: nest.flatten(x) if input_is_sequence else [x]\n\n def input_pack(x):\n return nest.pack_sequence_as(elems, x) if input_is_sequence else x[0]\n\n elems_flat = input_flatten(elems)\n elems_flat = ragged_tensor.match_row_splits_dtypes(*elems_flat)\n\n with ops.name_scope(name, \"map\", elems_flat):\n # TODO(akshayka): Remove the in_graph_mode check once caching devices are\n # supported in Eager\n if in_graph_mode:\n # Any get_variable calls in fn will cache the first call locally\n # and not issue repeated network I/O requests for each iteration.\n varscope = vs.get_variable_scope()\n varscope_caching_device_was_none = False\n if varscope.caching_device is None:\n # TODO(ebrevdo): Change to using colocate_with here and in other\n # methods.\n varscope.set_caching_device(lambda op: op.device)\n varscope_caching_device_was_none = True\n\n elems_flat = [\n ragged_tensor.convert_to_tensor_or_ragged_tensor(elem, name=\"elem\")\n for elem in elems_flat\n ]\n\n # We can either infer the output, or we can assume that it will be the same\n # as the input structure.\n dtype = dtype or input_pack([elem.dtype for elem in elems_flat])\n\n # Find the number of iterations, n may be known statically.\n if isinstance(elems_flat[0], ragged_tensor.RaggedTensor):\n n = elems_flat[0].nrows(out_type=dtypes.int32)\n else:\n static_shape = elems_flat[0].shape\n if static_shape.ndims is not None and static_shape.ndims < 1:\n if len(elems_flat) == 1:\n raise ValueError(\n \"elems must be a 1+ dimensional Tensor, not a scalar\")\n else:\n raise ValueError(\n \"elements in elems must be 1+ dimensional Tensors, not scalars\")\n n = (tensor_shape.dimension_value(static_shape[0]) or\n array_ops.shape(elems_flat[0])[0])\n\n n = math_ops.cast(n, dtype=dtypes.int32)\n # Create a flat list of TAs.\n\n # Flatten the dtype structure to a list.\n dtype_flat = nest.flatten(dtype)\n\n # decompose to components\n dtype_components = [_maybe_decompose_dtype(d) for d in dtype_flat]\n dtype_components_flat = nest.flatten(dtype_components)\n\n # Create TensorArrays.\n accs_ta = [\n tensor_array_ops.TensorArray(\n dtype=t, dynamic_size=False, infer_shape=infer_shape, size=n)\n for t in dtype_components_flat\n ]\n\n i = constant_op.constant(0, dtype=dtypes.int32)\n\n def compute(i, tas):\n \"\"\"The loop body of map_fn.\n\n Args:\n i: the loop counter\n tas: the flat TensorArray accumulator list\n\n Returns:\n (i + 1, tas): the updated counter + updated TensorArrays\n\n Raises:\n TypeError: if dtype and packed_fn_values structure do not match\n ValueType: if dtype and packed_fn_values lengths do not match\n \"\"\"\n # Get Tensors or RaggedTensors sliced at i, then pack it back to the\n # original structure.\n packed_values = input_pack([elem_flat[i] for elem_flat in elems_flat])\n packed_fn_values = fn(packed_values)\n\n # Check that the structure of the output matches what was declared or\n # inferred.\n # nest.assert_same_structure(dtype or elems, packed_fn_values)\n\n # Flatten and decompose to a list of Tensors\n flat_fn_values = nest.flatten(packed_fn_values)\n\n # If we declared that we are expecting a RaggedTensor output, but we get a\n # Tensor output. We should try to convert it to a RaggedTensor.\n flat_fn_composite_tensors = list(\n _convert_declared(flat_fn_values, dtype_flat))\n\n flat_fn_components = [\n _maybe_decompose_tensor(t) for t in flat_fn_composite_tensors\n ]\n flat_fn_tensors = nest.flatten(flat_fn_components)\n\n # Write to TAs.\n tas = [ta.write(i, value) for (ta, value) in zip(tas, flat_fn_tensors)]\n\n return (i + 1, tas)\n\n _, r_a = control_flow_ops.while_loop(\n lambda i, _: i < n, compute, (i, accs_ta),\n parallel_iterations=parallel_iterations,\n back_prop=back_prop,\n swap_memory=swap_memory,\n maximum_iterations=n)\n\n # TODO(akshayka): Remove the in_graph_mode check once caching devices are\n # supported in Eager\n if in_graph_mode and varscope_caching_device_was_none:\n varscope.set_caching_device(None)\n\n # Pack back into a list of components\n results_as_components = nest.pack_sequence_as(dtype_components, r_a)\n\n # Stack TensorArrays for Tensor outputs, and concat RaggedTensor outputs.\n def _stack_or_concat(e):\n if isinstance(e, _RaggedTensorComponents):\n return _concat_ragged_tensor_components(e)\n else:\n result = e.stack()\n return result\n\n results_flat_components = [\n _stack_or_concat(e) for e in results_as_components\n ]\n\n results_packed = [\n _maybe_recompose_tensor(c) for c in results_flat_components\n ]\n results_packed = nest.pack_sequence_as(dtype, results_packed)\n return results_packed", "def __init__(\n self,\n transform_fn: Callable[[Iterator[Block]], Iterator[Block]],\n input_op: PhysicalOperator,\n name: str = \"TaskPoolMap\",\n min_rows_per_bundle: Optional[int] = None,\n ray_remote_args: Optional[Dict[str, Any]] = None,\n ):\n super().__init__(\n transform_fn, input_op, name, min_rows_per_bundle, ray_remote_args\n )\n self._tasks: Dict[ObjectRef[ObjectRefGenerator], _TaskState] = {}\n self._next_task_idx = 0", "def bs_replicate(data, func=mn.mean):", "def make_average(fn, num_samples=100):\n def avg_fn(*args):\n i = 0\n for x in range (0,num_samples):\n i += fn(*args)\n return i/num_samples\n return avg_fn" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Render rays in smaller minibatches to avoid OOM.
def batchify_rays(num_frames, rays_flat, chunk=1024 * 32, **kwargs): all_ret = {} for i in range(0, rays_flat.shape[0], chunk): ret = render_rays(num_frames, rays_flat[i : i + chunk], **kwargs) for k in ret: if k not in all_ret: all_ret[k] = [] all_ret[k].append(ret[k]) all_ret = {k : torch.cat(all_ret[k], 0) for k in all_ret} return all_ret
[ "def startRayTracing(self):\n\n final = numpy.zeros((self.imageplane.getHeight(), self.imageplane.getWidth(), 3))\n\n cpu_count = multiprocessing.cpu_count()\n\n stepSize = int(self.imageplane.getHeight()/cpu_count)\n\n processes = []\n managers = []\n workers = []\n\n for i in range(0, cpu_count):\n manager = BaseManager()\n manager.register('Worker', Worker)\n manager.start()\n\n managers.append(manager)\n\n worker = manager.Worker(i*stepSize, (i+1)*stepSize, 0, self.imageplane.getWidth(), self.imageplane.getHeight(), self.imageplane.getWidth())\n workers.append(worker)\n\n process = multiprocessing.Process(target=self.trace, args=[worker])\n process.start()\n processes.append(process)\n\n for i in range(0, cpu_count):\n processes[i].join()\n\n for i in range(0, cpu_count):\n final[i*stepSize:(i+1)*stepSize, :] = workers[i].getImg()\n\n return final", "def render():\r\n # generates a matrix of tuples, with the first element i being the ith pixel along the horizontal axis\r\n # and j being the jth pixel along the vertical axis\r\n i, j = np.indices((nbr_pixels_y, nbr_pixels_x))\r\n coord_matrix = np.array((j, i))\r\n coord_matrix = coord_matrix.T\r\n # we add 0.5 to get the center of the pixels\r\n coord_matrix = coord_matrix + 0.5\r\n # generating a matrix with each element being the direction vector of the ray for that pixel\r\n indices = np.zeros((nbr_pixels_x, nbr_pixels_y, 3))\r\n indices[:coord_matrix.shape[0], :coord_matrix.shape[1], :coord_matrix.shape[2]] = coord_matrix\r\n indices[:, :, 0] = ((indices[:, :, 0]*2/nbr_pixels_x) - 1)*tan(fov)*(nbr_pixels_x/nbr_pixels_y)\r\n indices[:, :, 1] = ((indices[:, :, 1]*2/nbr_pixels_y) - 1)*tan(fov)\r\n indices[:, :, 2] = -1 # looking in the z = -1 direction\r\n indices = normalize(indices)\r\n img = cast_ray(indices, np.array([0, 0, 0]), scene_objects, light_list)\r\n\r\n cv2.imshow(\"render\", color_cut(img).astype(np.uint8)) # uint8 because opencv can't handle anything else\r\n cv2.waitKey(0)\r\n cv2.destroyAllWindows()", "def test_sphere_splat_render_along_ray(out_dir, cam_pos, width, height, fovy, focal_length, use_quartic,\n b_display=False):\n import copy\n print('render sphere along ray')\n sampling_time = []\n rendering_time = []\n\n num_samples = width * height\n\n large_scene = copy.deepcopy(SCENE_TEST)\n\n large_scene['camera']['viewport'] = [0, 0, width, height]\n large_scene['camera']['eye'] = tch_var_f(cam_pos)\n large_scene['camera']['fovy'] = np.deg2rad(fovy)\n large_scene['camera']['focal_length'] = focal_length\n large_scene['objects']['disk']['material_idx'] = tch_var_l(np.zeros(num_samples, dtype=int).tolist())\n large_scene['materials']['albedo'] = tch_var_f([[0.6, 0.6, 0.6]])\n large_scene['tonemap']['gamma'] = tch_var_f([1.0]) # Linear output\n\n x, y = np.meshgrid(np.linspace(-1, 1, width), np.linspace(-1, 1, height))\n #z = np.sqrt(1 - np.min(np.stack((x ** 2 + y ** 2, np.ones_like(x)), axis=-1), axis=-1))\n unit_disk_mask = (x ** 2 + y ** 2) <= 1\n z = np.sqrt(1 - unit_disk_mask * (x ** 2 + y ** 2))\n\n # Make a hemi-sphere bulging out of the xy-plane scene\n z[~unit_disk_mask] = 0\n pos = np.stack((x.ravel(), y.ravel(), z.ravel() - 5, np.ones(num_samples)), axis=1)\n\n # Normals outside the sphere should be [0, 0, 1]\n x[~unit_disk_mask] = 0\n y[~unit_disk_mask] = 0\n z[~unit_disk_mask] = 1\n\n normals = np_normalize(np.stack((x.ravel(), y.ravel(), z.ravel(), np.zeros(num_samples)), axis=1))\n\n if b_display:\n plt.ion()\n plt.figure()\n plt.subplot(131)\n plt.imshow(pos[..., 0].reshape((height, width)))\n plt.subplot(132)\n plt.imshow(pos[..., 1].reshape((height, width)))\n plt.subplot(133)\n plt.imshow(pos[..., 2].reshape((height, width)))\n\n plt.figure()\n plt.imshow(normals[..., 2].reshape((height, width)))\n\n ## Convert to the camera's coordinate system\n #Mcam = lookat(eye=large_scene['camera']['eye'], at=large_scene['camera']['at'], up=large_scene['camera']['up'])\n\n pos_CC = tch_var_f(pos) #torch.matmul(tch_var_f(pos), Mcam.transpose(1, 0))\n\n large_scene['objects']['disk']['pos'] = pos_CC\n large_scene['objects']['disk']['normal'] = None # Estimate the normals tch_var_f(normals)\n # large_scene['camera']['eye'] = tch_var_f([-10., 0., 10.])\n # large_scene['camera']['eye'] = tch_var_f([2., 0., 10.])\n large_scene['camera']['eye'] = tch_var_f([-5., 0., 0.])\n\n # main render run\n start_time = time()\n res = render_splats_along_ray(large_scene, use_quartic=use_quartic)\n rendering_time.append(time() - start_time)\n\n # Test cam_to_world\n res_world = cam_to_world(res['pos'].reshape(-1, 3), res['normal'].reshape(-1, 3), large_scene['camera'])\n\n im = get_data(res['image'])\n im = np.uint8(255. * im)\n\n depth = get_data(res['depth'])\n depth[depth >= large_scene['camera']['far']] = large_scene['camera']['far']\n\n if b_display:\n\n\n plt.figure()\n plt.imshow(im, interpolation='none')\n plt.title('Image')\n plt.savefig(out_dir + '/fig_img_orig.png')\n\n plt.figure()\n plt.imshow(depth, interpolation='none')\n plt.title('Depth Image')\n #plt.savefig(out_dir + '/fig_depth_orig.png')\n\n plt.figure()\n pos_world = get_data(res_world['pos'])\n posx_world = pos_world[:, 0].reshape((im.shape[0], im.shape[1]))\n posy_world = pos_world[:, 1].reshape((im.shape[0], im.shape[1]))\n posz_world = pos_world[:, 2].reshape((im.shape[0], im.shape[1]))\n plt.subplot(131)\n plt.imshow(posx_world)\n plt.title('x_world')\n plt.subplot(132)\n plt.imshow(posy_world)\n plt.title('y_world')\n plt.subplot(133)\n plt.imshow(posz_world)\n plt.title('z_world')\n\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n ax.scatter(pos_world[:, 0], pos_world[:, 1], pos_world[:, 2], s=1.3)\n ax.set_xlabel('x')\n ax.set_ylabel('y')\n\n plt.figure()\n pos_world = get_data(res['pos'].reshape(-1, 3))\n posx_world = pos_world[:, 0].reshape((im.shape[0], im.shape[1]))\n posy_world = pos_world[:, 1].reshape((im.shape[0], im.shape[1]))\n posz_world = pos_world[:, 2].reshape((im.shape[0], im.shape[1]))\n plt.subplot(131)\n plt.imshow(posx_world)\n plt.title('x_CC')\n plt.subplot(132)\n plt.imshow(posy_world)\n plt.title('y_CC')\n plt.subplot(133)\n plt.imshow(posz_world)\n plt.title('z_CC')\n\n imsave(out_dir + '/img_orig.png', im)\n #imsave(out_dir + '/depth_orig.png', im_depth)\n\n # hold matplotlib figure\n plt.ioff()\n plt.show()", "def ray_trace_full_set_jones(tstep=5, runtime=24, m0=(2*np.pi)/250, plots=True):\n ladcp, ctd, bathy = data_load.load_data()\n U, V, z_grid = oc.loadLADCP(ladcp)\n S, T, p, lat, lon = oc.loadCTD(ctd)\n N2 = oc.gswN2(S, T, p, lat, lon)\n for i, cast in enumerate(N2.T):\n N2[:,i] = oc.verticalBoxFilter1(cast, p[:,i])\n # Load Data\n lambdaH = pd.read_excel('lambdaH.xlsx')\n kh = pd.read_excel('Kh_masked.xlsx')\n omega = pd.read_excel('omega_masked.xlsx')\n # Depth grid stored as index in pandas dataframes\n depths = np.array(omega.index)\n X = pd.DataFrame(index=depths, columns=np.arange(0,21))\n Z = pd.DataFrame(index=depths, columns=np.arange(0,21))\n OM = pd.DataFrame(index=depths, columns=np.arange(0,21))\n m = pd.DataFrame(index=depths, columns=np.arange(0,21))\n# time = np.arange(0, runtime, tstep)\n x_all = []\n z_all = []\n Om_all = []\n starts = []\n count=0\n for i in range(kh.shape[1]):\n \n \n for k in range(kh.shape[0]):\n depth = depths[k]\n if np.isfinite(kh.loc[depth][i]) and np.isfinite(omega.loc[depth][i]):\n X.loc[depth][i], Z.loc[depth][i],\\\n OM.loc[depth][i], m.loc[depth][i]\\\n = ray_trace_jones_top_down(U[:,i], V[:,i], z_grid,\\\n N2[:,i], p[:,i], kh.loc[depth][i],\\\n m0, depth, omega.loc[depth][i], lat[:,i],\\\n tstep=tstep, runtime=runtime)\n starts.append([i+1, depth])\n x_all.append(X.loc[depth][i])\n z_all.append(Z.loc[depth][i])\n Om_all.append(OM.loc[depth][i])\n \n else:\n X.loc[depth][i] = np.nan\n OM.loc[depth][i] = np.nan\n Z.loc[depth][i] = np.nan\n m.loc[depth][i] = np.nan\n count +=1\n print(count)\n \n \n x_all = np.vstack(x_all)\n z_all = np.vstack(z_all)\n Om_all = np.vstack(Om_all)\n starts = np.vstack(starts)\n \n np.savetxt('x_ray_trace.csv', x_all)\n np.savetxt('z_ray_trace.csv', z_all)\n np.savetxt('Om_ray_trace.csv', Om_all)\n np.savetxt('starts_ray_trace.csv', starts)\n \n \n \n \n # Plotting Data\n if plots:\n fig = plt.figure()\n for i in range(kh.shape[1]):\n for k in range(kh.shape[0]):\n depth = depths[k]\n idx = i\n plt.plot(X.loc[depth][idx],Z.loc[depth][idx])\n plt.xlabel('Horizontal Distance (km)')\n plt.ylabel('depth (m)')\n plt.gca().invert_yaxis()\n \n \n fig = plt.figure()\n for i in range(kh.shape[1]):\n for k in range(kh.shape[0]):\n depth = depths[k]\n idx = i\n plt.plot(X.loc[depth][idx],m.loc[depth][idx]/(2*np.pi))\n plt.xlabel('Horizontal Distance (km)')\n plt.ylabel('vertical wavenumber')\n \n \n fig = plt.figure()\n for i in range(kh.shape[1]):\n for k in range(kh.shape[0]):\n depth = depths[k]\n idx = i\n plt.plot(X.loc[depth][idx],OM.loc[depth][idx])\n plt.xlabel('Horizontal Distance (km)')\n plt.ylabel('frequency ')\n \n \n \n \n \n return x_all, z_all, Om_all, starts", "def ray_trace_jones_bottom_up_test():", "def test_monte_carlo_rendering(\n self, n_frames=20, volume_size=(30, 30, 30), image_size=(40, 50)\n ):\n volumes = init_boundary_volume(\n volume_size=volume_size, batch_size=n_frames, shape=\"sphere\"\n )[0]\n\n # generate camera extrinsics and intrinsics\n cameras = init_cameras(n_frames, image_size=image_size)\n\n # init the grid raysampler\n raysampler_multinomial = MultinomialRaysampler(\n min_x=0.5,\n max_x=image_size[1] - 0.5,\n min_y=0.5,\n max_y=image_size[0] - 0.5,\n image_width=image_size[1],\n image_height=image_size[0],\n n_pts_per_ray=256,\n min_depth=0.5,\n max_depth=2.0,\n )\n\n # init the mc raysampler\n raysampler_mc = MonteCarloRaysampler(\n min_x=0.5,\n max_x=image_size[1] - 0.5,\n min_y=0.5,\n max_y=image_size[0] - 0.5,\n n_rays_per_image=3000,\n n_pts_per_ray=256,\n min_depth=0.5,\n max_depth=2.0,\n )\n\n # get the EA raymarcher\n raymarcher = EmissionAbsorptionRaymarcher()\n\n # get both mc and grid renders\n (\n (images_opacities_mc, ray_bundle_mc),\n (images_opacities_grid, ray_bundle_grid),\n ) = [\n VolumeRenderer(\n raysampler=raysampler_multinomial,\n raymarcher=raymarcher,\n sample_mode=\"bilinear\",\n )(cameras=cameras, volumes=volumes)\n for raysampler in (raysampler_mc, raysampler_multinomial)\n ]\n\n # convert the mc sampling locations to [-1, 1]\n sample_loc = ray_bundle_mc.xys.clone()\n sample_loc[..., 0] = 2 * (sample_loc[..., 0] / image_size[1]) - 1\n sample_loc[..., 1] = 2 * (sample_loc[..., 1] / image_size[0]) - 1\n\n # sample the grid render at the mc locations\n images_opacities_mc_ = torch.nn.functional.grid_sample(\n images_opacities_grid.permute(0, 3, 1, 2), sample_loc, align_corners=False\n )\n\n # check that the samples are the same\n self.assertClose(\n images_opacities_mc.permute(0, 3, 1, 2), images_opacities_mc_, atol=1e-4\n )", "def trace(self, worker):\n\n if self.antialiasing:\n samplingdistanceX = 1/self.imageplane.getWidth()\n samplingdistanceY = 1 / self.imageplane.getHeight()\n\n for y in worker.getYRange():\n for x in worker.getXRange():\n pixelX = 2 * x / self.imageplane.getWidth() - 1\n pixelY = 1 - 2 * y / self.imageplane.getHeight()\n\n pixelRay = self.camera.getRay(pixelX, pixelY)\n\n if self.antialiasing:\n pixelRayAntialiasing0 = self.camera.getRay(pixelX + samplingdistanceX, pixelY + samplingdistanceY)\n pixelRayAntialiasing1 = self.camera.getRay(pixelX + samplingdistanceX, pixelY - samplingdistanceY)\n pixelRayAntialiasing2 = self.camera.getRay(pixelX - samplingdistanceX, pixelY + samplingdistanceY)\n pixelRayAntialiasing3 = self.camera.getRay(pixelX - samplingdistanceX, pixelY - samplingdistanceY)\n worker.setColorAntialiasing(y, x, self.traceRay(pixelRay, 0), self.traceRay(pixelRayAntialiasing0, 0), self.traceRay(pixelRayAntialiasing1, 0), self.traceRay(pixelRayAntialiasing2, 0), self.traceRay(pixelRayAntialiasing3, 0))\n else:\n worker.setColor(y, x, self.traceRay(pixelRay, 0).getArray())", "def traceXRS(smax,pmin,fun,L=200.,nodegap=25.,Nshell=1e3,energy=1000.,\\\n rough=1.,offaxis=0.):\n #Loop through sections and construct node positions\n N = len(smax)\n rsec = []\n for sec in range(N):\n #Establish radius vector\n rad = np.array([])\n rout = 0.\n #Compute shell gap\n gap = (pmin[sec]+L-1e4)*3e-3\n #First node position\n rad = np.append(rad,200.+(1300./N)*sec)\n rout = conic.primrad(pmin[sec]+L,rad[-1],\\\n np.sqrt(1e4**2-rad[-1]**2))\n while rout+gap < 200.+(1300./N)*(sec+1):\n rad = np.append(rad,rout+gap)\n rout = conic.primrad(pmin[sec]+L,rad[-1],\\\n np.sqrt(1e4**2-rad[-1]**2))\n #Add to list of node positions\n rsec.append(rad)\n\n #Trace through all shells, computing reflectivity and geometric area\n #for each shell\n for i in range(N):\n for r in rsec[i]:\n #Set up aperture\n z = np.sqrt(1e4**2-r**2)\n a0 = conic.primrad(pmin[i],r,z)\n a1 = conic.primrad(pmin[i]+L,r,z) \n rays = sources.annulus(a0,a1,Nshell)\n tran.transform(rays,0,0,-z,0,0,0)\n\n #Set up weights\n weights = np.repeat((a1**2-a0**2) * np.pi / 100. / Nshell,Nshell)\n\n #Trace to primary\n psi = fun[i](r)\n surf.wsPrimary(rays,r,z,psi)\n rays[4] = rays[4]+np.sin(offaxis)\n rays[6] = -np.sqrt(1.-rays[4]**2)\n tran.reflect(rays)\n ang = anal.grazeAngle(rays)\n weights = weights*\\\n pol.computeReflectivities(ang,energy,rough,1,cons)[0]\n\n #Trace to secondary\n surf.wsSecondary(rays,r,z,psi)\n tran.reflect(rays)\n ang = anal.grazeAngle(rays)\n weights = weights*\\\n pol.computeReflectivities(ang,energy,rough,1,cons)[0]\n\n #Handle vignetting\n ind = np.logical_and(rays[3]>smax[i]-L,rays[3]<smax[i])\n if sum(ind) == 0:\n pdb.set_trace()\n rays = tran.vignette(rays,ind=ind)\n weights = weights[ind]\n\n #Go to focus\n try:\n surf.flat(rays)\n except:\n pdb.set_trace()\n\n #Accumulate master rays\n try:\n mrays = [np.concatenate([mrays[ti],rays[ti]]) for ti in range(10)]\n mweights = np.concatenate([mweights,weights])\n except:\n mrays = rays\n mweights = weights\n\n return mrays,mweights", "def render_multiple_meshes(mesh_paths: List[Tuple[Path, Path]],\r\n radius_multiplier=3., positioning_vector=Vector3(0, 1, 1), tilt=Transform.rotate(util.axis_unit_vector('x'), 20.),\r\n width=1920, height=1440, num_samples=256, num_workers=8) -> None:\r\n queue = util.prepare_queue(num_workers)\r\n\r\n mesh_paths = list(mesh_paths)\r\n with tqdm(total=len(mesh_paths), bar_format='Total {percentage:3.0f}% {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}{postfix}] {desc}', dynamic_ncols=True) as t:\r\n util.redirect_logger(tqdm.write, EWarn, t)\r\n for mesh_path in mesh_paths:\r\n input_path, output_path = mesh_path\r\n t.write(f'Rendering {input_path.stem}')\r\n # Make Mesh\r\n mesh = prepare_ply_mesh(input_path, util.get_predefined_spectrum('light_blue'))\r\n # Make sensor\r\n sensor_transform = cameras.create_transform_on_bbsphere(mesh.getAABB(), radius_multiplier, positioning_vector, tilt)\r\n sensor = cameras.create_sensor_from_transform(sensor_transform, width, height, fov=45., num_samples=num_samples)\r\n # Make Scene\r\n scene = util.construct_simple_scene([mesh], sensor)\r\n scene.setDestinationFile(str(output_path / f'{input_path.stem}.png'))\r\n # Make Result\r\n job = RenderJob(f'Render-{input_path.stem}', scene, queue)\r\n job.start()\r\n\r\n queue.waitLeft(0)\r\n queue.join()\r\n t.update()", "def ray_probe_box10_100():\n t = tg_box1(tg())\n for i in xrange(100):\n t.ray_probe(t.coords2index(15, 10), t.DIRECTIONS['RIGHT'], 10)", "def B_direction_from_tree(rays, coherence_length, particle_tree_small,\n particle_tree_med, particle_tree_large,\n particle_positions, particle_attribs, particle_id,\n particle_dist, voight_x0, voight_HWHM, ray_interval):\n print [sum([len(i) for i in r]) for r in particle_id.values()]\n dl_dict = {}\n for r in rays.keys():\n if len(rays[r]) == 0:\n dl_dict[r] = []\n else:\n NeToConsider = find_ne(len(rays[r]), particle_id[r],\n particle_dist[r], particle_attribs)\n near_particles_small = particle_tree_small.query_ball_point(\n rays[r], coherence_length)\n #gives list of particles close to ray\n near_particles_med = particle_tree_med.query_ball_point(\n rays[r], coherence_length)\n near_particles_large = particle_tree_large.query_ball_point(\n rays[r], coherence_length)\n near_particles = combine_particle_ids(len(\n rays[r]), near_particles_small, near_particles_med,\n near_particles_large)\n dl_vec = [0] * len(rays[r])\n try:\n print 'near_particles', len(near_particles),\\\n len(near_particles[0])\n except:\n pass\n sys.stdout.flush()\n for i in range(len(rays[r])):\n if NeToConsider[i] == 0:\n dl_vec[i] = 0\n init_theta = 2 * np.pi * random.random()\n else:\n if len(near_particles[i]) == 0:\n change_in_theta = d_theta(voight_x0, voight_HWHM)\n init_theta = init_theta + change_in_theta\n dl_vec[i] = ray_interval * np.cos(init_theta)\n else:\n #put in on 16/7/17\n if len(near_particles[i])>1e6:\n percent01 = int(0.001 * len(near_particles[i]))\n near_particles_temp = random.choice(\n near_particles[i], size = percent01)\n elif len(near_particles[i]) > 1e5:\n percent1 = int(0.01 * len(near_particles[i]))\n near_particles_temp = random.choice(\n near_particles[i], size = percent1)\n elif len(near_particles[i]) > 1e4:\n percent10 = int(0.1 * len(near_particles[i]))\n near_particles_temp = random.choice(\n near_particles[i], size = percent10)\n #------------------\n vectors = particle_positions[near_particles_temp] - \\\n rays[r][i]\n normed_vectors = np.apply_along_axis(normalise, 0,\n np.array(vectors))\n resultant_vec = [sum(normed_vectors[:, 0]),\n sum(normed_vectors[:, 1]),\n sum(normed_vectors[:, 1])]\n normed_resultant_vec = normalise(\n np.array(resultant_vec))\n angular_contribution = angle_between(\n normed_resultant_vec, rays[r][-1])\n dl_vec[i] = ray_interval * np.cos(angular_contribution)\n dl_dict[r] = dl_vec\n print 'Length of directions for ray',r,'is',len(dl_vec),len(rays[r])\n return dl_dict", "def batched_inference(models, embeddings,\n rays, N_samples, N_importance, use_disp,\n chunk,\n white_back):\n B = rays.shape[0]\n chunk = 1024*32\n results = defaultdict(list)\n for i in range(0, B, chunk):\n rendered_ray_chunks = \\\n render_rays(models,\n embeddings,\n rays[i:i+chunk],\n N_samples,\n use_disp,\n 0,\n 0,\n N_importance,\n chunk,\n dataset.white_back,\n test_time=True)\n\n for k, v in rendered_ray_chunks.items():\n results[k] += [v]\n\n for k, v in results.items():\n results[k] = torch.cat(v, 0)\n return results", "def OnDraw(self):\n self.SetCurrent()\n \n glClear(GL_COLOR_BUFFER_BIT)\n \n if self.arena != None:\n glBegin(GL_LINE_LOOP)\n [red, green, blue] = self.arena.GetColor()\n glColor3f(red, green, blue)\n for lines in self.arena.GetLines():\n [point1x, point1y] = lines.GetPosition(0)\n [point2x, point2y] = lines.GetPosition(1)\n glVertex2f(point1x, point1y)\n glVertex2f(point2x, point2y)\n \n \n glEnd()\n \n \n for pillar in self.pillar:\n glBegin(GL_LINE_LOOP)\n [red, green, blue] = pillar.GetColor()\n glColor3f(red, green, blue)\n for lines in pillar.GetLines():\n [point1x, point1y] = lines.GetPosition(0)\n [point2x, point2y] = lines.GetPosition(1)\n glVertex2f(point1x, point1y)\n glVertex2f(point2x, point2y)\n glEnd()\n\n\n#\t if self.temppoint != []:\n#\t \t glBegin(GL_POINTS)\n#\t \t glVertex2f(self.temppoint[0][0], self.temppoint[0][1])\n# glEnd()\n\t\n #Currentray is the ray where we have to worry about animation and changes.\n if self.currentray is not None: \n glBegin(GL_LINES)\n [red, green, blue] = self.currentray.GetColor()\n glColor3f(red, green, blue)\n\t\n [x, y] = [self.currentray.GetPoint().GetPosition(0), self.currentray.GetPoint().GetPosition(1)]\n glVertex2f(x, y)\n \n \n [x, y] = self.currentray.GetEndPoint(self.t)\n \n glVertex2f(x, y)\n\t\n glEnd()\n \n #These rays are static, since they have come to a stop at their points of collision.\n for i in self.ray:\n glBegin(GL_LINES)\n [red, green, blue] = i.GetColor()\n glColor3f(red, green, blue)\n \n [x, y] = [i.GetPoint().GetPosition(0), i.GetPoint().GetPosition(1)]\n glVertex(x, y)\n \n [x, y] = i.GetEndPoint(i.finaltime)\n glVertex2f(x, y)\n glEnd()\n\t\t\t\n \n self.SwapBuffers()\n \n return", "def batched_inference(models,\n coverage_models,\n embeddings,\n rays,\n N_samples,\n N_importance,\n use_disp,\n chunk,\n point_transform_func=None,\n topk=0):\n B = rays.shape[0]\n results = defaultdict(list)\n for i in range(0, B, chunk):\n rendered_ray_chunks = \\\n render_rays(models,\n coverage_models,\n embeddings,\n rays[i:i+chunk],\n N_samples,\n use_disp,\n 0,\n 0,\n N_importance,\n chunk,\n dataset.white_back,\n test_time=True,\n point_transform_func=point_transform_func,\n topk=topk)\n\n for k, v in rendered_ray_chunks.items():\n results[k] += [v.cpu()]\n\n for k, v in results.items():\n results[k] = torch.cat(v, 0)\n return results", "def multires_scaled_hex(infname, outfname, xc=25000/2.0, yc=50000/2.0, radius=5000., dxscale=0.10, ntimes=15, nllyod=20, nlayers=0, plot=False):\n shutil.copyfile(infname, outfname)\n ds = netCDF4.Dataset(outfname,'r+')\n\n tree = KDTree(zip(ds.variables['xCell'], ds.variables['yCell']))\n _, center = tree.query([xc,yc])\n centerall = tree.query_ball_point([xc,yc], radius)\n\n xcenter = ds.variables['xCell'][center]\n ycenter = ds.variables['yCell'][center]\n x = ds.variables['xVertex'] - xcenter\n y = ds.variables['yVertex'] - ycenter\n xc = ds.variables['xCell'] - xcenter\n yc = ds.variables['yCell'] - ycenter\n\n\n # form rings aound the center\n dx = np.median(ds.variables['dvEdge'])\n dv = np.median(ds.variables['dcEdge'])/2.0\n cells = np.array(centerall).tolist()\n vertices = []\n for acell in centerall:\n vertices.append(ds.variables['verticesOnCell'][acell,:ds.variables['nEdgesOnCell'][acell]]-1)\n vertices = np.unique(vertices).tolist()\n\n for i in 1+np.arange(ntimes):\n print 'Processing layer %d of %d...'%(i,ntimes)\n for acell in cells[:]:\n for cellneighs in ds.variables['cellsOnCell'][acell]-1:\n cells.append(cellneighs)\n for avertex in ds.variables['verticesOnCell'][cellneighs,:ds.variables['nEdgesOnCell'][cellneighs]]-1:\n vertices.append(avertex)\n cells = np.unique(cells).tolist()\n vertices = np.unique(vertices).tolist()\n # now have list of vertices and cells to NOT scale\n\n rmax = np.max(np.sqrt(xc[cells]*xc[cells] + yc[cells]*yc[cells]))\n # compute alpha to get approximate dx\n alpha = (dxscale*dx+rmax)/rmax\n\n # number of layers to scale\n if nlayers == 0 or not np.mod(i,nlayers):\n x *= alpha\n y *= alpha\n xc *= alpha\n yc *= alpha\n\n x[vertices] /= alpha\n y[vertices] /= alpha\n xc[cells] /= alpha\n yc[cells] /= alpha\n\n\n # plot incremental changes\n if plot:\n #plt.plot(x,y,'b.')\n plt.plot(xc,yc,'bo')\n plt.plot(0.0,0.0,'rx')\n plt.axis('equal')\n plt.show()\n\n print 'done!'\n\n # compute vertex locations from circumcenters to ensure grid is Voronoi\n interior = np.prod(ds.variables['cellsOnVertex'][:],axis=1) > 0\n\n verticesOnCell = ds.variables['verticesOnCell'][:,:]-1\n for ic, nedge in enumerate(ds.variables['nEdgesOnCell'][:]):\n verticesOnCell[ic,nedge:] = np.nan\n\n for nl in np.arange(nllyod):\n print 'On iteration %d of %d'%(nl+1, nllyod)\n if nl > 0:\n # update xc generators to be centroid of cells\n xc = np.nanmean(x[verticesOnCell], axis=1)\n yc = np.nanmean(y[verticesOnCell], axis=1)\n\n # update Voronoi diagram to be consistent with generators\n xcv = xc[ds.variables['cellsOnVertex'][interior,:]-1]\n ycv = yc[ds.variables['cellsOnVertex'][interior,:]-1]\n # handle periodicity\n if ds.is_periodic == 'YES':\n xcv = fix_periodicity_numexpr(xcv, np.mean(xcv,axis=1)[:,np.newaxis], ds.x_period)\n ycv = fix_periodicity_numexpr(ycv, np.mean(ycv,axis=1)[:,np.newaxis], ds.y_period)\n #circumcenter calc from https://en.wikipedia.org/wiki/Circumscribed_circle\n ax = xcv[:,0]\n bx = xcv[:,1] - ax\n cx = xcv[:,2] - ax\n ay = ycv[:,0]\n by = ycv[:,1] - ay\n cy = ycv[:,2] - ay\n d = ne.evaluate('2*(bx*cy-by*cx)')\n x[interior] = ne.evaluate('(cy*(bx*bx+by*by)-by*(cx*cx+cy*cy))/d + ax')\n y[interior] = ne.evaluate('(bx*(cx*cx+cy*cy)-cx*(bx*bx+by*by))/d + ay')\n\n ds.variables['xCell'][:] = xc + xcenter\n ds.variables['yCell'][:] = yc + ycenter\n ds.variables['xVertex'][:] = x + xcenter\n ds.variables['yVertex'][:] = y + ycenter\n\n ds.close()\n\n print 'finished grid'", "def plot_rayCast(self, succeeded_distance_x, succeeded_distance_y, ray_directions, z_true):\n plt.ion()\n plt.imshow(self.occupancy_map, cmap='Greys', origin='lower')\n plt.scatter(succeeded_distance_x / 10, succeeded_distance_y / 10, c='r', marker='.')\n\n x_start, y_start = succeeded_distance_x / 10, succeeded_distance_y / 10\n for index, ray_direction in enumerate(ray_directions):\n fails, range = z_true[index]\n x_dest = x_start + range * math.cos(ray_direction) / 10\n y_dest = y_start + range * math.sin(ray_direction) / 10\n color = 'b' if fails else 'r'\n plt.plot([x_start, x_dest], [y_start, y_dest], c=color, linewidth=1)\n plt.pause(0)", "def render_depth(outprefix, cam=None, obj_names=None, ray_depth=False):\n logger_name = thisfile + '->render_depth()'\n\n cam_name, obj_names, scene, outnode = _render_prepare(cam, obj_names)\n\n if ray_depth:\n raise NotImplementedError(\"Ray depth\")\n\n # Use Blender Render for anti-aliased results -- faster than Cycles,\n # which needs >1 samples to figure out object boundary\n scene.render.engine = 'BLENDER_RENDER'\n scene.render.alpha_mode = 'TRANSPARENT'\n\n node_tree = scene.node_tree\n nodes = node_tree.nodes\n\n # Render z pass, without anti-aliasing to avoid values interpolated between\n # real depth values (e.g., 1.5) and large background depth values (e.g., 1e10)\n scene.render.use_antialiasing = False\n scene.use_nodes = True\n try:\n result_socket = nodes['Render Layers'].outputs['Z']\n except KeyError:\n result_socket = nodes['Render Layers'].outputs['Depth']\n outpath_z = _render(scene, outnode, result_socket, outprefix + '_z')\n\n # Render alpha pass, with anti-aliasing to get a soft mask for blending\n scene.render.use_antialiasing = True\n result_socket = nodes['Render Layers'].outputs['Alpha']\n outpath_a = _render(scene, outnode, result_socket, outprefix + '_a')\n\n logger.name = logger_name\n logger.info(\"Depth map of %s rendered through '%s' to\", obj_names, cam_name)\n logger.info(\"\\t1. z w/o anti-aliasing: %s\", outpath_z)\n logger.info(\"\\t2. alpha w/ anti-aliasing: %s\", outpath_a)\n logger.warning(\"The scene node tree has changed\")", "def shift_start_of_ray_bundle(ray_bundle, start_offset, r, t):\n\n for ri, ray in enumerate(ray_bundle):\n b4_pt = r.dot(ray[mc.ray][1][mc.p]) - t\n b4_dir = r.dot(ray[mc.ray][0][mc.d])\n if ri == 0:\n # For the chief ray, use the input offset.\n dst = -b4_pt[2]/b4_dir[2]\n else:\n pt0 = ray_bundle[0][mc.ray][0][mc.p]\n dir0 = ray_bundle[0][mc.ray][0][mc.d]\n # Calculate distance along ray to plane perpendicular to\n # the chief ray.\n dst = -(b4_pt - pt0).dot(dir0)/b4_dir.dot(dir0)\n pt = b4_pt + dst*b4_dir\n ray[mc.ray][0][mc.p] = pt\n ray[mc.ray][0][mc.d] = b4_dir", "def render(self, shade=False):\n print(\"Scene\")\n for o in range(0, self.obj_count):\n self.obj_list[o].clear()\n for l in range(0, self.light_count):\n for o in range(0, self.obj_count):\n self.obj_list[o].receive(self.light_list[l])\n print(\"OK\")" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write a DataMap to a location in the data directory. If root is a string, then the saving is restricted to what's inside that key. The result is flattened such that the root field doesn't exist in the output. If root is a data map, then fields also within the base map are omitted If fields are given, only fields within the list are exported
def save_data_map(self, location, data_map, *, root=None, fields=None, lang='en'): location = self.get_data_path(location) result = {} if not root and not fields: raise Exception("Either a root (string or dictionary) or a list of fields " + "must be given when persisting a data map") root_is_string = isinstance(root, str) for entry_id, entry in data_map.items(): name = entry.name(lang) # stores the result for this round result_entry = {} # If the root is a string, use the field as the entry (if it exists) # if the root field doesn't exist, skip to the next if root and root_is_string: if root not in entry: continue entry = entry[root] # check the fields in the entry to copy them over for key, value in entry.items(): # check if this is an allowed field if fields and key not in fields: continue # if root is not a string, assume its a base map # If the field is part of the base map, then skip if root and not root_is_string: base_entry = root[entry.id] if key in base_entry: continue result_entry[key] = value if result_entry: result[name] = result_entry with open(location, 'w', encoding='utf-8') as f: json.dump(result, f, indent=4, ensure_ascii=False)
[ "def save_split_data_map(self, location, base_map, data_map, key_field, lang='en'):\n location = self.get_data_path(location)\n\n # Split items into buckets separated by the key field\n split_data = collections.OrderedDict()\n for entry in data_map.values():\n base_entry = base_map[entry.id]\n \n # Create the result entry. Fields are copied EXCEPT for base ones\n result_entry = {}\n for key, value in entry.items():\n if key not in base_entry:\n result_entry[key] = value\n\n # Add to result, key'd by the key field\n split_key = entry[key_field]\n split_data[split_key] = split_data.get(split_key, {})\n split_data[split_key][entry.name(lang)] = result_entry\n\n os.makedirs(location, exist_ok=True)\n # todo: should we delete what's inside?\n \n # Write out the buckets into separate json files\n for key, items in split_data.items():\n file_location = os.path.join(location, f\"{key}.json\")\n\n # Validation to make sure there's no backpathing\n if not os.path.commonprefix([location, file_location]):\n raise Exception(f\"Invalid Key Location {file_location}\")\n\n with open(file_location, 'w', encoding='utf-8') as f:\n json.dump(items, f, indent=4, ensure_ascii=False)", "def serialize(self, data):\n if isinstance(data[0], dict):\n self.write_metadata(data[0])\n data = data[1:]\n else:\n self.write_metadata({})\n\n super(BaseMapXMLWriter, self).serialize(data)", "def write_full_dir_map_file(map_path, root_dir, directories, max_num_items=100000, sample_interval=1):\n dir_files = {}\n # Get clean list of files from all directories.\n for d in directories:\n dir_path = os.path.join(root_dir, d)\n print 'Processing ' + dir_path\n dir_files[d] = sample_dir(root_dir, dir_path, sample_interval)\n\n cur_items = 0\n with open(map_path, 'w') as f:\n for d in dir_files.itervalues():\n for lab, idx in labels.iteritems():\n for path in d[lab]:\n f.write('{} {}\\n'.format(path, idx))\n cur_items += 1\n if cur_items > max_num_items:\n return", "def write_fieldmaps(fieldmap_dict, path):\n assert os.path.exists(path)\n \n for k, fmap in fieldmap_dict.items():\n file = os.path.join(path, k)\n \n # Remove any previous symlinks\n if os.path.islink(file):\n os.unlink(file) \n \n write_fieldmap(file, fmap)", "def write_to_map_yaml(self):\n dir = self.get_existed_directory(self._directories['map_dir'], 'map_dir')\n if dir:\n with open(\"{0}/maps.yaml\".format(self._directories['map_dir']), 'w') as yaml_file:\n yaml.dump(self._device_type_maps, yaml_file, default_flow_style=False)", "def setRootDatadir(self, root):\n for arg, value in self.args.items():\n if value:\n self.args[arg] = value.replace('$DATA', root)\n for arg, value in self.drendargs.items():\n if value:\n self.drendargs[arg] = value.replace('$DATA', root)\n if self.datadir:\n self.datadir = self.datadir.replace('$DATA', root)", "def writeToMap(self):\n pass", "def WritePathValsToDbroot(dbroot, fieldpath_vals, log=None):\n if fieldpath_vals:\n for concrete_fieldpath, val in fieldpath_vals:\n if log:\n log.debug(\"writing path:>%s<, >%s<\" % (concrete_fieldpath, str(val)))\n SetValueAtFieldPath(dbroot, concrete_fieldpath, val, log)\n if log:\n log.debug(\"done writing path\")\n\n if log:\n log.debug(\"done writing path vals\")", "def serialize(self, root):\n\n dtree = self.clone_original(root)\n self.decorate(dtree, 1)\n\n d = deque()\n serialization = []\n if dtree:\n d.append(dtree)\n while len(d) > 0:\n n = d.popleft()\n serialization.append((n.val, n.order))\n if n.left:\n d.append(n.left)\n if n.right:\n d.append(n.right)\n\n pkl = pickle.dumps(serialization)\n\n return pkl", "def writePlist(root_object, path_or_file, binary=False):\n did_open = False\n if isinstance(path_or_file, (str, unicode)):\n path_or_file = open(path_or_file, \"w\")\n did_open = True\n dump(root_object, path_or_file, binary)\n if did_open:\n path_or_file.close()", "def export(d, key):\n ed = {}\n\n if d is None:\n return None\n\n def set_if_not_null(d, key, value):\n if value is not None:\n d[key] = value\n else:\n d[key] = None\n\n if isinstance(key, (tuple, list)):\n for key_params in key:\n res = export(d, key_params)\n ed.update(res)\n elif isinstance(key, string_types):\n if key == '*':\n if isdictionarylike(d):\n for d_key in d:\n set_if_not_null(ed, d_key, d[d_key])\n else:\n try:\n # we must try to access this argument\n # and should not check the \"in\" operator first\n # since otherwise we will not load lazy-loaded\n # documents correctly\n set_if_not_null(ed, key, d[key])\n except KeyError:\n pass\n elif isinstance(key, dict):\n for key_name, key_value in key.items():\n if key_name == '*':\n if isinstance(d, dict):\n for d_key in d:\n set_if_not_null(ed, d_key, export(d[d_key], key_value))\n elif isiterable(d):\n return [v for v in [export(element, key_value) for element in d] if v is not None]\n elif callable(key_name):\n for d_key in d:\n if key_name(d_key):\n set_if_not_null(ed, d_key, export(d[d_key], key_value))\n else:\n try:\n # we must try to access this argument\n # and should not check the \"in\" operator first\n # since otherwise we will not load lazy-loaded\n # documents correctly\n set_if_not_null(ed, key_name, export(d[key_name], key_value))\n except KeyError:\n pass\n elif callable(key):\n return key(d)\n return ed", "def writeSDM2DtoRoot(inData, fileName):\n\tcount_calls('writeSDM2DtoRoot')\n\toutROOT = root_open(os.curdir+os.sep+'ROOT'+os.sep+fileName, mode = \"RECREATE\")\n\tbinning3=[]\n\tfor dataset in inData:\n\t\tif not dataset[0] in binning3:\n\t\t\tbinning3.append(dataset[0])\n\t\tif not dataset[1] in binning3:\n\t\t\tbinning3.append(dataset[1])\n\tbinning3.sort()\n\tbinning3 = numpy.asarray(binning3,dtype=numpy.float64)\t\t\n\tmeta = inData[0][2]\n\tfor i in range(len(meta)):\n\t\tplot = meta[i]\n\t\tbinning2=[]\n\t\tid2 = plot[0][-1]\n\t\tid1 = plot[0][-2]\n\t\tfor point in plot:\n\t\t\tif not point[0] in binning2:\n\t\t\t\tbinning2.append(point[0])\n\t\t\tif not point[1] in binning2:\n\t\t\t\tbinning2.append(point[1])\t\t\n\t\tbinning2.sort()\n\t\tbinning2 = numpy.asarray(binning2,dtype=numpy.float64)\n\t\thi = TH2D(id1+\" vs. \"+id2,id1+\" vs. \"+id2,len(binning3)-1,binning3, len(binning2)-1,binning2)\n\t\tfor dataset in inData:\n\t\t\tm3 = (dataset[0]+dataset[1])/2\n\t\t\tbin3 = hi.GetXaxis().FindBin(m3)\n\t\t\tplot = dataset[2][i]\n\t\t\tfor point in plot:\n\t\t\t\tm2 = (point[0]+point[1])/2\n\t\t\t\tbin2 = hi.GetYaxis().FindBin(m2)\n\t\t\t\tif id1 == id2:\n\t\t\t\t\tv = point[2]\n\t\t\t\t\te = point[3]\n\t\t\t\telse:\n\t\t\t\t\tv = point[6]\n\t\t\t\t\te = point[7]\n\t\t\t\thi.SetBinContent(bin3,bin2,v)\n\t\t\t\thi.SetBinError(bin3,bin2,e)\n\t\tif not id1 == id2:\n\t\t\thi = removePhaseAmbiguities(hi)\n\t\thi.Write()\n\toutROOT.Close()", "def write_map_file_with_undersampling(map_path, root_dir, directories, max_num_items=10000, sample_interval=1):\n dir_files = {}\n # Get clean list of files from all directories.\n for d in directories:\n dir_path = os.path.join(root_dir, d)\n print 'Processing ' + dir_path\n dir_files[d] = sample_balance_dir(root_dir, dir_path, sample_interval)\n # Balance directories. Each directory has equal number of files for each\n # label so just take count from first label.\n min_size = min([len(v[labels.keys()[0]]) for v in dir_files.itervalues()]) \n max_per_dir_per_class = min(max_num_items / (len(dir_files) * len(labels)), min_size)\n print('Using {} iterms per directory per class.'.format(max_per_dir_per_class))\n\n with open(map_path, 'w') as f:\n for dir in dir_files.itervalues():\n for lab_dir in dir.iteritems():\n for path in lab_dir[1][:max_per_dir_per_class]:\n f.write('{} {}\\n'.format(path, labels[lab_dir[0]]))", "def enmap2dmap(emap, dmap, root=0):\n\tfor ti in range(dmap.ntile):\n\t\tid = dmap.geometry.tile_ownership[ti]\n\t\tloc = dmap.geometry.tile_glob2loc[ti]\n\t\tbox = dmap.geometry.tile_boxes[ti]\n\t\tif dmap.comm.rank == root:\n\t\t\tdata = np.ascontiguousarray(emap[...,box[0,0]:box[1,0],box[0,1]:box[1,1]])\n\t\tif dmap.comm.rank == root and id == root:\n\t\t\tdmap.tiles[loc] = data\n\t\telif dmap.comm.rank == root:\n\t\t\tdmap.comm.Send(data, dest=id, tag=loc)\n\t\telif dmap.comm.rank == id:\n\t\t\tdmap.comm.Recv(dmap.tiles[loc], source=root, tag=loc)", "def dumpMap(self, path, outPath):\n J = os.path.join\n outPath = os.path.realpath(outPath)\n dirs = ('animations', 'animcurv', 'mod', 'models', 'TEX0', 'TEX1', 'voxmap')\n for d in dirs:\n os.makedirs(J(outPath, d), exist_ok=True)\n self.dumpAnimations(J(path, 'ANIM'), J(outPath, 'animations'))\n self.dumpAnimCurv (J(path, 'ANIMCURV'), J(outPath, 'animcurv'))\n self.dumpModels (J(path, 'MODELS'), J(outPath, 'models'))\n self.dumpTextures (J(path, 'TEX0'), J(outPath, 'TEX0'))\n self.dumpTextures (J(path, 'TEX1'), J(outPath, 'TEX1'))\n self.dumpVoxMap (J(path, 'VOXMAP'), J(outPath, 'voxmap'))\n for name in os.listdir(path):\n if re.match(r'^mod[0-9a-fA-F]+\\.zlb', name):\n self.dumpMod(J(path, name.split('.')[0]), J(outPath, 'mod'))", "def write_stata_docs(stata_docs: Dict[str, str], output_path: str) -> None:\n for form_id, document in stata_docs.items():\n write_path = os.path.join(output_path, '{0}.xml'.format(form_id))\n with open(write_path, mode='w', encoding=\"UTF-8\") as out_doc:\n out_doc.write(document)\n logger.info(\"Wrote form data for form_id: {0}, to a file at: \"\n \" {1}.\".format(form_id, write_path))", "def to_file_map(self, file_map=None):\n if file_map is None:\n file_map = self.file_map\n data = self.get_data()\n with file_map['image'].get_prepare_fileobj('wb') as bvf:\n self._write_header(bvf, self.header)\n self._write_data(bvf, data, self.header)\n self.file_map = file_map", "def save_maps(self, dirname):\n try:\n os.makedirs(dirname)\n for f,m in self:\n filename = dirname+\"%dMHz.fits\" % int(1e3*f)\n m.to_fits(filename)\n except (IOError, OSError) as e:\n if e.errno != e.EEXIST:\n raise SystemExit('{}: {}'.format(e.filename, e.strerror))", "def export_nodemap(self) -> None:\n\n # Clear arrays\n self.mapdl.run(\"*DEL,coords_1\")\n self.mapdl.run(\"*DEL,coords_2\")\n self.mapdl.run(\"*DEL,header\")\n\n # Change to post-processing\n self.mapdl.post1()\n self.mapdl.set(\"LAST\")\n self.mapdl.allsel()\n\n # Get total number of nodes\n self.mapdl.get(\"NodeCount_1\", \"NODE\", \"\", \"COUNT\")\n\n # Get coordinates, displacements, strains, and stresses\n self.mapdl.run(\"*VGET,dEPTOXs,NODE,,EPTO,X\")\n self.mapdl.run(\"*VGET,dEPTOYs,NODE,,EPTO,Y\")\n self.mapdl.run(\"*VGET,dEPTOXYs,NODE,,EPTO,XY\")\n self.mapdl.run(\"*VGET,dEPTOEQVs,NODE,,EPTO,EQV\")\n self.mapdl.run(\"*VGET,dUXs,NODE,,U,X\")\n self.mapdl.run(\"*VGET,dUYs,NODE,,U,Y\")\n self.mapdl.run(\"*VGET,dUZs,NODE,,U,Z\")\n self.mapdl.run(\"*DIM,coords_1,ARRAY,NodeCount_1,14\") # Prepare Output-File\n self.mapdl.run(\"*VGET,coords_1(1,1),NODE,,NLIST\") # Node index\n self.mapdl.run(\"*VGET,coords_1(1,2),NODE,coords_1(1,1),LOC,X\") # Undeformed coordinates X\n self.mapdl.run(\"*VGET,coords_1(1,3),NODE,coords_1(1,1),LOC,Y\") # Undeformed coordinates Y\n self.mapdl.run(\"*VGET,coords_1(1,4),NODE,coords_1(1,1),LOC,Z\") # Undeformed coordinates Z\n self.mapdl.run(\"*VGET,coords_1(1,5),NODE,coords_1(1,1),U,X\") # Displacements X\n self.mapdl.run(\"*VGET,coords_1(1,6),NODE,coords_1(1,1),U,Y\") # Displacements Y\n self.mapdl.run(\"*VGET,coords_1(1,7),NODE,coords_1(1,1),U,Z\") # Displacements Z\n self.mapdl.run(\"*VOPER,coords_1(1,8),dEPTOXs,MULT,100.0\") # Total strains X\n self.mapdl.run(\"*VOPER,coords_1(1,9),dEPTOYs,MULT,100.0\") # Total strains Y\n self.mapdl.run(\"*VOPER,coords_1(1,10),dEPTOXYs,MULT,0.5\") # Total strains XY\n self.mapdl.run(\"*VOPER,coords_1(1,11),dEPTOEQVs,MULT,100.0\") # Total strains XY\n self.mapdl.run(\"*VGET,coords_1(1,12),NODE,coords_1(1,1),S,X\") # Stress X\n self.mapdl.run(\"*VGET,coords_1(1,13),NODE,coords_1(1,1),S,Y\") # Stress Y\n self.mapdl.run(\"*VGET,coords_1(1,14),NODE,coords_1(1,1),S,XY\") # Stress XY\n\n # Define header\n self.mapdl.run(\"*DIM,header,string,10,14\")\n self.mapdl.run(\"header(1,1)='index'\")\n self.mapdl.run(\"header(1,2)='x_undf'\")\n self.mapdl.run(\"header(1,3)='y_undf'\")\n self.mapdl.run(\"header(1,4)='z_undf'\")\n self.mapdl.run(\"header(1,5)='ux'\")\n self.mapdl.run(\"header(1,6)='uy'\")\n self.mapdl.run(\"header(1,7)='uz'\")\n self.mapdl.run(\"header(1,8)='eps_x'\")\n self.mapdl.run(\"header(1,9)='eps_y'\")\n self.mapdl.run(\"header(1,10)='eps_xy'\")\n self.mapdl.run(\"header(1,11)='eps_eqv'\")\n self.mapdl.run(\"header(1,12)='s_x'\")\n self.mapdl.run(\"header(1,13)='s_y'\")\n self.mapdl.run(\"header(1,14)='s_xy'\")\n\n # Write into file\n with self.mapdl.non_interactive:\n self.mapdl.run(\"*CFOPEN,Nodemap,txt\")\n self.mapdl.run(\"*VWRITE,header(1,1),header(1,2),header(1,3),header(1,4),header(1,5),header(1,6),\"\n \"header(1,7),header(1,8),header(1,9),header(1,10),\"\n \"header(1,11),header(1,12),header(1,13),header(1,14)\")\n self.mapdl.run(\"('#',A11,13(';',A12))\")\n self.mapdl.run(\"*VWRITE,coords_1(1,1),coords_1(1,2),coords_1(1,3),coords_1(1,4),coords_1(1,5),\"\n \"coords_1(1,6),coords_1(1,7),coords_1(1,8),coords_1(1,9),coords_1(1,10),\"\n \"coords_1(1,11),coords_1(1,12),coords_1(1,13),coords_1(1,14)\")\n self.mapdl.run(\"(13(F12.6,';')F12.6)\")\n self.mapdl.run(\"*CFCLOSE\")\n self.mapdl.run(\"/GOPR\")" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Writes a DataMap to a folder as separated json files. The split occurs on the value of key_field. Fields that exist in the base map are not copied to the data maps
def save_split_data_map(self, location, base_map, data_map, key_field, lang='en'): location = self.get_data_path(location) # Split items into buckets separated by the key field split_data = collections.OrderedDict() for entry in data_map.values(): base_entry = base_map[entry.id] # Create the result entry. Fields are copied EXCEPT for base ones result_entry = {} for key, value in entry.items(): if key not in base_entry: result_entry[key] = value # Add to result, key'd by the key field split_key = entry[key_field] split_data[split_key] = split_data.get(split_key, {}) split_data[split_key][entry.name(lang)] = result_entry os.makedirs(location, exist_ok=True) # todo: should we delete what's inside? # Write out the buckets into separate json files for key, items in split_data.items(): file_location = os.path.join(location, f"{key}.json") # Validation to make sure there's no backpathing if not os.path.commonprefix([location, file_location]): raise Exception(f"Invalid Key Location {file_location}") with open(file_location, 'w', encoding='utf-8') as f: json.dump(items, f, indent=4, ensure_ascii=False)
[ "def writeSplitDatasetToJson(dataset:typings.dataset,split:bool): \n for index,key in enumerate(dataset):\n os.makedirs('dataset',exist_ok=True)\n if (key != \"__status\" and key!='__invalid'):\n os.makedirs('dataset/{}'.format(key), exist_ok=True)\n os.makedirs('dataset/dataset_txt/{}'.format(key),exist_ok=True)\n tempDf = dataset[key].T\n with open('dataset/{}/list.json'.format(key),'w') as f:\n json.dump(list(tempDf.index),f)\n for index in range(0,len(tempDf.index)):\n with open(\"dataset/{}/{}\".format(key,tempDf.index[index]), 'w', encoding='utf-8') as file:\n json.dump(json.loads(str(tempDf.iloc[[index]][['goal','log']].T.to_json(force_ascii=False)).replace(\"null\",\"\")),file,ensure_ascii=False,indent=4)\n print(\"{} files written!\".format(len(tempDf.index)))\n if split == True:\n tempDf['log'] = [[{'text':item['text']} for item in x] for x in tempDf['log']]\n for index in range(0,len(tempDf.index)):\n with open(\"dataset/dataset_txt/{}/{}_txt.json\".format(key,str(tempDf.index[index]).split('.')[0]), 'w', encoding='utf-8') as file:\n json.dump(json.loads(str(tempDf.iloc[[index]][['goal','log']].T.to_json(force_ascii=False)).replace(\"null\",\"\")),file,ensure_ascii=False,indent=4)\n print(\"Splitting files! {} files written!\".format(len(tempDf.index)))\n dataset['__status'].to_excel('dataset/stats.xlsx')\n print(\"Stats.xlsx written!\")", "def write_fieldmaps(fieldmap_dict, path):\n assert os.path.exists(path)\n \n for k, fmap in fieldmap_dict.items():\n file = os.path.join(path, k)\n \n # Remove any previous symlinks\n if os.path.islink(file):\n os.unlink(file) \n \n write_fieldmap(file, fmap)", "def save_data_map(self, location, data_map, *, root=None, fields=None, lang='en'):\n location = self.get_data_path(location)\n\n result = {}\n\n if not root and not fields:\n raise Exception(\"Either a root (string or dictionary) or a list of fields \" +\n \"must be given when persisting a data map\")\n\n root_is_string = isinstance(root, str)\n\n for entry_id, entry in data_map.items():\n name = entry.name(lang)\n\n # stores the result for this round\n result_entry = {}\n\n # If the root is a string, use the field as the entry (if it exists)\n # if the root field doesn't exist, skip to the next\n if root and root_is_string:\n if root not in entry:\n continue\n entry = entry[root]\n\n # check the fields in the entry to copy them over\n for key, value in entry.items():\n # check if this is an allowed field\n if fields and key not in fields:\n continue\n\n # if root is not a string, assume its a base map\n # If the field is part of the base map, then skip\n if root and not root_is_string:\n base_entry = root[entry.id]\n if key in base_entry:\n continue\n \n result_entry[key] = value\n\n if result_entry:\n result[name] = result_entry\n\n with open(location, 'w', encoding='utf-8') as f:\n json.dump(result, f, indent=4, ensure_ascii=False)", "def write_all_files(curdir, json_dict):\n for field in json_dict.keys():\n fieldname = \"hgf_\" + field\n if len(field) == len('XXXii'):\n write_json(curdir, fieldname, json_dict[field])\n else:\n write_file(curdir, fieldname, json_dict[field])\n return", "def write_indiv_json(self, output_folder: str, song_info: dict):\n\t\tfile_list = []\n\n\t\t# for ever song id in the song_info dict, there is another dict full of the song information\n\t\t# for that specific song id\n\t\tfor song_id in song_info.keys():\n\t\t\tfile_name = output_folder + song_id + \".json\"\n\t\t\tfile = open(file_name, 'w')\n\t\t\tjson_str = to_json(song_info[song_id])\n\t\t\tfile.write(json_str)\n\t\t\tfile.close()\n\t\t\tfile_list.append(file_name)", "def write_indiv_json(self, output_folder:str, song_info:dict):\n file_list = []\n\n # for ever song id in the song_info dict, there is another dict full of the song information\n # for that specific song id\n for song_id in song_info.keys():\n file_name = self.root_dir + song_id + \".json\"\n file = open(file_name, 'w')\n json_str = to_json(song_info[song_id])\n file.write(json_str)\n file.close()\n file_list.append(file_name)", "def adapter(self, dict_of_fields):\n\n # Hash function of username\n def hash_processor(d):\n if 'username' in d:\n return hash_username(d['username'])\n self.report(d, 'username')\n\n # Natural naming\n file_input = {k: k + '.json' for k in dict_of_fields}\n file_output = {k: k + '.csv' for k in dict_of_fields}\n # Output fields\n output_fields = dict_of_fields\n # Map Dictionary\n pre_map_dict = {k: [\n (\n (0, 0),\n k,\n {f: f for f in v if f != 'username'}\n ),\n (\n (0, 1),\n k,\n {\n 'username': hash_processor\n }\n ) if any([f == 'username' for f in v]) else None\n ] for k, v in dict_of_fields.items()}\n pre_map_dict = {k: [p for p in l if p is not None] for k, l in pre_map_dict.items()}\n post_map_dict = {k: [\n (\n (2, 2),\n k,\n lambda x: x,\n )\n ] for k, v in dict_of_fields.items()}\n return file_input, file_output, output_fields, pre_map_dict, post_map_dict", "def _dict_to_hdf5_subdatasets(hdf5_object, dictionary, base_path = ''):\n\n\tfor key, value in dictionary.items():\n\n\t\thdf5_object.create_dataset(os.path.join(base_path, key), data = value, compression = 'gzip', chunks = True)\n\n\treturn", "def writeToMap(self):\n pass", "def export(self, folder):\n f = open(folder, \"w\")\n f.write(json.dumps(self.data, sort_keys=True, indent=4))\n f.close()", "def __output_to_file(self):\n\n fn = self.out_dir + self.output_file\n map_keys = self.ordered_keys\n row_count = len(self.output_map[map_keys[0]])\n\n with open(fn, 'w') as csvfile:\n wr = writer(csvfile)\n wr.writerow(map_keys)\n\n for row in range(row_count):\n temp = []\n for col in map_keys:\n temp.append(self.output_map[col][row])\n\n wr.writerow(temp)", "def df_split(DATA_OUT, data, cpu, df_in):\n \n # make a tmp dir to write out \n dir_nm = os.path.join(DATA_OUT+data+'_tmp/')\n print(dir_nm)\n os.mkdir(dir_nm)\n \n # split them \n df_list = np.array_split(df_in, cpu)\n\n # write them out\n for i, df in enumerate(df_list):\n df.to_json(dir_nm+data+'_'+str(i)+'.json', orient = 'split')", "def divide_jsons():\n with open(file) as our_file:\n json_file = json.load(our_file)\n our_file.close()\n\n for i in range(count, len(json_file)):\n data = json_file[i]\n with open('/usr/local/airflow/data/jsons/src-' + str(i) + '.json', 'w') as outfile:\n json.dump(data, outfile)\n outfile.close()", "def write_running_data(self):\n if(self.DEBUG):\n print(\"Writing data to files now\")\n\n # Looping through self.running_data to write each entry to a file\n for key in self.running_data:\n\n if(self.DEBUG):\n print(\n \"Writing to \" + key + \".json: \" +\n str(json.dumps(self.running_data[key]))\n )\n\n self.file_put_contents(\n self.config['running_data_dir'] + os.sep + key + \".json\",\n json.dumps(self.running_data[key])\n )\n\n if(self.DEBUG):\n print(\"Writing \" + key + \".json data file\")", "def write_full_dir_map_file(map_path, root_dir, directories, max_num_items=100000, sample_interval=1):\n dir_files = {}\n # Get clean list of files from all directories.\n for d in directories:\n dir_path = os.path.join(root_dir, d)\n print 'Processing ' + dir_path\n dir_files[d] = sample_dir(root_dir, dir_path, sample_interval)\n\n cur_items = 0\n with open(map_path, 'w') as f:\n for d in dir_files.itervalues():\n for lab, idx in labels.iteritems():\n for path in d[lab]:\n f.write('{} {}\\n'.format(path, idx))\n cur_items += 1\n if cur_items > max_num_items:\n return", "def WriteDict( d, filename, *fields ):\r\n\tif len( fields ): d = dict( ( k, v ) for k, v in d.items() if k in fields )\r\n\tfile = open( MakeWayFor( filename ), 'wt' )\r\n\tfile.write( '{\\n' )\r\n\tfor k, v in sorted( d.items() ): file.write( '\\t%s : %s,\\n' % ( repr( k ), repr( v ) ) )\r\n\tfile.write( '}\\n' )\r\n\tfile.close()", "def generate(self, filepath: str, data: dict): \n \n with open(filepath, 'w') as f:\n json.dump(data, f, indent=4)", "def add_json(self, data_file, *, key=None, join=None):\n\n if not join:\n raise ValueError('Join must have a value')\n\n data = self.reader.load_json(self._get_filename(data_file))\n\n def derive_key(d):\n return d[join]\n\n # validation, make sure it links\n entry_map = { str(e[join]):e for e in self.data_map.values() }\n converted_keys = [str(k) for k in data.keys()]\n unlinked = [k for k in converted_keys if k not in entry_map.keys()]\n if unlinked:\n raise Exception(\n \"Several invalid names found in sub data map. Invalid entries are \" +\n ','.join('None' if e is None else str(e) for e in unlinked))\n\n # validation complete, it may not link to all base entries but thats ok\n for data_key, data_entry in data.items():\n base_entry = entry_map[str(data_key)]\n \n if key:\n base_entry[key] = data_entry\n \n elif isinstance(data_entry, collections.Mapping):\n joindicts(base_entry, data_entry)\n \n else:\n # If we get here, its a key-less merge with a non-dict\n # We cannot merge a dictionary with a non-dictionary\n raise Exception(\"Invalid data, the data map must be a dictionary for a keyless merge\")\n\n return self", "def addFileSizeToJson(smallKey, smallKeyFolder, shpFolder):\n\n os.chdir(shpFolder)\n for file in glob.glob(\"*.shp\"):\n shpFileName = file\n shpFilePath = os.path.join(shpFolder, shpFileName)\n sizeInBytes = os.path.getsize(shpFilePath)\n jsonPath = os.path.join(smallKeyFolder, smallKey) + '.json'\n with open(jsonPath) as f:\n data = json.load(f)\n data[\"config\"][\"File_Size\"] = sizeInBytes\n with open(jsonPath, \"w\") as f:\n json.dump(data, f)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read subnets from config file or if not set try to get them from default VPC
def _provide_subnets(self): if not self.cfg.aws.subnet: logging.debug("Subnets are not provided") # Try to get subnet from default VPC or VPC set in aws-vpc config parameter vpc = self._provide_vpc() if vpc: subnet_list = vpc.subnets.all() self.vpc_id = vpc.id self.subnets = ','.join(map(lambda x: x.id, subnet_list)) else: # Ensure that VPC is set and that subnets provided belong to it subnets = [x.strip() for x in self.cfg.aws.subnet.split(',')] # If aws-vpc parameter is set, use this VPC, otherwise use VPC of the # first subnet logging.debug(f"Subnets are provided: {' ,'.join(subnets)}") vpc = None if self.vpc_id: if self.vpc_id.lower() == 'none': return None vpc = self.ec2.Vpc(self.vpc_id) for subnet_name in subnets: subnet = self.ec2.Subnet(subnet_name) if not vpc: vpc = subnet.vpc # if subnet is invalid - will throw an exception botocore.exceptions.ClientError with InvalidSubnetID.NotFound else: if subnet.vpc != vpc: raise UserReportError(returncode=INPUT_ERROR, message="Subnets set in aws-subnet parameter belong to different VPCs") self.vpc_id = vpc.id self.subnets = ','.join(subnets) logging.debug(f"Using VPC {self.vpc_id}, subnet(s) {self.subnets}")
[ "def load_excluded_subnets():\n \n control_networks = list()\n with open('/etc/map/testbed-control-subnets.txt') as f:\n for line in f:\n subnet = ipaddress.ip_network(line.strip())\n control_networks.append(subnet)\n\n return control_networks", "def test_vmware_service_resources_subnets_get(self):\n pass", "def _get_subnets(self) -> List[dict]:\n print('Getting subnets...')\n\n return self._run_az([\n 'network', 'vnet', 'subnet', 'list',\n '--resource-group', self._selected_resource_group['name'],\n '--vnet-name', self._selected_virtual_network['name']\n ])", "def test_azure_service_api_network_subnets_get(self):\n pass", "def get_subnet(self, subnet_id):", "def get_subnets(connection, vpc_id):\n return connection.get_all_subnets(filters={'vpc_id': vpc_id})", "def multi_subnet_ip_configurations(self) -> Optional[Sequence['outputs.MultiSubnetIpConfigurationResponse']]:\n return pulumi.get(self, \"multi_subnet_ip_configurations\")", "def allowed_subnets(self) -> Sequence['outputs.GetVirtualNetworkAllowedSubnetResult']:\n return pulumi.get(self, \"allowed_subnets\")", "def private_subnet(template):\n return template.resources[\"PrivateSubnet\"]", "def set_subnet_cidr(value, yaml_file):\n yaml_content = get_yaml(elife_global_yaml)\n yaml_content[\"defaults\"][\"aws\"][\"subnet-cidr\"] = value\n write_yaml(yaml_content, yaml_file)", "def validate_subnets(subnet_spec):\n exit_if_none(subnet_spec, \"Missing subnets\")\n actual_subnets = {}\n paginator = boto3.client('ec2').get_paginator('describe_subnets')\n for page in paginator.paginate():\n for subnet in page['Subnets']:\n actual_subnets[subnet['SubnetId']] = subnet['VpcId']\n subnets = []\n vpcs = set()\n for subnet_id in subnet_spec.split(\",\"):\n vpc_id = actual_subnets.get(subnet_id)\n exit_if_none(vpc_id, f\"invalid subnet: {subnet_id}\")\n subnets.append(subnet_id)\n vpcs.add(vpc_id)\n if (len(vpcs) > 1):\n exit_if_none(None, \"subnets belong to different VPCs\")\n return subnets", "def get(resource_name: str,\n id: pulumi.Input[str],\n opts: Optional[pulumi.ResourceOptions] = None,\n internet_id: Optional[pulumi.Input[str]] = None,\n ip_addresses: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,\n max_ip_address: Optional[pulumi.Input[str]] = None,\n min_ip_address: Optional[pulumi.Input[str]] = None,\n netmask: Optional[pulumi.Input[int]] = None,\n network_address: Optional[pulumi.Input[str]] = None,\n next_hop: Optional[pulumi.Input[str]] = None,\n switch_id: Optional[pulumi.Input[str]] = None,\n zone: Optional[pulumi.Input[str]] = None) -> 'Subnet':\n opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))\n\n __props__ = _SubnetState.__new__(_SubnetState)\n\n __props__.__dict__[\"internet_id\"] = internet_id\n __props__.__dict__[\"ip_addresses\"] = ip_addresses\n __props__.__dict__[\"max_ip_address\"] = max_ip_address\n __props__.__dict__[\"min_ip_address\"] = min_ip_address\n __props__.__dict__[\"netmask\"] = netmask\n __props__.__dict__[\"network_address\"] = network_address\n __props__.__dict__[\"next_hop\"] = next_hop\n __props__.__dict__[\"switch_id\"] = switch_id\n __props__.__dict__[\"zone\"] = zone\n return Subnet(resource_name, opts=opts, __props__=__props__)", "def get_subnets(self, ec2, client):\n filters = [{'Name': 'vpc-id', 'Values': [self.vpc_id]}]\n self.subnets = list(ec2.subnets.filter(Filters=filters))\n public_subnets = OrderedDict()\n private_subnets = OrderedDict()\n\n for subnet in self.subnets:\n subnet_full = client.describe_subnets(\n SubnetIds=[subnet.id]).get('Subnets')[0]\n tag_dict = {t['Key'] : t['Value'] for t in subnet_full['Tags']}\n try:\n network = tag_dict['Network']\n except KeyError:\n network = None\n name = tag_dict['Name']\n if name[:6].lower() == 'public':\n public_subnets[tag_dict['Name']] = {'Name' : name, 'id' : subnet.id}\n elif name[:7].lower() == 'private':\n private_subnets[tag_dict['Name']] = {'Name': name, 'id': subnet.id}\n sorted_public_subnets = [public_subnets[x] for x in sorted(public_subnets)]\n sorted_private_subnets = [private_subnets[x] for x in sorted(private_subnets)]\n self.public_subnets = sorted_public_subnets\n self.private_subnets = sorted_private_subnets", "def nat_subnets(self) -> pulumi.Input[Sequence[pulumi.Input[str]]]:\n return pulumi.get(self, \"nat_subnets\")", "def test_pcluster_configure_avoid_bad_subnets(\n request,\n vpc_stack,\n subnet_in_use1_az3,\n pcluster_config_reader,\n key_name,\n region,\n os,\n instance,\n scheduler,\n clusters_factory,\n test_datadir,\n):\n config_path = test_datadir / \"config.yaml\"\n bad_subnets_prompts = (\n standard_first_stage_prompts(region, key_name, scheduler, os, instance)\n + standard_queue_prompts(scheduler, instance, region)\n + [\n PROMPTS[\"vpc_creation\"](\"n\"),\n PROMPTS[\"vpc_id\"](vpc_stack.cfn_outputs[\"VpcId\"]),\n PROMPTS[\"subnet_creation\"](\"n\"),\n prompt_head_node_subnet_id(subnet_id=\"\", no_of_omitted_subnets=3),\n prompt_compute_node_subnet_id(subnet_id=\"\", head_node_subnet_id=\"\", no_of_omitted_subnets=3),\n ]\n )\n stages = orchestrate_pcluster_configure_stages(prompts=bad_subnets_prompts, scheduler=scheduler)\n assert_configure_workflow(request, region, stages, config_path)\n assert_config_contains_expected_values(key_name, scheduler, os, instance, region, None, None, config_path)", "def get_restricted_subnets(self):\n self.navigate_to(self.CONFIGURE, self.CONFIGURE_GUEST_ACCESS)\n\n #@author: Jane.Guo @since: 2013-09 adapt to 9.8 guest access improvement\n edit_span = self.info['loc_cfg_guest_access_edit_span'] % DEFAULT_GUEST_ACCESS_NAME\n time.sleep(2)\n self.s.click_and_wait(edit_span)\n self.s.click_and_wait(self.info['loc_cfg_guest_access_restrict_list'])\n \n subnet_list = []\n i = 1\n while True:\n i = i + 1\n locator = self.info['loc_cfg_restricted_rule_row']\n locator = locator.replace(\"$_$\", str(i))\n time.sleep(3)\n if self.s.is_element_present(locator):\n locator = self.info['loc_cfg_restricted_subnets_textbox']\n locator = locator.replace(\"$_$\", str(i))\n subnet = self.s.get_text(locator)\n subnet_list.append(subnet)\n\n else:\n break\n self.s.click_and_wait(self.info['loc_cfg_guest_access_cancel'])\n time.sleep(1)\n\n return subnet_list", "def subnet_overrides(self) -> Sequence['outputs.GetVirtualNetworkSubnetOverrideResult']:\n return pulumi.get(self, \"subnet_overrides\")", "def test_create_subnet_with_cidr_and_default_subnetpool(self):\n with self.network() as network:\n tenant_id = network['network']['tenant_id']\n subnetpool_prefix = '10.0.0.0/8'\n with self.subnetpool(prefixes=[subnetpool_prefix],\n admin=True,\n name=\"My subnet pool\",\n tenant_id=tenant_id,\n min_prefixlen='25',\n is_default=True):\n data = {'subnet': {'network_id': network['network']['id'],\n 'cidr': '10.0.0.0/24',\n 'ip_version': constants.IP_VERSION_4,\n 'tenant_id': tenant_id}}\n subnet_req = self.new_create_request('subnets', data)\n res = subnet_req.get_response(self.api)\n subnet = self.deserialize(self.fmt, res)['subnet']\n self.assertIsNone(subnet['subnetpool_id'])", "def get_first_subnet_per_region(self, region=None):\n # TODO: Sometimes this might cause AWS rate limiting to hit. For those cases, we should\n # probably catch the exceptions and default to the self.metadata[\"base_subnets\"] for the\n # mapping.\n regions = [region] if region is not None else self.get_regions()\n search_pattern = \"*-vpn\"\n subnet_per_region = {}\n for r in regions:\n host_info = self.get_host_info_specific_args(r, search_pattern)\n if not host_info:\n continue\n subnet_per_region[r] = host_info[\"subnet\"]\n return subnet_per_region" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get boto3 Vpc object for either configured VPC, or if not, default VPC for the configured region, if not available return None
def _provide_vpc(self): if self.vpc_id: if self.vpc_id.lower() == 'none': return None return self.ec2.Vpc(self.vpc_id) vpcs = list(self.ec2.vpcs.filter(Filters=[{'Name':'isDefault', 'Values':['true']}])) if len(vpcs) > 0: logging.debug(f'Default vpc is {vpcs[0].id}') return vpcs[0] else: return None
[ "def get_vpc_info(self):\n if not self.base['cluster'].get('vpc'):\n res = self.ec2.describe_vpcs()\n self.base['cluster']['vpc'] = [vpc['VpcId'] for vpc in res['Vpcs'] if vpc['IsDefault']][0]\n logger.info('No vpc selected, using default vpc')\n logger.info(self.base['cluster']['vpc'])", "def get_usable_vpc(config):\n _, _, compute, _ = construct_clients_from_provider_config(config[\"provider\"])\n\n # For backward compatibility, reuse the VPC if the VM is launched.\n resource = GCPCompute(\n compute,\n config[\"provider\"][\"project_id\"],\n config[\"provider\"][\"availability_zone\"],\n config[\"cluster_name\"],\n )\n node = resource._list_instances(label_filters=None, status_filter=None)\n if len(node) > 0:\n netInterfaces = node[0].get(\"networkInterfaces\", [])\n if len(netInterfaces) > 0:\n vpc_name = netInterfaces[0][\"network\"].split(\"/\")[-1]\n return vpc_name\n\n vpcnets_all = _list_vpcnets(config, compute)\n\n usable_vpc_name = None\n for vpc in vpcnets_all:\n if _check_firewall_rules(vpc[\"name\"], config, compute):\n usable_vpc_name = vpc[\"name\"]\n break\n\n proj_id = config[\"provider\"][\"project_id\"]\n if usable_vpc_name is None:\n logger.info(f\"Creating a default VPC network, {SKYPILOT_VPC_NAME}...\")\n\n # Create a SkyPilot VPC network if it doesn't exist\n vpc_list = _list_vpcnets(config, compute, filter=f\"name={SKYPILOT_VPC_NAME}\")\n if len(vpc_list) == 0:\n body = VPC_TEMPLATE.copy()\n body[\"name\"] = body[\"name\"].format(VPC_NAME=SKYPILOT_VPC_NAME)\n body[\"selfLink\"] = body[\"selfLink\"].format(\n PROJ_ID=proj_id, VPC_NAME=SKYPILOT_VPC_NAME\n )\n _create_vpcnet(config, compute, body)\n\n _create_rules(\n config, compute, FIREWALL_RULES_TEMPLATE, SKYPILOT_VPC_NAME, proj_id\n )\n\n usable_vpc_name = SKYPILOT_VPC_NAME\n logger.info(f\"A VPC network {SKYPILOT_VPC_NAME} created.\")\n\n # Configure user specified rules\n ports = config[\"provider\"].get(\"ports\", [])\n user_rules = []\n for port in ports:\n cluster_name_hash = common_utils.truncate_and_hash_cluster_name(\n config[\"cluster_name\"]\n )\n name = f\"user-ports-{cluster_name_hash}-{port}\"\n user_rules.append(\n {\n \"name\": name,\n \"description\": f\"Allow user-specified port {port} for cluster {config['cluster_name']}\",\n \"network\": \"projects/{PROJ_ID}/global/networks/{VPC_NAME}\",\n \"selfLink\": \"projects/{PROJ_ID}/global/firewalls/\" + name,\n \"direction\": \"INGRESS\",\n \"priority\": 65534,\n \"allowed\": [\n {\n \"IPProtocol\": \"tcp\",\n \"ports\": [str(port)],\n },\n ],\n \"sourceRanges\": [\"0.0.0.0/0\"],\n \"targetTags\": [config[\"cluster_name\"]],\n }\n )\n\n _create_rules(config, compute, user_rules, usable_vpc_name, proj_id)\n\n return usable_vpc_name", "def vpc_configuration(self) -> Optional[pulumi.Input['HostVpcConfigurationArgs']]:\n return pulumi.get(self, \"vpc_configuration\")", "def _get_id(\n vpc_name=None,\n cidr=None,\n tags=None,\n region=None,\n key=None,\n keyid=None,\n profile=None,\n):\n\n if not any((vpc_name, tags, cidr)):\n raise SaltInvocationError(\n \"At least one of the following must be provided: vpc_name, cidr or tags.\"\n )\n\n if vpc_name and not any((cidr, tags)):\n vpc_id = _cache_id(\n vpc_name, region=region, key=key, keyid=keyid, profile=profile\n )\n if vpc_id:\n return vpc_id\n\n vpc_ids = _find_vpcs(\n vpc_name=vpc_name,\n cidr=cidr,\n tags=tags,\n region=region,\n key=key,\n keyid=keyid,\n profile=profile,\n )\n if vpc_ids:\n log.debug(\"Matching VPC: %s\", \" \".join(vpc_ids))\n if len(vpc_ids) == 1:\n vpc_id = vpc_ids[0]\n if vpc_name:\n _cache_id(\n vpc_name,\n vpc_id,\n region=region,\n key=key,\n keyid=keyid,\n profile=profile,\n )\n return vpc_id\n else:\n raise CommandExecutionError(\n \"Found more than one VPC matching the criteria.\"\n )\n else:\n log.info(\"No VPC found.\")\n return None", "def _ensure_default_vpc(client):\n\n default_vpc_filter_expression = [{\n 'Name': 'isDefault',\n 'Values': ['true'],\n }]\n\n res = client.describe_vpcs(Filters=default_vpc_filter_expression)\n\n if res['Vpcs']:\n return res['Vpcs'][0]['VpcId']\n else:\n return client.create_default_vpc()['Vpc']['VpcId']", "def describe(\n vpc_id=None,\n vpc_name=None,\n region=None,\n key=None,\n keyid=None,\n profile=None,\n):\n\n try:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n vpc_id = _find_vpcs(\n vpc_id=vpc_id,\n vpc_name=vpc_name,\n region=region,\n key=key,\n keyid=keyid,\n profile=profile,\n )\n except BotoServerError as err:\n boto_err = __utils__[\"boto.get_error\"](err)\n if boto_err.get(\"aws\", {}).get(\"code\") == \"InvalidVpcID.NotFound\":\n # VPC was not found: handle the error and return None.\n return {\"vpc\": None}\n return {\"error\": boto_err}\n\n if not vpc_id:\n return {\"vpc\": None}\n\n filter_parameters = {\"vpc_ids\": vpc_id}\n\n try:\n vpcs = conn.get_all_vpcs(**filter_parameters)\n except BotoServerError as err:\n return {\"error\": __utils__[\"boto.get_error\"](err)}\n\n if vpcs:\n vpc = vpcs[0] # Found!\n log.debug(\"Found VPC: %s\", vpc.id)\n\n keys = (\n \"id\",\n \"cidr_block\",\n \"is_default\",\n \"state\",\n \"tags\",\n \"dhcp_options_id\",\n \"instance_tenancy\",\n )\n _r = {k: getattr(vpc, k) for k in keys}\n _r.update({\"region\": getattr(vpc, \"region\").name})\n return {\"vpc\": _r}\n else:\n return {\"vpc\": None}", "def vpc_configurations(self) -> Optional[Sequence['outputs.ApplicationVpcConfiguration']]:\n return pulumi.get(self, \"vpc_configurations\")", "def check_vpc(\n vpc_id=None,\n vpc_name=None,\n region=None,\n key=None,\n keyid=None,\n profile=None,\n):\n\n if not _exactly_one((vpc_name, vpc_id)):\n raise SaltInvocationError(\n \"One (but not both) of vpc_id or vpc_name must be provided.\"\n )\n if vpc_name:\n vpc_id = _get_id(\n vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile\n )\n elif not _find_vpcs(\n vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile\n ):\n log.info(\"VPC %s does not exist.\", vpc_id)\n return None\n return vpc_id", "def ec2_current_region() -> Optional[str]:\n cfg = ec2_metadata()\n if cfg is None:\n return None\n return cfg.get(\"region\", None)", "def get_vpc_id(account, region):\n uri = '/networks/aws'\n response = gate_request(uri=uri)\n\n if not response.ok:\n raise SpinnakerVPCNotFound(response.text)\n\n vpcs = response.json()\n\n for vpc in vpcs:\n LOG.debug('VPC Response: %s', vpc)\n if 'name' in vpc and all([vpc['name'] == VPC_NAME, vpc['account'] == account, vpc['region'] == region]):\n LOG.info('Found VPC ID for %s in %s: %s', account, region, vpc['id'])\n vpc_id = vpc['id']\n break\n else:\n LOG.fatal('VPC list: %s', vpcs)\n raise SpinnakerVPCIDNotFound('No VPC available for {0} [{1}].'.format(account, region))\n\n return vpc_id", "def get_vpc_from_env(self, env):\n vpcs = self.get_all_vpcs(filters=[{\"Name\": \"tag:Environment\", 'Values': [env]}])\n if len(vpcs) == 1:\n return vpcs[0]\n else:\n logger.error(\"Multiple envs found: %s\" % (env,))\n raise ValueError", "def _find_vpc_Id(self):\n ec2 = boto3.resource('ec2', region_name=self.infos.region)\n client = boto3.client('ec2', region_name=self.infos.region)\n ids = map(lambda x: x.id, list(ec2.vpcs.filter(Filters=[])))\n for id in ids:\n response = client.describe_vpcs(VpcIds=[id])\n if 'Tags' in response['Vpcs'][0]:\n for tag in response['Vpcs'][0]['Tags']:\n if tag['Key'] == 'Environment' and tag['Value'] == self.infos.environment:\n return id\n raise ValueError('vpc id {} not found for environment'.format(self.infos.environment))", "def get_pv(pv_name, **kwargs):\n # pylint: disable=unused-argument\n # return PVS.get(pv_name, 0)\n return PVS.get(pv_name, \"\")", "def vpc_urn(self) -> Optional[pulumi.Input[str]]:\n return pulumi.get(self, \"vpc_urn\")", "def get_region():\n url = 'http://169.254.169.254/latest/dynamic/instance-identity/document'\n region = None\n try:\n resp = requests.get(url, timeout=0.5)\n resp.raise_for_status()\n region = resp.json()['region']\n except (requests.exceptions.HTTPError,\n requests.exceptions.ReadTimeout,\n KeyError):\n logger.exception('Trying to access {0} failed'.format(url))\n finally:\n return region", "def vpc_settings(self) -> pulumi.Output['outputs.SimpleAdVpcSettings']:\n return pulumi.get(self, \"vpc_settings\")", "def get_vpc_endpoint(self, vpc_id, route_table_id):\n vpc_endpoints = self.get_list('DescribeVpcEndpoints', {},\n [('item', VPCEndpoint)], verb='POST')\n\n for vpc_endpoint in vpc_endpoints:\n if (vpc_endpoint.vpc_id == vpc_id and\n vpc_endpoint.route_tables[0] == route_table_id):\n return vpc_endpoint\n\n return None", "def get_aws_region():\n _name: str = \"get_aws_region()\"\n region: Optional[str] = None\n if 'AWS_DEFAULT_REGION' in os.environ:\n region = os.getenv('AWS_DEFAULT_REGION')\n elif 'AWS_REGION' in os.environ:\n region = os.getenv('AWS_REGION')\n else:\n msg: str = \"AWS_DEFAULT_REGION nor AWS_REGION defined in the environment.\"\n _logger.error(\"%s: %s\", _name, msg)\n raise RuntimeError(msg)\n\n return region", "def try_get_creds(cloud):\n if not path.isfile(cred_path):\n return None\n\n existing_creds = yaml.safe_load(open(cred_path))\n if 'credentials' not in existing_creds:\n return None\n\n if cloud not in existing_creds['credentials'].keys():\n return None\n\n if len(existing_creds['credentials'][cloud].keys()) == 0:\n return None\n\n if 'default-credential' in existing_creds['credentials'][cloud]:\n return existing_creds['credentials'][cloud]['default-credential']\n\n # XXX we should really prompt to select because this is non-deterministic\n for k, v in existing_creds['credentials'][cloud].items():\n if 'default-region' in k:\n app.current_region = v\n else:\n return k", "def getvpcs(show):\n vpclist=[]\n \n try:\n vpcs=ec2.describe_vpcs()\n except botocore.exceptions.ClientError as e:\n coloredtext(\"There was an error while getting vpc data: \\n\\n\\n\")\n print(e)\n for vpc in vpcs['Vpcs']:\n name=vpc['VpcId']\n cidr=vpc['CidrBlock']\n if show:\n print(\"VPC Id: \"+name+\" CIDR: \"+cidr)\n vpclist.append({ \"name\":name})\n return vpclist" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find role for AWS ECS instances.
def _get_instance_role(self) -> str: # if instance role is set in config, return it if self.cfg.aws.instance_role: logging.debug(f'Instance role provided from config: {self.cfg.aws.instance_role}') return self.cfg.aws.instance_role # check if ecsInstanceRole is present in the account and return it, # if it is # instance profile and role, both named ecsInstanceRole must exist DFLT_INSTANCE_ROLE_NAME = 'ecsInstanceRole' instance_profile = self.iam.InstanceProfile(DFLT_INSTANCE_ROLE_NAME) try: role_names = [i.name for i in instance_profile.roles] if DFLT_INSTANCE_ROLE_NAME in role_names: logging.debug(f'Using {DFLT_INSTANCE_ROLE_NAME} present in the account') return DFLT_INSTANCE_ROLE_NAME except self.iam.meta.client.exceptions.NoSuchEntityException: # an exception means that ecsInstanceRole is not defined in the # account pass # otherwise return en empty string, which cloudformation template # will interpret to create the instance role logging.debug('Instance role will be created by cloudformation') return ''
[ "def find_role(cls, keyword):\n return _CompilerRole.find(keyword)", "def cmd_role_get(self, args):\n role_id = args[0]\n self._get_obj(role_id, 'role')", "def cloudwatch_logs_role_arn(self) -> str:\n return pulumi.get(self, \"cloudwatch_logs_role_arn\")", "def _get_elastic_ip_node_():\n all_instances = _ec2_instances_()\n for instance in all_instances:\n if ip_address(instance) == env.elastic_ip:\n return instance\n return None", "def validate_role(context, param, value):\n role = context.obj.api.role_by_name(value)\n if role:\n return role\n else:\n raise click.BadParameter(\"\\\"%s\\\" was not found\" % value)", "def isRole(\n role, shardName, ipAddress, numOfShards=3, numOfRetries=1, sleepFor=3, port=8181\n):\n ip = getClusterRoles(\n shardName, numOfShards, numOfRetries, sleepFor, port, ipAddress\n )\n print(ip)\n if ip[ipAddress] == role:\n return True\n return False", "def _get_role_arn(self):\n if self.stack.cloudformation_service_role:\n return {\"RoleARN\": self.stack.cloudformation_service_role}\n else:\n return {}", "def _get_batch_service_role(self):\n # if batch service role is set in config, return it\n if self.cfg.aws.batch_service_role:\n logging.debug(f'Batch service role provided from config: {self.cfg.aws.batch_service_role}')\n return self.cfg.aws.batch_service_role\n\n # check if ecsInstanceRole is present in the account and return it,\n # if it is\n # instance profile and role, both named ecsInstanceRole must exist\n DFLT_BATCH_SERVICE_ROLE_NAME = 'AWSBatchServiceRole'\n role = self.iam.Role(DFLT_BATCH_SERVICE_ROLE_NAME)\n try:\n role.arn\n logging.debug(f'Using {role.name} present in the account')\n return role.arn\n except self.iam.meta.client.exceptions.NoSuchEntityException:\n # an exception means that the role is not defined in the account\n pass\n\n # otherwise return en empty string, which cloudformation template\n # will interpret to create the instance role\n logging.debug('Batch service role will be created by cloudformation')\n return ''", "def get_role(obj, role_name):\n for role in obj.roles:\n if role.name == role_name:\n return role\n return None", "def get_nodes_using_role(ctx, target_role):\n\n # Nodes containing a service of the specified role\n nodes_of_interest = []\n\n # Prepare a modified version of cluster.remotes with ceph-deploy-ized names\n modified_remotes = {}\n ceph_deploy_mapped = dict()\n for _remote, roles_for_host in ctx.cluster.remotes.items():\n modified_remotes[_remote] = []\n for svc_id in roles_for_host:\n if svc_id.startswith(\"{0}.\".format(target_role)):\n fqdn = str(_remote).split('@')[-1]\n nodename = str(str(_remote).split('.')[0]).split('@')[1]\n if target_role == 'mon':\n nodes_of_interest.append(fqdn)\n else:\n nodes_of_interest.append(nodename)\n mapped_role = \"{0}.{1}\".format(target_role, nodename)\n modified_remotes[_remote].append(mapped_role)\n # keep dict of mapped role for later use by tasks\n # eg. mon.a => mon.node1\n ceph_deploy_mapped[svc_id] = mapped_role\n else:\n modified_remotes[_remote].append(svc_id)\n\n ctx.cluster.remotes = modified_remotes\n # since the function is called multiple times for target roles\n # append new mapped roles\n if not hasattr(ctx.cluster, 'mapped_role'):\n ctx.cluster.mapped_role = ceph_deploy_mapped\n else:\n ctx.cluster.mapped_role.update(ceph_deploy_mapped)\n log.info(\"New mapped_role={mr}\".format(mr=ctx.cluster.mapped_role))\n return nodes_of_interest", "def get_role(cls, name):\n return cls.query.filter_by(name=name).first()", "def get_role_name(self):\n try:\n return self.tags['Role']\n except KeyError:\n return None", "def roles(self) -> Optional[Sequence['outputs.CloudServiceRoleProfilePropertiesResponse']]:\n return pulumi.get(self, \"roles\")", "def get_role(self, role):\r\n uri = \"OS-KSADM/roles/%s\" % utils.get_id(role)\r\n resp, resp_body = self.method_get(uri)\r\n role = Role(self, resp_body.get(\"role\"))\r\n return role", "def getRoleEntitlements(self):\n lst = []\n rhns = self.redhat()\n entitlements = rhns.find('3.*.1')\n for ent in entitlements:\n oid = ent[0]\n root = oid.rtrim(1)\n ext = rhns.branch(root)\n lst.append(Role(ext))\n return lst", "async def searchin(self, ctx, *args):\n\t\tif len(args)<2:\n\t\t\tmessage = await ctx.send('Invalid syntax for the command.')\n\t\t\tself.bot.set_answer(ctx.message.id, message)\n\t\t\treturn\n\n\t\trole = ' '.join(args[:-1]).lower()\n\t\tname = args[-1].lower()\n\n\t\tfor r in ctx.guild.roles:\n\t\t\tif r.name.lower()==role:\n\t\t\t\trole = r\n\t\t\t\tbreak\n\t\telse:\n\t\t\tmessage = await ctx.send(\"Error: I haven't found the role on this server.\")\n\t\t\tself.bot.set_answer(ctx.message.id, message)\n\t\t\treturn\n\n\t\tmembers = []\n\t\tfor m in ctx.guild.members:\n\t\t\tif role not in m.roles:\n\t\t\t\tcontinue\n\t\t\tif m.nick is not None and name in m.nick.lower() or name in m.name.lower():\n\t\t\t\tmembers.append(f\"{self.get_emoji(m.status.value)} {m.display_name}\")\n\n\t\tembed = discord.Embed()\n\t\tembed.title = f\"Members with the role `{role}`:\"\n\t\tembed.description = \"\\n\".join(members)\n\t\tmessage = await ctx.send(embed=embed)\n\t\tself.bot.set_answer(ctx.message.id, message)", "def role(self, name):\n for r, n in itertools.chain(self._role_to_prop.items(), self._ref_role_to_prop.items()):\n if n == name:\n return r\n else:\n return -1", "def _get_spot_fleet_role(self):\n if self.cfg.aws.spot_fleet_role:\n role = self.cfg.aws.spot_fleet_role\n logging.debug(f'Using Spot Fleet role provided from config: {role}')\n return role\n else:\n logging.debug('Spot Fleet role will be created by cloudformation')\n return ''", "def iam_role_id(self) -> str:\n return pulumi.get(self, \"iam_role_id\")" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find AWS Batch service role.
def _get_batch_service_role(self): # if batch service role is set in config, return it if self.cfg.aws.batch_service_role: logging.debug(f'Batch service role provided from config: {self.cfg.aws.batch_service_role}') return self.cfg.aws.batch_service_role # check if ecsInstanceRole is present in the account and return it, # if it is # instance profile and role, both named ecsInstanceRole must exist DFLT_BATCH_SERVICE_ROLE_NAME = 'AWSBatchServiceRole' role = self.iam.Role(DFLT_BATCH_SERVICE_ROLE_NAME) try: role.arn logging.debug(f'Using {role.name} present in the account') return role.arn except self.iam.meta.client.exceptions.NoSuchEntityException: # an exception means that the role is not defined in the account pass # otherwise return en empty string, which cloudformation template # will interpret to create the instance role logging.debug('Batch service role will be created by cloudformation') return ''
[ "def _get_job_role(self):\n if self.cfg.aws.job_role:\n job_role = self.cfg.aws.job_role\n logging.debug(f'Using Batch job role provided from config: {job_role}')\n return job_role\n else:\n logging.debug('Batch job role will be created by cloudformation')\n return ''", "def find_role(cls, keyword):\n return _CompilerRole.find(keyword)", "def _get_role_arn(self):\n if self.stack.cloudformation_service_role:\n return {\"RoleARN\": self.stack.cloudformation_service_role}\n else:\n return {}", "def get_role(obj, role_name):\n for role in obj.roles:\n if role.name == role_name:\n return role\n return None", "def validate_role(context, param, value):\n role = context.obj.api.role_by_name(value)\n if role:\n return role\n else:\n raise click.BadParameter(\"\\\"%s\\\" was not found\" % value)", "def cmd_role_get(self, args):\n role_id = args[0]\n self._get_obj(role_id, 'role')", "def get_role(self, role):\r\n uri = \"OS-KSADM/roles/%s\" % utils.get_id(role)\r\n resp, resp_body = self.method_get(uri)\r\n role = Role(self, resp_body.get(\"role\"))\r\n return role", "def lookup_role_arn(roleName):\n lastSlash = roleName.rfind(\"/\")\n if lastSlash >= 0:\n prefix = roleName[:lastSlash+1]\n baseName = roleName[lastSlash+1:]\n else:\n prefix = \"/\"\n baseName = roleName\n for page in iam_client.get_paginator('list_roles').paginate(PathPrefix=prefix):\n for role in page['Roles']:\n if baseName == role['RoleName']:\n return role['Arn']\n raise Exception(f'Unable to find role with name \"{roleName}\"')", "def get_role_name(self):\n try:\n return self.tags['Role']\n except KeyError:\n return None", "def isRole(\n role, shardName, ipAddress, numOfShards=3, numOfRetries=1, sleepFor=3, port=8181\n):\n ip = getClusterRoles(\n shardName, numOfShards, numOfRetries, sleepFor, port, ipAddress\n )\n print(ip)\n if ip[ipAddress] == role:\n return True\n return False", "def _get_instance_role(self) -> str:\n\n # if instance role is set in config, return it\n if self.cfg.aws.instance_role:\n logging.debug(f'Instance role provided from config: {self.cfg.aws.instance_role}')\n return self.cfg.aws.instance_role\n\n # check if ecsInstanceRole is present in the account and return it,\n # if it is\n # instance profile and role, both named ecsInstanceRole must exist\n DFLT_INSTANCE_ROLE_NAME = 'ecsInstanceRole'\n instance_profile = self.iam.InstanceProfile(DFLT_INSTANCE_ROLE_NAME)\n try:\n role_names = [i.name for i in instance_profile.roles]\n if DFLT_INSTANCE_ROLE_NAME in role_names:\n logging.debug(f'Using {DFLT_INSTANCE_ROLE_NAME} present in the account')\n return DFLT_INSTANCE_ROLE_NAME\n except self.iam.meta.client.exceptions.NoSuchEntityException:\n # an exception means that ecsInstanceRole is not defined in the\n # account\n pass\n\n # otherwise return en empty string, which cloudformation template\n # will interpret to create the instance role\n logging.debug('Instance role will be created by cloudformation')\n return ''", "def _get_spot_fleet_role(self):\n if self.cfg.aws.spot_fleet_role:\n role = self.cfg.aws.spot_fleet_role\n logging.debug(f'Using Spot Fleet role provided from config: {role}')\n return role\n else:\n logging.debug('Spot Fleet role will be created by cloudformation')\n return ''", "def retrieve_role(role_name):\n return RolesManager.retrieve_role(role_name)", "def role_profile(self) -> Optional['outputs.CloudServiceRoleProfileResponse']:\n return pulumi.get(self, \"role_profile\")", "def get_account_id_from_role(role):\n acct_id_re = re.compile(r'::(\\d+):')\n acct_ids = re.search(acct_id_re, role)\n if acct_ids.groups():\n for ids in acct_ids.groups():\n if len(ids) == 12:\n return ids\n else:\n raise Exception('Missing or malformed account ID!')", "def role_name(self) -> pulumi.Output[Optional[str]]:\n return pulumi.get(self, \"role_name\")", "def get_role(cls, name):\n return cls.query.filter_by(name=name).first()", "def service_roles(self):\n return self._service_roles", "def role(self, name):\n for r, n in itertools.chain(self._role_to_prop.items(), self._ref_role_to_prop.items()):\n if n == name:\n return r\n else:\n return -1" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find AWS Batch job role.
def _get_job_role(self): if self.cfg.aws.job_role: job_role = self.cfg.aws.job_role logging.debug(f'Using Batch job role provided from config: {job_role}') return job_role else: logging.debug('Batch job role will be created by cloudformation') return ''
[ "def _get_batch_service_role(self):\n # if batch service role is set in config, return it\n if self.cfg.aws.batch_service_role:\n logging.debug(f'Batch service role provided from config: {self.cfg.aws.batch_service_role}')\n return self.cfg.aws.batch_service_role\n\n # check if ecsInstanceRole is present in the account and return it,\n # if it is\n # instance profile and role, both named ecsInstanceRole must exist\n DFLT_BATCH_SERVICE_ROLE_NAME = 'AWSBatchServiceRole'\n role = self.iam.Role(DFLT_BATCH_SERVICE_ROLE_NAME)\n try:\n role.arn\n logging.debug(f'Using {role.name} present in the account')\n return role.arn\n except self.iam.meta.client.exceptions.NoSuchEntityException:\n # an exception means that the role is not defined in the account\n pass\n\n # otherwise return en empty string, which cloudformation template\n # will interpret to create the instance role\n logging.debug('Batch service role will be created by cloudformation')\n return ''", "def find_role(cls, keyword):\n return _CompilerRole.find(keyword)", "def get_role(obj, role_name):\n for role in obj.roles:\n if role.name == role_name:\n return role\n return None", "def get_role_name(self):\n try:\n return self.tags['Role']\n except KeyError:\n return None", "def lookup_role_arn(roleName):\n lastSlash = roleName.rfind(\"/\")\n if lastSlash >= 0:\n prefix = roleName[:lastSlash+1]\n baseName = roleName[lastSlash+1:]\n else:\n prefix = \"/\"\n baseName = roleName\n for page in iam_client.get_paginator('list_roles').paginate(PathPrefix=prefix):\n for role in page['Roles']:\n if baseName == role['RoleName']:\n return role['Arn']\n raise Exception(f'Unable to find role with name \"{roleName}\"')", "def validate_role(context, param, value):\n role = context.obj.api.role_by_name(value)\n if role:\n return role\n else:\n raise click.BadParameter(\"\\\"%s\\\" was not found\" % value)", "def cmd_role_get(self, args):\n role_id = args[0]\n self._get_obj(role_id, 'role')", "def role_name(self) -> pulumi.Output[Optional[str]]:\n return pulumi.get(self, \"role_name\")", "def _get_role_arn(self):\n if self.stack.cloudformation_service_role:\n return {\"RoleARN\": self.stack.cloudformation_service_role}\n else:\n return {}", "def validate_role(name_or_arn):\n paginator = boto3.client('iam').get_paginator('list_roles')\n for page in paginator.paginate():\n for role in page['Roles']:\n if (name_or_arn == role['Arn']) or (name_or_arn == role['RoleName']):\n return role['Arn']\n exit_if_none(None, f\"invalid role name/ARN: {name_or_arn}\")", "def retrieve_role(role_name):\n return RolesManager.retrieve_role(role_name)", "def role(self, name):\n for r, n in itertools.chain(self._role_to_prop.items(), self._ref_role_to_prop.items()):\n if n == name:\n return r\n else:\n return -1", "def get_role(cls, name):\n return cls.query.filter_by(name=name).first()", "def _get_role(role_name):\n known_roles = kv().get('charm.azure.roles', {})\n if role_name in known_roles:\n return known_roles[role_name]\n sub_id = kv().get('charm.azure.sub-id')\n role_file = Path('files/roles/{}.json'.format(role_name))\n role_data = json.loads(role_file.read_text())\n role_fullname = role_data['Name'].format(sub_id)\n scope = role_data['AssignableScopes'][0].format(sub_id)\n role_data['Name'] = role_fullname\n role_data['AssignableScopes'][0] = scope\n try:\n log('Ensuring role {}', role_fullname)\n _azure('role', 'definition', 'create',\n '--role-definition', json.dumps(role_data))\n except AlreadyExistsAzureError:\n pass\n known_roles[role_name] = role_fullname\n kv().set('charm.azure.roles', known_roles)\n return role_fullname", "def iam_role_id(self) -> str:\n return pulumi.get(self, \"iam_role_id\")", "def _get_instance_role(self) -> str:\n\n # if instance role is set in config, return it\n if self.cfg.aws.instance_role:\n logging.debug(f'Instance role provided from config: {self.cfg.aws.instance_role}')\n return self.cfg.aws.instance_role\n\n # check if ecsInstanceRole is present in the account and return it,\n # if it is\n # instance profile and role, both named ecsInstanceRole must exist\n DFLT_INSTANCE_ROLE_NAME = 'ecsInstanceRole'\n instance_profile = self.iam.InstanceProfile(DFLT_INSTANCE_ROLE_NAME)\n try:\n role_names = [i.name for i in instance_profile.roles]\n if DFLT_INSTANCE_ROLE_NAME in role_names:\n logging.debug(f'Using {DFLT_INSTANCE_ROLE_NAME} present in the account')\n return DFLT_INSTANCE_ROLE_NAME\n except self.iam.meta.client.exceptions.NoSuchEntityException:\n # an exception means that ecsInstanceRole is not defined in the\n # account\n pass\n\n # otherwise return en empty string, which cloudformation template\n # will interpret to create the instance role\n logging.debug('Instance role will be created by cloudformation')\n return ''", "def _find_backupjob(cs, backupjob_id):\n return utils.find_resource(cs.backupjobs, backupjob_id)", "def role(self):\n if self.groups.filter(name=MEMBER_ROLES[\"STAFF\"][0]).exists():\n return self.groups.get(name=MEMBER_ROLES[\"STAFF\"][0])\n elif self.groups.filter(name=MEMBER_ROLES[\"STUDENT\"][0]).exists():\n return self.groups.get(name=MEMBER_ROLES[\"STUDENT\"][0])\n else:\n return None", "def ledger_role_name(self) -> str:\n return pulumi.get(self, \"ledger_role_name\")" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find AWS EC2 Spot Fleet role.
def _get_spot_fleet_role(self): if self.cfg.aws.spot_fleet_role: role = self.cfg.aws.spot_fleet_role logging.debug(f'Using Spot Fleet role provided from config: {role}') return role else: logging.debug('Spot Fleet role will be created by cloudformation') return ''
[ "def find_role(cls, keyword):\n return _CompilerRole.find(keyword)", "def _get_instance_role(self) -> str:\n\n # if instance role is set in config, return it\n if self.cfg.aws.instance_role:\n logging.debug(f'Instance role provided from config: {self.cfg.aws.instance_role}')\n return self.cfg.aws.instance_role\n\n # check if ecsInstanceRole is present in the account and return it,\n # if it is\n # instance profile and role, both named ecsInstanceRole must exist\n DFLT_INSTANCE_ROLE_NAME = 'ecsInstanceRole'\n instance_profile = self.iam.InstanceProfile(DFLT_INSTANCE_ROLE_NAME)\n try:\n role_names = [i.name for i in instance_profile.roles]\n if DFLT_INSTANCE_ROLE_NAME in role_names:\n logging.debug(f'Using {DFLT_INSTANCE_ROLE_NAME} present in the account')\n return DFLT_INSTANCE_ROLE_NAME\n except self.iam.meta.client.exceptions.NoSuchEntityException:\n # an exception means that ecsInstanceRole is not defined in the\n # account\n pass\n\n # otherwise return en empty string, which cloudformation template\n # will interpret to create the instance role\n logging.debug('Instance role will be created by cloudformation')\n return ''", "def get_role(obj, role_name):\n for role in obj.roles:\n if role.name == role_name:\n return role\n return None", "def validate_role(context, param, value):\n role = context.obj.api.role_by_name(value)\n if role:\n return role\n else:\n raise click.BadParameter(\"\\\"%s\\\" was not found\" % value)", "def get_role_name(self):\n try:\n return self.tags['Role']\n except KeyError:\n return None", "async def stoprole(self, ctx):\r\n\t\trole = self.settings.getServerStat(ctx.message.guild, \"RequiredStopRole\")\r\n\t\tif role == None or role == \"\":\r\n\t\t\tmsg = '**Only Admins** can use stop.'\r\n\t\t\tawait ctx.message.channel.send(msg)\r\n\t\telse:\r\n\t\t\t# Role is set - let's get its name\r\n\t\t\tfound = False\r\n\t\t\tfor arole in ctx.message.guild.roles:\r\n\t\t\t\tif str(arole.id) == str(role):\r\n\t\t\t\t\tfound = True\r\n\t\t\t\t\tvowels = \"aeiou\"\r\n\t\t\t\t\tif arole.name[:1].lower() in vowels:\r\n\t\t\t\t\t\tmsg = 'You need to be an **{}** to use `$stop`.'.format(arole.name)\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tmsg = 'You need to be a **{}** to use `$stop`.'.format(arole.name)\r\n\t\t\t\t\t\r\n\t\t\tif not found:\r\n\t\t\t\tmsg = 'There is no role that matches id: `{}` - consider updating this setting.'.format(role)\r\n\t\t\tmsg = Utils.suppressed(ctx,msg)\r\n\t\t\tawait ctx.message.channel.send(msg)", "def role(self):\n if self.groups.filter(name=MEMBER_ROLES[\"STAFF\"][0]).exists():\n return self.groups.get(name=MEMBER_ROLES[\"STAFF\"][0])\n elif self.groups.filter(name=MEMBER_ROLES[\"STUDENT\"][0]).exists():\n return self.groups.get(name=MEMBER_ROLES[\"STUDENT\"][0])\n else:\n return None", "def get_role2(self):\r\n \r\n return self.obj_dict['role2']", "def get_role(cls, name):\n return cls.query.filter_by(name=name).first()", "def role(self):\n if self.case_status == 'adoption':\n return ''\n return self.user_role", "def role(self) -> 'PodRoleType':\n return self.args.pod_role", "def _get_role_arn(self):\n if self.stack.cloudformation_service_role:\n return {\"RoleARN\": self.stack.cloudformation_service_role}\n else:\n return {}", "def get_by_name(self, name: str) -> tp.Optional[RoleType]:\n pass", "def get_user_role():\n if 'roletype' in session:\n return session['roletype']\n return None", "def role_name(self) -> pulumi.Output[Optional[str]]:\n return pulumi.get(self, \"role_name\")", "def role_profile(self) -> Optional['outputs.CloudServiceRoleProfileResponse']:\n return pulumi.get(self, \"role_profile\")", "def _get_batch_service_role(self):\n # if batch service role is set in config, return it\n if self.cfg.aws.batch_service_role:\n logging.debug(f'Batch service role provided from config: {self.cfg.aws.batch_service_role}')\n return self.cfg.aws.batch_service_role\n\n # check if ecsInstanceRole is present in the account and return it,\n # if it is\n # instance profile and role, both named ecsInstanceRole must exist\n DFLT_BATCH_SERVICE_ROLE_NAME = 'AWSBatchServiceRole'\n role = self.iam.Role(DFLT_BATCH_SERVICE_ROLE_NAME)\n try:\n role.arn\n logging.debug(f'Using {role.name} present in the account')\n return role.arn\n except self.iam.meta.client.exceptions.NoSuchEntityException:\n # an exception means that the role is not defined in the account\n pass\n\n # otherwise return en empty string, which cloudformation template\n # will interpret to create the instance role\n logging.debug('Batch service role will be created by cloudformation')\n return ''", "def role_name(self):\n if self.groups.filter(name=MEMBER_ROLES[\"STAFF\"][0]).exists():\n return MEMBER_ROLES[\"STAFF\"][1]\n elif self.groups.filter(name=MEMBER_ROLES[\"STUDENT\"][0]).exists():\n return MEMBER_ROLES[\"STUDENT\"][1]\n else:\n return None", "def role(self, name):\n for r, n in itertools.chain(self._role_to_prop.items(), self._ref_role_to_prop.items()):\n if n == name:\n return r\n else:\n return -1" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a tuple of BLAST database basename, path (if applicable), and label suitable for job name. Gets user provided database from configuration. For custom database finds basename from full path, and provides correct path for db retrieval. For standard database the basename is the only value provided by the user, and the path name returned is empty. Example cfg.blast.db = pdb_nt > 'pdb_nt', 'None', 'pdb_nt'
def _get_blastdb_info(self) -> Tuple[str, str, str]: db = self.cfg.blast.db db_path = 'None' if db.startswith('s3://'): #TODO: support tar.gz database bname, key = parse_bucket_name_key(db) if not self.dry_run: try: bucket = self.s3.Bucket(bname) if len(list(bucket.objects.filter(Prefix=key, Delimiter='/'))) == 0: raise RuntimeError except: raise UserReportError(returncode=BLASTDB_ERROR, message=f'{db} is not a valid BLAST database') db_path = os.path.dirname(db) db = os.path.basename(db) elif db.startswith('gs://'): raise UserReportError(returncode=BLASTDB_ERROR, message=f'User database should be in the AWS S3 bucket') return db, db_path, sanitize_aws_batch_job_name(db)
[ "def get_database_uri(self, label: str = \"default\") -> str:\n return self.config[\"databases\"][label]", "def guess_database(args):\n return _guess_database_file(args.gtf, args.database)", "def get_db_name(self):\n return self.config.get(\"db\", \"name\")", "def _getDBName(self):\n return getConfiguration().getDatabaseFactory(self._path).getName()", "def get_database_name(database):\n return _db_names[database]", "def get_ref_db_name(db_conn, experiment_id):\n get_ref_db_query = \"SELECT used_plaza_database FROM experiments WHERE experiment_id={experiment_id}\".format(experiment_id=str(experiment_id))\n # Execute query\n cursor = db_conn.cursor()\n cursor.execute(get_ref_db_query)\n ref_db_name = cursor.fetchall()[0][0]\n return ref_db_name", "def dbPath(self):\n return self._parameters['DB_PATH']", "def get_label_db_path(self, stage):\n raise NotImplementedError('Please implement me')", "def __discover_database_path__(self):\n for path in MIXXX_DATABASE_PATHS:\n if os.path.isfile(path):\n return path\n raise MixxxDatabaseError('Mixxx database not found')", "def _get_frm_path(dbtablename, datadir, new_db=None):\n\n # Form the path to the .frm file. There are two possibilities:\n # a) the user has specified a full path\n # b) the user has specified a db:table combination (with/without .frm)\n\n path_parts = os.path.split(dbtablename)\n if ':' in dbtablename and len(path_parts[0]) == 0:\n # here we use the datadir to form the path\n path_parts = dbtablename.split(\":\")\n db = path_parts[0]\n table = path_parts[1]\n if datadir is None:\n datadir = \"\"\n frm_path = os.path.join(datadir, table)\n elif len(path_parts) == 2 and \":\" in path_parts[1]:\n db, table = path_parts[1].split(\":\", 1)\n frm_path = os.path.join(path_parts[0], table)\n else:\n # here we decipher the last folder as the database name\n frm_path = dbtablename\n db = None\n if len(path_parts) == 2:\n path, table = path_parts\n if path == '':\n db = None\n path = None\n elif len(path_parts) == 1:\n db = None\n path = None\n table = dbtablename\n if db is None and path:\n # find database from path\n folders = path.split(os.path.sep)\n if len(folders):\n db = folders[len(folders) - 1]\n\n # Check that the frm_path name has .frm.\n if not frm_path.lower().endswith(\".frm\"):\n frm_path += \".frm\"\n\n # Strip the .frm from table\n if table.lower().endswith('.frm'):\n table = os.path.splitext(table)[0]\n\n if not os.access(frm_path, os.R_OK):\n raise UtilError(\"Cannot read .frm file from %s.\" % frm_path)\n\n if new_db:\n db = new_db\n return (db, table, frm_path)", "def get_db_name(self):\n return self.dbname", "def get_db_path(ilmtconfig):\n md5name = generate_md5_name(ilmtconfig.instance_id)\n dbname = '{0}{1}{2}'.format(CPX_ILMT_FILE_PREFIX, md5name,\n CPX_ILMT_DB_EXT)\n return os.path.join(ilmtconfig.location, dbname)", "def get_dbdir(ibs):\n #return join(ibs.workdir, ibs.dbname)\n return ibs.dbdir", "def read_database_name():\n with open(\"model/database_name.json\") as json_file:\n database = json.load(json_file)\n return database[\"DATABASE\"]", "def get_database_filepath():\n\tfilepath = os.path.dirname(os.path.realpath(__file__))\n\tdatabase_filepath = \"\"\n\tif platform.system() == \"Windows\":\n\t\tdatabase_filepath = filepath.split('apps\\\\backend')[0] + \"data\\\\\"\n\telse:\n\t\tdatabase_filepath = filepath.split('apps/backend')[0] + \"data/\"\n\treturn database_filepath", "def get_db_info_from_uri(uri):\n parsed_uri = urllib.parse.urlparse(uri)\n if parsed_uri.scheme == \"databricks\":\n profile_tokens = parsed_uri.netloc.split(\":\")\n parsed_scope = profile_tokens[0]\n if len(profile_tokens) == 1:\n parsed_key_prefix = None\n elif len(profile_tokens) == 2:\n parsed_key_prefix = profile_tokens[1]\n else:\n # parse the content before the first colon as the profile.\n parsed_key_prefix = \":\".join(profile_tokens[1:])\n validate_db_scope_prefix_info(parsed_scope, parsed_key_prefix)\n return parsed_scope, parsed_key_prefix\n return None, None", "def _getRootDBName(self):\n return getConfiguration().getDatabaseFactory('/').getName()", "def _get_db_url(self):\n return os.path.join(self.groc_dir, self.db_name)", "def get_bin_path(self, loqusdb_id=None):\n if loqusdb_id is None or loqusdb_id == \"\":\n return self.default_setting().get(BINARY_PATH)\n try:\n return self.search_setting(loqusdb_id).get(BINARY_PATH)\n except AttributeError:\n raise ConfigError(\"LoqusDB id not found: {}\".format(loqusdb_id))" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a list of batch job ids
def get_job_ids(self) -> List[str]: # we can only query for job ids by jobs states which can change # between calls, so order in which job states are processed matters ids = defaultdict(int) logging.debug(f'Retrieving job IDs from job queue {self.job_queue_name}') for status in AWS_BATCH_JOB_STATES: batch_of_jobs = self.batch.list_jobs(jobQueue=self.job_queue_name, jobStatus=status) for j in batch_of_jobs['jobSummaryList']: ids[j['jobId']] = 1 while 'nextToken' in batch_of_jobs: batch_of_jobs = self.batch.list_jobs(jobQueue=self.job_queue_name, jobStatus=status, nextToken=batch_of_jobs['nextToken']) for j in batch_of_jobs['jobSummaryList']: ids[j['jobId']] = 1 logging.debug(f'Retrieved {len(ids.keys())} job IDs') return list(ids.keys())
[ "def job_ids(self):\n return [elem[\"id\"] for elem in self.all()]", "def get_job_ids(self, offset=0, length=-1):\n start = offset\n if length >= 0:\n end = offset + (length - 1)\n else:\n end = length\n return [as_text(job_id) for job_id in\n self.connection.lrange(self.key, start, end)]", "def get_ids(request, job_name):\n\ttry:\n\t\tjob = Job.objects.get(name=job_name)\n\t\tids = [task.task_id for task in job.task_set.all()]\n\t\treturn StreamingHttpResponse(json.dumps(ids))\n\texcept Job.DoesNotExist:\n\t\treturn Http404", "def _get_current_job_ids():\n jobs = [int(x) for x in kvs.current_jobs()]\n\n return sorted(jobs)", "def getJobIDs(workflowIDs = []):\n return Aux.getJobIDs(workflowIDs)", "def get_just_ids(jobs, id_index):\n ids = [job[id_index] for job in jobs]\n ids = list(set(ids))\n return ids", "def get_all_ids(path, id_column):\n all_jobs = get_all_jobs(path)\n all_ids = get_just_ids(all_jobs, id_column)\n return all_ids", "def get_child_ids(self, job_specifier, project=None, status=None):\n if project is None:\n project = self._path\n self.update()\n id_master = self.get_job_id(project=project, job_specifier=job_specifier)\n if id_master is None:\n return []\n else:\n df_tmp = self._job_table[self._job_table.id == id_master]\n working_directory = (df_tmp[\"project\"] + df_tmp[\"job\"] + \"_hdf5/\").values[0]\n if status is not None:\n id_lst = self._job_table[\n (self._job_table.project == working_directory)\n & (self._job_table.status == status)\n ].id.values\n else:\n id_lst = self._job_table[\n (self._job_table.project == working_directory)\n ].id.values\n return sorted(id_lst)", "def getActiveJobs():\n ge = GridEngine()\n # require all array job tasks\n so = ge.qstat(['-u', '*', '-j', '*'])\n # job ids are collected as jobid.taskid - for non array\n # jobs jobid.1\n jobids = [ ]\n lines = so.split('\\n')\n jobid = ''\n taskid = ''\n for line in lines:\n if \"job_number:\" in line:\n pair = line.split()\n if len(pair) == 2:\n jobid = pair[1]\n if \"job-array tasks: \" in line:\n triple = line.split()\n if len(triple) == 3:\n taskid = triple[2]\n if \"scheduling info:\" in line:\n # this is the last entry (even when turned off)\n if jobid != '':\n if taskid == '':\n jobids.append(jobid)\n else:\n # 1-100:1 for example\n for task in expandTaskIds(taskid):\n jobids.append(jobid + \".\" + str(task))\n jobid = ''\n taskid = ''\n\n return jobids", "def get_ids():", "def getJobs(self, type=\"list\"):\n if type == \"list\":\n return self.jobs\n elif type == \"id\":\n jobIDs = []\n\n for job in self.jobs:\n jobIDs.append(job[\"id\"])\n\n return jobIDs\n else:\n print(\"Unknown type: %s\" % type)\n\n return", "def get_pool_ids(self, job_ids):\n return [self.jobs[id].pool_id for id in job_ids]", "def getIssuedLocalJobIDs(self) -> List[int]:\n local_ids: List[int] = self.localBatch.getIssuedBatchJobIDs()\n return local_ids", "def jobs(self):\n with TRN:\n sql = \"\"\"SELECT job_id FROM qiita.analysis_job\n WHERE analysis_id = %s\"\"\".format(self._table)\n TRN.add(sql, [self._id])\n return TRN.execute_fetchflatten()", "def batch_ids(self, querystring, num=10):\n \n for batch in self.batchquery(querystring, num):\n yield [doc['id'] for doc in batch]", "def get_checkpoint_ids(self, job_id):\n return [elem[\"id\"] for elem in self.get_checkpoints(job_id=job_id)[\"history\"]]", "def get_vertex_ids(self, job_id):\n return [elem[\"id\"] for elem in self.get(job_id)[\"vertices\"]]", "def jobs_get(self):\n try:\n cart = self.cart\n jobs = []\n\n c = get_cursor()\n c.execute(\"\"\" select job_id from job\n where job.cart_id = %s\"\"\",\n (self.cart['cart_id'],))\n job_ids = c.fetchall()\n\n for job_id in job_ids:\n jobs.append(Job.Job(job_id=job_id))\n return jobs\n except CartInvalid as e:\n raise CartInvalid(e)\n except Exception as e:\n import traceback\n traceback.print_exc()\n print e.__class__.__name__ + \": \" + str(e)\n raise DbError(\"Internal error\")", "def get_ids(self):\n return self.multiengine.get_ids()" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save batch job ids in a metadata file in S3
def upload_job_ids(self) -> None: bucket_name, key = parse_bucket_name_key(f'{self.results_bucket}/{ELB_METADATA_DIR}/{ELB_AWS_JOB_IDS}') bucket = self.s3.Bucket(bucket_name) bucket.put_object(Body=json.dumps(self.job_ids).encode(), Key=key)
[ "def put_s3_batch(data, bucket, prefix):\n # Pickle data\n data = pickle.dumps(data)\n\n # s3 setup\n s3 = boto3.resource(\"s3\")\n\n # timestamp = str(time.time()).replace('.', '')\n filename = f\"{prefix}.pickle\"\n obj = s3.Object(bucket, filename)\n obj.put(Body=data)\n\n return filename", "def _load_job_ids_from_aws(self):\n with NamedTemporaryFile() as tmp:\n bucket_name, key = parse_bucket_name_key(os.path.join(self.results_bucket, ELB_METADATA_DIR, ELB_AWS_JOB_IDS))\n bucket = self.s3.Bucket(bucket_name)\n try:\n bucket.download_file(key, tmp.name)\n with open(tmp.name) as f_ids:\n self.job_ids = json.load(f_ids)\n except ClientError as err:\n # if the metadata file does not exist, get job ids\n # and save them in metadata\n logging.debug(f'Failed to retrieve {os.path.join(self.results_bucket, ELB_METADATA_DIR, ELB_AWS_JOB_IDS)}')\n if err.response['Error']['Code'] == '404':\n self.job_ids = self.get_job_ids()\n self.upload_job_ids()\n else:\n raise", "def _save(self, s3_prefix):\n bucket_name, prefix = split_s3_path(s3_prefix)\n bucket = self.s3_conn.get_bucket(bucket_name)\n self._compute_percentages()\n self.stats['last_updated'] = datetime.now().isoformat()\n key = boto.s3.key.Key(\n bucket=bucket,\n name='{}/{}/{}.json'.format(\n prefix,\n self.directory,\n self.dataset_id\n )\n )\n key.set_contents_from_string(json.dumps(self.stats))", "def _generate_s3_metadata_key(self, file_id: str, location: str) -> str:\n return f'{location}/{file_id}.{self._get_metadata_location_extension(location)}'", "def _save(self, s3_prefix):\n bucket_name, prefix = split_s3_path(s3_prefix)\n bucket = self.s3_conn.get_bucket(bucket_name)\n self._compute_percentages()\n self.stats['last_updated'] = datetime.now().isoformat()\n key = self._key(bucket, prefix)\n key.set_contents_from_string(json.dumps(self.stats))", "def save_to_file(self):\n for key, value in self.object_metadata.items():\n print('Bucket: {} ====> {}'.format(key, value))\n file_name = os.path.join(\n self.output_dir, 'object_count_difference.json')\n os.makedirs(os.path.dirname(file_name), exist_ok=True)\n with open(file_name, 'w') as fp:\n json.dump(self.object_metadata, fp)\n print('File saved at: {}'.format(file_name))\n print('Prefix Path: {}, File Name: {}'.format(prefix_path, file_name))", "def set_metadata(self, jobid, metadata):", "def store_gafqmc_info_metadata(info, hdf5_job_rec):\n pass", "def mongo_add_s3_file_key(job_id, s3_file_key):\n response = mongo.db.jobs.update_one({'_id': ObjectId(job_id)}, {'$set': {'s3_file_key': s3_file_key}})\n return response", "def _SaveMetadata(self):\n data = {'cur_seq': self.cur_seq,\n 'cur_pos': self.cur_pos}\n with file_utils.AtomicWrite(self.metadata_path, fsync=True) as f:\n json.dump(data, f)", "def save_chunk(app, chunk_id, dset_json, chunk_arr, bucket=None):\n log.info(f\"save_chunk {chunk_id} bucket={bucket}\")\n\n try:\n validateInPartition(app, chunk_id)\n except KeyError:\n log.error(f\"Chunk {chunk_id} not in partition\")\n raise HTTPInternalServerError()\n\n item_size = getItemSize(dset_json[\"type\"])\n # will store filter options into app['filter_map']\n getFilterOps(app, dset_json, item_size)\n\n chunk_cache = app[\"chunk_cache\"]\n if chunk_id not in chunk_cache:\n # check that we have enough room to store the chunk\n # TBD: there could be issues with the free space calculation\n # not working precisely with variable types\n log.debug(f\"chunk_cache free space: {chunk_cache.memFree}\")\n if chunk_cache.memFree < chunk_arr.size:\n msg = f\"unable to save chunk: {chunk_id}, \"\n msg += f\"chunk_cache free space: {chunk_cache.memFree}, \"\n msg += f\"chunk_size:{chunk_arr.size}\"\n log.warn(msg)\n raise HTTPServiceUnavailable()\n\n chunk_cache[chunk_id] = chunk_arr\n chunk_cache.setDirty(chunk_id)\n log.debug(f\"chunk cache dirty count: {chunk_cache.dirtyCount}\")\n\n # async write to S3\n dirty_ids = app[\"dirty_ids\"]\n now = time.time()\n dirty_ids[chunk_id] = (now, bucket)", "def store_job_meta(self, mol_db_id):\n logger.info('Storing job metadata')\n rows = [(mol_db_id, self._ds.id, JobStatus.RUNNING, datetime.now().strftime('%Y-%m-%d %H:%M:%S'))]\n self._job_id = self._db.insert_return(JOB_INS, rows=rows)[0]", "def save_modified(self, path):\n print(\"Modify bucket name to proceed\")\n bucket = 'your.bucket.name'\n body = ''\n for key in self.data:\n body += key\n #if len(key) < 22:\n # body += (' ' * (21 - len(key)))\n #key_length = self.length - len(self.data[key])\n key_length = len(self.data[key])\n for i in range(0, len(self.data[key])):\n if type(self.data[key][i]) == bool:\n #self.data[key][i] = '.{0}.'.format(str(self.data[key][i]).upper())\n body += (','+'.{0}.'.format(str(self.data[key][i]).upper()))\n elif type(self.data[key][i]) == float and self.data[key][i] == 0.0:\n self.data[key][i] = int(self.data[key][i])\n body += (','+str(self.data[key][i]))\n else:\n body += (','+str(self.data[key][i]))\n #body += (','*key_length)\n body += '\\n'\n #######\n #MODIFY THE SECTION TO SUIT YOUR NEEDS\n ######\n print('Modify the code section below before running')\n #s3 = boto3.client('s3', region_name = 'us-east-1')\n #self.counter += 1\n #modified_path = 'your/path' + path + '-{}.csv'.format(self.counter)\n #s3.put_object(Bucket = bucket, Key = modified_path, Body = body)\n #self._insert_changes(modified_path.replace('your/path', ''))\n print('Saving parameter file ' + modified_path + ' to S3' )", "def session_to_s3(prefix, bucket_name, timestamp=True, **kwargs):\n if timestamp:\n now_str = str(datetime.now())\n date_time_str = re.sub('[^0-9a-zA-Z]+', '_', now_str)\n filename = prefix + \"_\" + date_time_str + \".pkl\"\n else:\n filename = prefix + \".pkl\"\n dill.dump_session(filename)\n s3 = boto3.resource('s3')\n s3.meta.client.upload_file(filename, bucket_name, filename, **kwargs)\n return filename", "def split_and_upload():\n df = pd.read_csv(\n \"data/2319102.csv\",\n parse_dates=[\"DATE\"],\n quoting=1,\n usecols=[\n \"STATION\",\n \"NAME\",\n \"LATITUDE\",\n \"LONGITUDE\",\n \"ELEVATION\",\n \"DATE\",\n \"AWND\",\n \"PRCP\",\n \"SNOW\",\n \"TMAX\",\n \"TMIN\",\n ],\n )\n\n s3 = boto3.resource(\"s3\")\n\n for date, group in df.groupby(\"DATE\"):\n buffer = StringIO()\n group.to_json(buffer, orient=\"records\", lines=True)\n\n date_str = date.date().isoformat()\n month_str = date_str[:7]\n path = f\"weather/{month_str}/weather-{date_str}.json\"\n\n try:\n s3.Object(\"dend-capstone-somi\", path).put(Body=buffer.getvalue())\n except Exception as e:\n logging.error(e)\n else:\n logging.info(f\"Saved {date_str}\")", "def save_results(output, dest_bucket, eventime):\n try:\n print(\"Saving results into: \" + dest_bucket)\n out='output/inference-{}.csv'.format(eventime)\n s3.put_object(Body=output, Bucket=dest_bucket, Key=out) \n\n except Exception as e:\n print(e)\n print('Error getting object {} from bucket {}. Make sure they exist and your bucket is in the same region as this function.'.format(key, bucket))\n raise e", "def _write(self, filename):\n\n loc = self.config[\"data_specs\"][\"out_loc\"] \n if \"s3://\" in loc.lower():\n s3 = boto3.resource('s3')\n splitted = loc.split(\"/\")\n bucket = splitted[2]\n key = \"/\".join(splitted[3:])\n key_divider = \"/\" if splitted[-1] else \"\"\n destination = \"{0}{1}{2}\".format(key, key_divider, filename)\n if filename.split(\".\")[-1] in [\"obj\", \"json\"]:\n with open(\"{0}/{1}\".format(tmpdir, filename), \"rb\") as data:\n s3.meta.client.upload_fileobj(data, bucket, destination)\n else:\n s3.meta.client.upload_file(\"{0}/{1}\".format(tmpdir, filename), bucket, destination)\n else:\n shutil.copyfileobj(\n open(\"{0}/{1}\".format(tmpdir, filename), \"rb\"), \n open(\"{0}/{1}\".format(\n loc[:-1] if loc[-1] == \"/\" else loc, \n filename), \"wb\")) \n os.remove(\"{0}/{1}\".format(tmpdir, filename))", "def save_metadata(self, dirname):\n file = 'metadata.csv'\n fn = os.path.join(dirname, file)\n self.metadata.to_csv(fn, index=False)", "def import_files():\n storage = S3BotoStorage()\n for key in storage.bucket.list():\n if not dm.Document.objects.filter(source_file=key.name): # No existing metadata object\n title = os.path.splitext(os.path.basename(key.name))[0]\n if title: # ignore .xxx files\n document = dm.Document(source_file=key.name,\n title=title)\n document.save() # save here so m2m relations are possible\n\n filename, created = dm.FileName.objects.get_or_create(name=key.name)\n if created:\n filename.save()\n document.filenames.add(filename)\n\n path = os.path.split(key.name)[0]\n if path:\n category_names = path.split(os.path.sep)\n categories = dm.verify_categories(category_names, create_if_absent=True)\n document.categories.add(categories[-1])" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save query length in a metadata file in S3
def upload_query_length(self, query_length: int) -> None: if self.dry_run: return bucket_name, key = parse_bucket_name_key(f'{self.results_bucket}/{ELB_METADATA_DIR}/{ELB_AWS_QUERY_LENGTH}') bucket = self.s3.Bucket(bucket_name) bucket.put_object(Body=str(query_length).encode(), Key=key)
[ "def _save(self, s3_prefix):\n bucket_name, prefix = split_s3_path(s3_prefix)\n bucket = self.s3_conn.get_bucket(bucket_name)\n self._compute_percentages()\n self.stats['last_updated'] = datetime.now().isoformat()\n key = boto.s3.key.Key(\n bucket=bucket,\n name='{}/{}/{}.json'.format(\n prefix,\n self.directory,\n self.dataset_id\n )\n )\n key.set_contents_from_string(json.dumps(self.stats))", "def _save(self, s3_prefix):\n bucket_name, prefix = split_s3_path(s3_prefix)\n bucket = self.s3_conn.get_bucket(bucket_name)\n self._compute_percentages()\n self.stats['last_updated'] = datetime.now().isoformat()\n key = self._key(bucket, prefix)\n key.set_contents_from_string(json.dumps(self.stats))", "def save_to_file(self):\n for key, value in self.object_metadata.items():\n print('Bucket: {} ====> {}'.format(key, value))\n file_name = os.path.join(\n self.output_dir, 'object_count_difference.json')\n os.makedirs(os.path.dirname(file_name), exist_ok=True)\n with open(file_name, 'w') as fp:\n json.dump(self.object_metadata, fp)\n print('File saved at: {}'.format(file_name))\n print('Prefix Path: {}, File Name: {}'.format(prefix_path, file_name))", "def s3_metadata(self) -> 'outputs.S3CompatibleMetadataResponse':\n return pulumi.get(self, \"s3_metadata\")", "def get_obj_file_size(bucket: str, key: str):\n s3 = boto3.resource('s3')\n bucket = s3.Bucket(bucket)\n filesize = 0\n try:\n obj = bucket.Object(key=key)\n filesize = obj.content_length\n except ClientError as err:\n print(str(err))\n return filesize", "def store_gafqmc_info_metadata(info, hdf5_job_rec):\n pass", "def save_modified(self, path):\n print(\"Modify bucket name to proceed\")\n bucket = 'your.bucket.name'\n body = ''\n for key in self.data:\n body += key\n #if len(key) < 22:\n # body += (' ' * (21 - len(key)))\n #key_length = self.length - len(self.data[key])\n key_length = len(self.data[key])\n for i in range(0, len(self.data[key])):\n if type(self.data[key][i]) == bool:\n #self.data[key][i] = '.{0}.'.format(str(self.data[key][i]).upper())\n body += (','+'.{0}.'.format(str(self.data[key][i]).upper()))\n elif type(self.data[key][i]) == float and self.data[key][i] == 0.0:\n self.data[key][i] = int(self.data[key][i])\n body += (','+str(self.data[key][i]))\n else:\n body += (','+str(self.data[key][i]))\n #body += (','*key_length)\n body += '\\n'\n #######\n #MODIFY THE SECTION TO SUIT YOUR NEEDS\n ######\n print('Modify the code section below before running')\n #s3 = boto3.client('s3', region_name = 'us-east-1')\n #self.counter += 1\n #modified_path = 'your/path' + path + '-{}.csv'.format(self.counter)\n #s3.put_object(Bucket = bucket, Key = modified_path, Body = body)\n #self._insert_changes(modified_path.replace('your/path', ''))\n print('Saving parameter file ' + modified_path + ' to S3' )", "def test_017_queue_insert_metadata_size65536(self):\n url = self.cfg.base_url + '/queues/qtestqueue/metadata'\n doc = functionlib.get_custom_body({\"metadatasize\": 65536})\n result = http.put(url, self.header, doc)\n\n self.assertEqual(result.status_code, 204)\n\n result = http.get(url, self.header)\n self.assertEqual(result.status_code, 200)\n self.assertEqual(result.json(), json.loads(doc))", "def write_size(self):\n data = {\"name\": str(self.source),\n \"size\": self.source.stat().st_size}\n with self.target_size_path.open(\"w\") as f:\n json.dump(data, f)\n return True", "def _generate_s3_metadata_key(self, file_id: str, location: str) -> str:\n return f'{location}/{file_id}.{self._get_metadata_location_extension(location)}'", "def write_cache(self):\n with open(self.output_filename+\"_cache\"+\".txt\", 'wb') as cache:\n cache.write(\"byte_count: \"+str(self.byte_count)+\"\\r\\n\")\n if self.ini_header.has_key(\"ETag\"):\n cache.write(\"ETag: \"+self.ini_header[\"ETag\"]+\"\\r\\n\")\n if self.ini_header.has_key(\"Last-Modified\"):\n cache.write(\"Last-Modified: \"+self.ini_header[\"Last-Modified\"]+\"\\r\\n\")\n if self.ini_header.has_key(\"Content-Length\"):\n cache.write(\"Content-Length: \"+str(self.content_length)+\"\\r\\n\")\n\n # print \"from extract: \" + cache_dict[\"Content-Length\"", "def write_meta(self, file_object):\n meta = self._gen_meta()\n file_object.write(meta[\"magic_number\"].encode(\"UTF-8\"))\n file_object.write(meta[\"data_length\"].to_bytes(8, \"big\", signed = False))\n file_object.write(meta[\"word_length\"].to_bytes(8, \"big\", signed = False))\n file_object.write(\"DICT_START\".encode(\"utf-8\"))\n file_object.write(str(meta[\"encode_dict\"]).encode(\"utf-8\"))\n file_object.write(\"DICT_END\".encode(\"utf-8\"))", "def _backend_metadata(self) -> dict:\n return {\"storage_type\": \"public_s3_bucket\",\n \"name\": \"Public S3 Bucket\",\n \"description\": \"A type to use data stored in a public S3 bucket\",\n \"tags\": [\"unmanaged\", \"s3\", \"aws\"],\n \"icon\": \"s3.png\",\n \"url\": \"https://docs.gigantum.com\",\n \"readme\": \"\"\"This dataset type simply loads data from a public S3 bucket. It supports automatic \nsynchronization with S3 so you don't need to manually enter any information other than the bucket name. \n\nDue to the possibility of storing lots of data, when updating you can optionally keep all data locally or not. Because\n all files must be hashed when adding to the dataset, they all need to be downloaded by the creator. Once added\n to the dataset, partial downloads of the data is supported. To learn more, check out the docs here:\n [https://docs.gigantum.com](https://docs.gigantum.com)\n\"\"\"}", "def test_016_queue_insert_metadata_size65535(self):\n url = self.cfg.base_url + '/queues/qtestqueue'\n result = http.put(url, self.header)\n\n url = self.cfg.base_url + '/queues/qtestqueue/metadata'\n doc = functionlib.get_custom_body({\"metadatasize\": 65535})\n result = http.put(url, self.header, doc)\n\n self.assertEqual(result.status_code, 204)\n\n result = http.get(url, self.header)\n self.assertEqual(result.status_code, 200)\n self.assertEqual(result.json(), json.loads(doc))", "def save_results(output, dest_bucket, eventime):\n try:\n print(\"Saving results into: \" + dest_bucket)\n out='output/inference-{}.csv'.format(eventime)\n s3.put_object(Body=output, Bucket=dest_bucket, Key=out) \n\n except Exception as e:\n print(e)\n print('Error getting object {} from bucket {}. Make sure they exist and your bucket is in the same region as this function.'.format(key, bucket))\n raise e", "def size(self, url):\n return self.metadata(url).size_in_bytes", "def get_size(bucket=\"czb-seqbot\", prefix=None):\n yield from prefix_gen(bucket, prefix, lambda r: (r[\"Key\"], r[\"Size\"]))", "def write_meta_information_to_file(meta_file, md5sum, chunk, chunks):\n if chunk < (chunks - 1):\n upload_meta_data = \"status=uploading&chunk=%s&chunks=%s&md5=%s\" % (chunk,chunks,md5sum)\n try:\n meta_file.write(upload_meta_data)\n finally:\n meta_file.close()\n else:\n # last chunk\n path = meta_file.name\n meta_file.close()\n os.remove(path)", "def metadata_save(gvar):\n return base_metadata_save(gvar, context='cloud')" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve the list of AWS Batch job IDs from AWS First it tries to get them from S3, if this isn't available, gets this data from AWS Batch APIs.
def _load_job_ids_from_aws(self): with NamedTemporaryFile() as tmp: bucket_name, key = parse_bucket_name_key(os.path.join(self.results_bucket, ELB_METADATA_DIR, ELB_AWS_JOB_IDS)) bucket = self.s3.Bucket(bucket_name) try: bucket.download_file(key, tmp.name) with open(tmp.name) as f_ids: self.job_ids = json.load(f_ids) except ClientError as err: # if the metadata file does not exist, get job ids # and save them in metadata logging.debug(f'Failed to retrieve {os.path.join(self.results_bucket, ELB_METADATA_DIR, ELB_AWS_JOB_IDS)}') if err.response['Error']['Code'] == '404': self.job_ids = self.get_job_ids() self.upload_job_ids() else: raise
[ "def get_job_ids(self) -> List[str]:\n # we can only query for job ids by jobs states which can change\n # between calls, so order in which job states are processed matters\n ids = defaultdict(int) \n logging.debug(f'Retrieving job IDs from job queue {self.job_queue_name}')\n for status in AWS_BATCH_JOB_STATES:\n batch_of_jobs = self.batch.list_jobs(jobQueue=self.job_queue_name,\n jobStatus=status)\n for j in batch_of_jobs['jobSummaryList']:\n ids[j['jobId']] = 1\n\n while 'nextToken' in batch_of_jobs:\n batch_of_jobs = self.batch.list_jobs(jobQueue=self.job_queue_name,\n jobStatus=status,\n nextToken=batch_of_jobs['nextToken'])\n for j in batch_of_jobs['jobSummaryList']:\n ids[j['jobId']] = 1\n\n logging.debug(f'Retrieved {len(ids.keys())} job IDs')\n return list(ids.keys())", "def upload_job_ids(self) -> None:\n bucket_name, key = parse_bucket_name_key(f'{self.results_bucket}/{ELB_METADATA_DIR}/{ELB_AWS_JOB_IDS}')\n bucket = self.s3.Bucket(bucket_name)\n bucket.put_object(Body=json.dumps(self.job_ids).encode(), Key=key)", "def jobs_get(self):\n try:\n cart = self.cart\n jobs = []\n\n c = get_cursor()\n c.execute(\"\"\" select job_id from job\n where job.cart_id = %s\"\"\",\n (self.cart['cart_id'],))\n job_ids = c.fetchall()\n\n for job_id in job_ids:\n jobs.append(Job.Job(job_id=job_id))\n return jobs\n except CartInvalid as e:\n raise CartInvalid(e)\n except Exception as e:\n import traceback\n traceback.print_exc()\n print e.__class__.__name__ + \": \" + str(e)\n raise DbError(\"Internal error\")", "def get_ids(request, job_name):\n\ttry:\n\t\tjob = Job.objects.get(name=job_name)\n\t\tids = [task.task_id for task in job.task_set.all()]\n\t\treturn StreamingHttpResponse(json.dumps(ids))\n\texcept Job.DoesNotExist:\n\t\treturn Http404", "def job_ids(self):\n return [elem[\"id\"] for elem in self.all()]", "def getJobs(self, type=\"list\"):\n if type == \"list\":\n return self.jobs\n elif type == \"id\":\n jobIDs = []\n\n for job in self.jobs:\n jobIDs.append(job[\"id\"])\n\n return jobIDs\n else:\n print(\"Unknown type: %s\" % type)\n\n return", "def getJobIDs(workflowIDs = []):\n return Aux.getJobIDs(workflowIDs)", "def get_batch_job(self) -> SlurmBatchJob:\n ...", "def get_job_ids(self, offset=0, length=-1):\n start = offset\n if length >= 0:\n end = offset + (length - 1)\n else:\n end = length\n return [as_text(job_id) for job_id in\n self.connection.lrange(self.key, start, end)]", "def get_jobs_in_queue(batch_job_queue: str) -> list:\n jobs = []\n # AWS Batch only returns one status at a time and doesn't provide a `count` or `total`.\n for status in [*PENDING_STATUSES, \"RUNNING\"]:\n list_jobs_dict = batch.list_jobs(jobQueue=batch_job_queue, jobStatus=status)\n\n jobs.extend(list_jobs_dict[\"jobSummaryList\"])\n\n while \"nextToken\" in list_jobs_dict and list_jobs_dict[\"nextToken\"]:\n list_jobs_dict = batch.list_jobs(\n jobQueue=batch_job_queue,\n jobStatus=status,\n nextToken=list_jobs_dict[\"nextToken\"],\n )\n jobs.extend(list_jobs_dict[\"jobSummaryList\"])\n\n return jobs", "def retrieve_jobs(self, job_ids):\n return [HoneywellJob(self, job_id, self._api) for job_id in job_ids]", "def get_jobs():\n\n redis_conn = db_utils.get_redis_conn()\n token = request.headers.get(\"Authorization\")\n job_ids = get_user_jobs(redis_conn, token)\n jobs = [get_job_info(redis_conn, job_id, with_relics=False) for job_id in job_ids]\n jobs = [j for j in jobs if j]\n\n return jsonify({\"success\": True, \"data\": jobs})", "def get_jobs(self, offset=0, length=-1):\n job_ids = self.get_job_ids(offset, length)\n return compact([self.fetch_job(job_id) for job_id in job_ids])", "def get_recording_batchrequest(self, job_id, **kwargs):\n\n all_params = ['job_id']\n all_params.append('callback')\n\n params = locals()\n for key, val in iteritems(params['kwargs']):\n if key not in all_params:\n raise TypeError(\n \"Got an unexpected keyword argument '%s'\"\n \" to method get_recording_batchrequest\" % key\n )\n params[key] = val\n del params['kwargs']\n\n # verify the required parameter 'job_id' is set\n if ('job_id' not in params) or (params['job_id'] is None):\n raise ValueError(\"Missing the required parameter `job_id` when calling `get_recording_batchrequest`\")\n\n\n resource_path = '/api/v2/recording/batchrequests/{jobId}'.replace('{format}', 'json')\n path_params = {}\n if 'job_id' in params:\n path_params['jobId'] = params['job_id']\n\n query_params = {}\n\n header_params = {}\n\n form_params = []\n local_var_files = {}\n\n body_params = None\n\n # HTTP header `Accept`\n header_params['Accept'] = self.api_client.\\\n select_header_accept(['application/json'])\n if not header_params['Accept']:\n del header_params['Accept']\n\n # HTTP header `Content-Type`\n header_params['Content-Type'] = self.api_client.\\\n select_header_content_type(['application/json'])\n\n # Authentication setting\n auth_settings = ['PureCloud OAuth']\n\n response = self.api_client.call_api(resource_path, 'GET',\n path_params,\n query_params,\n header_params,\n body=body_params,\n post_params=form_params,\n files=local_var_files,\n response_type='BatchDownloadJobStatusResult',\n auth_settings=auth_settings,\n callback=params.get('callback'))\n return response", "def start_job(self, job_name):\n\n if type(job_name) != list:\n job_name = [job_name, ]\n\n # Make sure we have an SSH connection\n self.refresh_ssh_client()\n\n for p, j in izip_longest(self.project_directory, job_name, fillvalue=self.project_directory[-1]):\n j = os.path.split(j)[-1]\n print('Starting batch file: {} in directory {}'.format(j, p))\n\n # Check for path existence\n stdin, stdout, stderr = self.client.exec_command('ls {}'.format(p))\n out = stdout.read()\n err = stderr.read() # Harmless module load errors make using stderr unreliable\n\n assert j in out, \"Cannot find {}\\n Run will not start\".format(j)\n\n stdin, stdout, stderr = self.client.exec_command('cd {}; sbatch {}'.format(p, j))\n\n out = stdout.read()\n err = stderr.read()\n\n if out:\n # return JobID\n status = out.split()\n self.job_ids.append(status[-1])\n elif err:\n print(err)\n return err\n\n if self.array_tasks:\n assert len(self.job_ids) == 1, \"Array job must return only 1 ID number\"\n for i in self.array_tasks:\n self.job_ids.append(str(self.job_ids[0] + '_' + str(i)))\n self.job_ids.pop(0)\n\n return self.job_ids", "def get_object_ids(self):\n params = self.default_params.copy()\n params.update(self.ids_params)\n if self.where:\n params.update({\n 'where': ' and '.join(self.where),\n })\n url = self.service_url + urlencode(params)\n logger.debug('Getting object ids with url \"%s\"' % url)\n return json.load(urlopen(url))['objectIds']", "def get_jobs_by_jobid(self, jobid):\n return self.get_jobs(jobid=jobid)", "def getActiveJobs():\n ge = GridEngine()\n # require all array job tasks\n so = ge.qstat(['-u', '*', '-j', '*'])\n # job ids are collected as jobid.taskid - for non array\n # jobs jobid.1\n jobids = [ ]\n lines = so.split('\\n')\n jobid = ''\n taskid = ''\n for line in lines:\n if \"job_number:\" in line:\n pair = line.split()\n if len(pair) == 2:\n jobid = pair[1]\n if \"job-array tasks: \" in line:\n triple = line.split()\n if len(triple) == 3:\n taskid = triple[2]\n if \"scheduling info:\" in line:\n # this is the last entry (even when turned off)\n if jobid != '':\n if taskid == '':\n jobids.append(jobid)\n else:\n # 1-100:1 for example\n for task in expandTaskIds(taskid):\n jobids.append(jobid + \".\" + str(task))\n jobid = ''\n taskid = ''\n\n return jobids", "def get_jobs(self, connector_id, page_num=0, page_size=150, client_id=None):\n\n if client_id is None:\n client_id = self._use_default_client_id()[0]\n\n url = self.api_base_url.format(str(client_id)) + \"/{}/job\".format(str(connector_id))\n\n params = {'page': page_num, 'size': page_size}\n\n try:\n raw_response = self.request_handler.make_request(ApiRequestHandler.GET, url, params=params)\n except RequestFailed:\n raise\n\n jsonified_response = json.loads(raw_response.text)\n\n return jsonified_response" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removes ancillary data from the end user's result bucket
def _remove_ancillary_data(self, bucket_prefix: str) -> None: bname, _ = parse_bucket_name_key(self.results_bucket) if not self.dry_run: s3_bucket = self.s3.Bucket(bname) s3_bucket.objects.filter(Prefix=bucket_prefix).delete() else: logging.debug(f'dry-run: would have removed {bname}/{bucket_prefix}')
[ "def clear_report_results(self):", "def delete(self,*args, **kwargs):\n for item in self.get_resultitem_dict().values():\n item.delete()\n super(Result, self).delete(*args, **kwargs)", "def clear(self):\n del self.results\n self.results = list()", "def remove_data(self, obj):\n del obj.data[self.key]", "def remove_all_data(self):\n self._entries = []", "def clear_data():\n try:\n db.all_requests.remove()\n return {\"msg\": \"complete\"}\n except:\n return {\"msg\": \"error\"}", "def filter_data(self):\n self.remove_rows(self.earnings_yield, 0)\n self.remove_rows(self.ret_on_capital, 0)\n self.remove_rows(\"Liq.2meses\", 0)", "def remove_data(self):\n _DEPRECATION_ERROR_METHOD(\n self, \"remove_data\", \"Use method 'del_data' instead.\"\n ) # pragma: no cover", "def clear(self):\n self.buckets = [None] * self.size\n self.items = 0", "def clean_data_buffer():\n global usr_occ_list, usr_name_list, usr_url_list\n usr_name_list = []\n usr_occ_list = []\n usr_url_list = []", "def clear_test_result(self, test):", "def _clear_results(self):\r\n self._result_widget.clear()", "def clean_data(self):\n # Remove any row that is SCRATCHED\n self.rows[:] = [row for row in self.rows if \"SCRATCHED\" not in row]\n # Remove the list items we aren't using\n self.rows.pop() # Remove the last item in list\n for row in self.rows:\n split_string = row[10].split(\"$\", 2)\n if len(split_string) >= 3:\n row[10] = split_string[1]\n # Remove the columns we aren't using\n columns_to_remove = [0, 3, 4, 6, 7]\n for column in sorted(columns_to_remove, reverse=True):\n del row[column]", "def clear_statistic_terms(self):\n pass", "def clear(user_id=None):", "def clear_result_available(self):\n self.result_available = False\n\n return", "def test_bucketlist_empty_after_removingall(self):\n self.blist.delete_all_items_in_bucket()\n self.assertEqual([], self.blist.display_list())", "def get(self):\n # self.hts.multiEvents[\"STOCK\"].exit()\n self.hts.remove_real()\n self.hts.clear_market_state(\"{0:05}\".format(1))\n print(\"REMOVE ALL REAL\")", "def clean_data(self):\r\n self.all_data.drop(len(self.all_data) - 1, inplace = True)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Iterate over cloudformation stack events and extract error messages for failed resource creation or deletion. Cloudformation stack object must already be initialized.
def _get_cloudformation_errors(self) -> List[str]: # cloudformation stack must be initialized assert self.cf_stack messages = [] for event in self.cf_stack.events.all(): if event.resource_status == 'CREATE_FAILED' or \ event.resource_status == 'DELETE_FAILED': # resource creation may be canceled because other resources # were not created, these are not useful for reporting # problems if 'Resource creation cancelled' not in event.resource_status_reason: messages.append(f'{event.logical_resource_id}: {event.resource_status_reason}') return messages
[ "def get_errors(exc):\n while True:\n yield exc\n exc = getattr(exc, \"__cause__\") or getattr(exc, \"__context__\")\n if exc is None:\n return", "def _diff_stack(self, stack: Stack, **_: Any) -> Status:\n if self.cancel.wait(0):\n return INTERRUPTED\n\n if not deploy.should_submit(stack):\n return NotSubmittedStatus()\n\n provider = self.build_provider()\n\n if not deploy.should_update(stack):\n stack.set_outputs(provider.get_outputs(stack.fqn))\n return NotUpdatedStatus()\n\n tags = deploy.build_stack_tags(stack)\n\n try:\n provider_stack = provider.get_stack(stack.fqn)\n except exceptions.StackDoesNotExist:\n provider_stack = None\n\n try:\n stack.resolve(self.context, provider)\n parameters = self.build_parameters(stack, provider_stack)\n outputs = provider.get_stack_changes(\n stack, self._template(stack.blueprint), parameters, tags\n )\n stack.set_outputs(outputs)\n except exceptions.StackDidNotChange:\n LOGGER.info(\"%s:no changes\", stack.fqn)\n stack.set_outputs(provider.get_outputs(stack.fqn))\n except exceptions.StackDoesNotExist:\n if self.context.persistent_graph:\n return SkippedStatus(\n \"persistent graph: stack does not exist, will be removed\"\n )\n return DoesNotExistInCloudFormation()\n except AttributeError as err:\n if (\n self.context.persistent_graph\n and \"defined class or template path\" in str(err)\n ):\n return SkippedStatus(\"persistent graph: will be destroyed\")\n raise\n except ClientError as err:\n if (\n err.response[\"Error\"][\"Code\"] == \"ValidationError\"\n and \"length less than or equal to\" in err.response[\"Error\"][\"Message\"]\n ):\n LOGGER.error(\n \"%s:template is too large to provide directly to the API; \"\n \"S3 must be used\",\n stack.name,\n )\n return SkippedStatus(\"cfngin_bucket: existing bucket required\")\n raise\n return COMPLETE", "def describe_resources(self):\n response = {}\n for stack in self.stacks.values():\n try:\n resources = stack.describe_resources()\n response.update({stack.name: resources})\n except(botocore.exceptions.ClientError) as exp:\n if exp.response[\"Error\"][\"Message\"].endswith(\"does not exist\"):\n pass\n else:\n raise\n return response", "def test_create_error(self):\r\n t = template_format.parse(ig_template)\r\n stack = utils.parse_stack(t)\r\n\r\n self.m.StubOutWithMock(parser.Stack, 'validate')\r\n parser.Stack.validate()\r\n self.m.StubOutWithMock(nova_keypair.KeypairConstraint, 'validate')\r\n nova_keypair.KeypairConstraint.validate(\r\n mox.IgnoreArg(), mox.IgnoreArg()).MultipleTimes().AndReturn(True)\r\n self.m.StubOutWithMock(image.ImageConstraint, 'validate')\r\n image.ImageConstraint.validate(\r\n mox.IgnoreArg(), mox.IgnoreArg()).MultipleTimes().AndReturn(True)\r\n self.m.StubOutWithMock(instance.Instance, 'handle_create')\r\n instance.Instance.handle_create().AndRaise(Exception)\r\n\r\n self.m.ReplayAll()\r\n self.create_resource(t, stack, 'JobServerConfig')\r\n self.assertRaises(\r\n exception.ResourceFailure,\r\n self.create_resource, t, stack, 'JobServerGroup')\r\n\r\n rsrc = stack['JobServerGroup']\r\n self.assertEqual((rsrc.CREATE, rsrc.FAILED), rsrc.state)\r\n\r\n # The failed inner resource remains\r\n self.assertEqual(1, len(rsrc.nested().resources))\r\n child_resource = rsrc.nested().resources.values()[0]\r\n self.assertEqual((child_resource.CREATE, child_resource.FAILED),\r\n child_resource.state)\r\n\r\n self.m.VerifyAll()", "def check_statuses(self):\n for _id in self.get_stacks():\n resource = self.cf.Stack(_id)\n yield (resource.stack_name, resource.stack_status)", "def wait_for_completion(self):\n for i in range(100):\n output = run_command(\"cfn-describe-stacks \" + self.stack_name)\n if \"CREATE_COMPLETE\" in output:\n break\n if \"ROLLBACK_COMPLETE\" in output:\n run_command(\"cfn-describe-stack-events \" + self.stack_name)\n raise Exception('Stack creation error')\n time.sleep(15)", "def describe_events(self):\n return self.connection_manager.call(\n service=\"cloudformation\",\n command=\"describe_stack_events\",\n kwargs={\"StackName\": self.stack.external_name},\n )", "def destroy(stack, cf_resource):\n print(f\"Deleting {stack.name}.\")\n stack.delete()\n print(\"Waiting for stack removal.\")\n waiter = cf_resource.meta.client.get_waiter('stack_delete_complete')\n waiter.wait(StackName=stack.name)\n print(\"Stack delete complete.\")", "def test_create_complete_state_err(self):\r\n del self.templ['Resources']['WebServer']\r\n self.parent_resource.set_template(self.templ, {\"KeyName\": \"test\"})\r\n\r\n ctx = self.parent_resource.context\r\n phy_id = \"cb2f2b28-a663-4683-802c-4b40c916e1ff\"\r\n templ = parser.Template(self.templ)\r\n env = environment.Environment({\"KeyName\": \"test\"})\r\n self.stack = parser.Stack(ctx, phy_id, templ, env, timeout_mins=None,\r\n disable_rollback=True,\r\n parent_resource=self.parent_resource)\r\n\r\n self.m.StubOutWithMock(parser, 'Template')\r\n parser.Template(self.templ, files={}).AndReturn(templ)\r\n\r\n self.m.StubOutWithMock(environment, 'Environment')\r\n environment.Environment({\"KeyName\": \"test\"}).AndReturn(env)\r\n\r\n self.m.StubOutWithMock(parser, 'Stack')\r\n parser.Stack(ctx, phy_id, templ, env, timeout_mins=None,\r\n disable_rollback=True,\r\n parent_resource=self.parent_resource,\r\n owner_id=self.parent_stack.id,\r\n adopt_stack_data=None).AndReturn(self.stack)\r\n\r\n st_set = self.stack.state_set\r\n self.m.StubOutWithMock(self.stack, 'state_set')\r\n self.stack.state_set(self.stack.CREATE, self.stack.IN_PROGRESS,\r\n \"Stack CREATE started\").WithSideEffects(st_set)\r\n\r\n self.stack.state_set(self.stack.CREATE, self.stack.COMPLETE,\r\n \"Stack CREATE completed successfully\")\r\n self.m.ReplayAll()\r\n\r\n self.assertRaises(exception.ResourceFailure,\r\n scheduler.TaskRunner(self.parent_resource.create))\r\n self.assertEqual(('CREATE', 'FAILED'), self.parent_resource.state)\r\n self.assertEqual(('Error: Stack CREATE started'),\r\n self.parent_resource.status_reason)\r\n\r\n self.m.VerifyAll()\r\n # Restore state_set to let clean up proceed\r\n self.stack.state_set = st_set", "def test_failed_heat_stacks(self):\n self.assertEqual(ovb_tenant_cleanup.failed_heat_stacks('testcloud'),\n ['baremetal_73703'])", "def error_details(self):\n\n # TODO There is no attempt so far to eliminate duplicates.\n # Duplicates could be eliminated based on exception type\n # and message or exception type and file name/line number\n # presuming the latter are available. Right now the file\n # name and line number aren't captured so can't rely on it.\n\n # TODO There are no constraints in place on what keys/values\n # can be in params dictionaries. Need to convert values to\n # strings at some point.\n\n if not self.errors:\n return\n\n for error in self.errors:\n params = {}\n params[\"stack_trace\"] = error.stack_trace\n\n intrinsics = {'spanId': error.span_id, 'error.expected': error.expected}\n intrinsics.update(self.trace_intrinsics)\n params['intrinsics'] = intrinsics\n\n params['agentAttributes'] = {}\n for attr in self.agent_attributes:\n if attr.destinations & DST_ERROR_COLLECTOR:\n params['agentAttributes'][attr.name] = attr.value\n\n params['userAttributes'] = {}\n for attr in self.user_attributes:\n if attr.destinations & DST_ERROR_COLLECTOR:\n params['userAttributes'][attr.name] = attr.value\n\n # add error specific custom params to this error's userAttributes\n\n err_attrs = create_user_attributes(error.custom_params,\n self.settings.attribute_filter)\n for attr in err_attrs:\n if attr.destinations & DST_ERROR_COLLECTOR:\n params['userAttributes'][attr.name] = attr.value\n\n yield newrelic.core.error_collector.TracedError(\n start_time=error.timestamp,\n path=self.path,\n message=error.message,\n type=error.type,\n parameters=params)", "def format_stack_event(e):\r\n keymap = {\r\n engine_api.EVENT_ID: 'EventId',\r\n engine_api.EVENT_RES_NAME: 'LogicalResourceId',\r\n engine_api.EVENT_RES_PHYSICAL_ID: 'PhysicalResourceId',\r\n engine_api.EVENT_RES_PROPERTIES: 'ResourceProperties',\r\n engine_api.EVENT_RES_STATUS_DATA: 'ResourceStatusReason',\r\n engine_api.EVENT_RES_TYPE: 'ResourceType',\r\n engine_api.EVENT_STACK_ID: 'StackId',\r\n engine_api.EVENT_STACK_NAME: 'StackName',\r\n engine_api.EVENT_TIMESTAMP: 'Timestamp',\r\n }\r\n\r\n result = api_utils.reformat_dict_keys(keymap, e)\r\n action = e[engine_api.EVENT_RES_ACTION]\r\n status = e[engine_api.EVENT_RES_STATUS]\r\n result['ResourceStatus'] = '_'.join((action, status))\r\n result['ResourceProperties'] = json.dumps(result[\r\n 'ResourceProperties'])\r\n\r\n return self._id_format(result)", "def delete_all_stacks(self):\n logging.debug(\"Destroying all cfn stacks\")\n for value in reversed(OrderedDict(self.__created_stacks).values()):\n try:\n self.delete_stack(value.name, value.region)\n except Exception as e:\n logging.error(\n \"Failed when destroying stack {0} in region {1} with exception {2}.\".format(\n value.name, value.region, e\n )\n )", "def _manage_stack_build(\n self, stack, command, threading_events,\n stack_statuses, dependencies\n ):\n for dependency in dependencies[stack.name]:\n threading_events[dependency].wait()\n if stack_statuses[dependency] == StackStatus.FAILED:\n self.logger.debug(\n \"%s, which %s depends on has failed. Marking \"\n \"%s as failed.\", dependency, stack.name, dependency\n )\n stack_statuses[stack.name] = StackStatus.FAILED\n\n if stack_statuses[stack.name] != StackStatus.FAILED:\n try:\n status = getattr(stack, command)()\n stack_statuses[stack.name] = status\n except Exception:\n stack_statuses[stack.name] = StackStatus.FAILED\n self.logger.exception(\n \"Stack %s failed to %s\", stack.name, command\n )\n\n threading_events[stack.name].set()", "def check_stacks(self, should_exist):\n stacks = {}\n\n for i in range(1, 7):\n stack_name = 'runway-tests-module-tags-' + str(i)\n try:\n response = CFN_CLIENT.describe_stacks(\n StackName=stack_name\n )['Stacks'][0]\n if response['StackStatus'] == 'CREATE_COMPLETE':\n stacks[stack_name] = True\n else:\n stacks[stack_name] = False\n except Exception: # pylint: disable=broad-except\n stacks[stack_name] = False\n for stack, status in stacks.items():\n if stack[-1] in should_exist:\n assert status, stack + ' exists in the account'\n else:\n assert not status, stack + ' does not exist'\n return stacks", "def test_is_stack_exists_boto_error(self):\n resp = deepcopy(self.FAKE_ERROR_RESP)\n resp['Error']['Message'] = 'An error that I cannot handle happened'\n self._cf.get_template.side_effect = ClientError(resp, '')\n\n with self.assertRaises(ClientError):\n self._cfn._is_stack_exists(self.TEST_STACK_NAME)\n self._cf.get_template.assert_called_once_with(StackName=self.TEST_STACK_NAME)", "def describe_resources(self):\n self.logger.debug(\"%s - Describing stack resources\", self.stack.name)\n try:\n response = self.connection_manager.call(\n service=\"cloudformation\",\n command=\"describe_stack_resources\",\n kwargs={\"StackName\": self.stack.external_name},\n )\n except botocore.exceptions.ClientError as e:\n if e.response[\"Error\"][\"Message\"].endswith(\"does not exist\"):\n return {self.stack.name: []}\n raise\n\n self.logger.debug(\n \"%s - Describe Stack resource response: %s\", self.stack.name, response\n )\n\n desired_properties = [\"LogicalResourceId\", \"PhysicalResourceId\"]\n\n formatted_response = {\n self.stack.name: [\n {k: v for k, v in item.items() if k in desired_properties}\n for item in response[\"StackResources\"]\n ]\n }\n return formatted_response", "def _describe_stack_resource_drifts(self) -> dict:\n self.logger.info(f\"{self.stack.name} - Describing Stack Resource Drifts\")\n\n return self.connection_manager.call(\n service=\"cloudformation\",\n command=\"describe_stack_resource_drifts\",\n kwargs={\"StackName\": self.stack.external_name},\n )", "def wait_for_stacks(self):\n while True:\n waiting = False\n for _id in self.get_stacks():\n resource = self.cf.Stack(_id)\n if resource.stack_status == 'CREATE_IN_PROGRESS':\n waiting = True\n if not waiting:\n return\n time.sleep(5)", "def check_file_exceptions(stack_references: list):\n for stack in stack_references:\n stack.raise_file_exception()" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This constructor method is used to assign the object of the Class Car to car attribute and parking slot number to parking_slot attribute of the class.
def __init__(self, car, parking_slot): self.car = car self.parking_slot = parking_slot
[ "def __init__(self, name, length, location, orientation):\r\n # Note that this function is required in your Car implementation.\r\n # However, is not part of the API for general car types.\r\n self.__name = name\r\n self.__length = length\r\n self.__location = location\r\n self.__orientation = orientation", "def __init__(self, car, nrDays):\n self.setCar(car)\n self.setNrDays(nrDays)", "def __init__(self, car_id='BMW_electric_i3_2014'):\n self.specs = get_specs(car_id)\n self.power_model = get_power_estimator(car_id)\n\n self.action_scaling_vecs()", "def setCar(self, car):\n self.__car = car", "def __init__(self, name, fuel):\n super().__init__(name, fuel)\n Taxi.price_per_km = 1.20\n self.current_fare_distance = 0", "def __init__(self, **kwargs):\n\n self._car_factory = CarFactory(type=kwargs.get(\"type\"), car_type=kwargs.get(\"car_type\"),doors=kwargs.get(\"doors\"),liters=kwargs.get(\"liters\"),fuel_type=kwargs.get(\"fuel_type\"))\n self.inventory.append(self._car_factory.get_car())", "def __init__(__self__, *,\n reservation_id: pulumi.Input[str],\n location: Optional[pulumi.Input[str]] = None,\n name: Optional[pulumi.Input[str]] = None,\n project: Optional[pulumi.Input[str]] = None,\n throughput_capacity: Optional[pulumi.Input[str]] = None):\n pulumi.set(__self__, \"reservation_id\", reservation_id)\n if location is not None:\n pulumi.set(__self__, \"location\", location)\n if name is not None:\n pulumi.set(__self__, \"name\", name)\n if project is not None:\n pulumi.set(__self__, \"project\", project)\n if throughput_capacity is not None:\n pulumi.set(__self__, \"throughput_capacity\", throughput_capacity)", "def __init__(self, id, manufacturer, model, year, price, wheel_size, category, spec1, spec2, spec3):\n\n self._id = id\n self._manufacturer = manufacturer\n self._model = model\n self._year = year\n self._price = price\n self._wheel_size = wheel_size\n self._type = category\n self._spec1 = spec1\n self._spec2 = spec2\n self._spec3 = spec3\n self.bike = [id, manufacturer, model, year, price, wheel_size, category, spec1, spec2, spec3]", "def __init__(self):\n self.fuel_capacity = 12\n self.fuel_level = 0", "def __init__(self, **kwargs):\n self.car = kwargs.get(\"type\")(type=kwargs.get(\"car_type\"),doors=kwargs.get(\"doors\"),fuel=Fuel(liters=kwargs.get(\"liters\"),type=kwargs.get(\"fuel_type\")))", "def __init__(self, move, car_list_parent, current, distance):\n self.move = move\n self.parent = car_list_parent\n self.current = current\n self.distance = distance", "def __init__(self, product_name: str, product_price: float):\n self.__product_name = product_name\n self.__product_price = product_price", "def __init__(self, name: str, price: float):\n self.name = name\n self.price = price", "def setup_car(self, vr, car):\n #\n # ASSIGNMENT: You may want to tune these paraneters.\n #\n car.set_boom_sensor_offset(0.1)\n # In the scene, we provide two cameras.\n # Camera 0 is used by default in the control loop and is the \"near\" one.\n # Some teams have also used a \"far\" camera in the past (Camera 1).\n # You can use additional cameras, but will have to add then in the V-REP scene\n # and bind the handle in Car.__init__. The V-REP remote API doesn't provide a\n # way to instantiate additional vision sensors.\n car.set_line_camera_parameters(0, height=0.3, orientation=30, fov=60)\n car.set_line_camera_parameters(1, height=0.4, orientation=15, fov=60)\n # You should measure the steering sevo limit and set it here.\n # A more accurate approach would be to implement servo slew limiting.\n car.set_steering_limit(30)", "def __init__(self, weight, fuel, fuel_consumption):\n self.weight = weight\n self.fuel = fuel\n self.fuel_consumption = fuel_consumption", "def __init__(self, species=''):\n\n # Check if the gas species is valid\n if species=='':\n raise ValueError(\"Gas species not defined.\")\n if type(species) is not str:\n raise TypeError(\"Gas species must be a string\")\n\n # SemiperfectIdealGas object:\n self.__from_semiperfect_gas = SemiperfectIdealGas(species)\n \n # Store the thermodynamic properties of the gas\n self.thermo_prop = self.__from_semiperfect_gas.thermo_prop\n\n # Reference temperature and gas species\n self.T_ref = cts.T_ref\n self._gas_species = species\n \n return", "def __init__(self, streets, paths, score_per_car, nr_iters):\n # Set parameters and store those necessary for resetting.\n self.streets = streets\n self.intersections = defaultdict(Intersection)\n self.cars = defaultdict(Car)\n self.score = 0\n self.score_per_car = score_per_car\n self.current_iter = 0\n self.nr_iters = nr_iters\n self.original_paths = paths\n\n # Build dict of Intersection objects using street dict\n for k, v in self.streets.items():\n self.intersections[v[0]].add_incoming(k)\n\n # Build dict of Car objects using paths\n for i, path in enumerate(paths):\n car = Car(path)\n self.cars[i] = car\n # Cars start waiting at the end of their first street, so queue them up.\n self.get_in_queue(i)", "def __init__(self, address, available, last_used):\n\n self.address = address\n self.available = available\n self.last_used = last_used\n\n pass", "def __init__(self):\n this = _coin.new_SoVRMLCylinder()\n try:\n self.this.append(this)\n except __builtin__.Exception:\n self.this = this" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method is used to return the vehicle registration number of the car.
def get_vehicle_registration_number(self): return self.car.get_registration_number()
[ "def get_registration_number(self):\n return self._registration_number", "def car_slot_no_for_registration_no(self, reg_id):\n\n if reg_id not in self.cars_parked:\n return \"Not found\"\n\n slot_number = 0\n\n for node in self.slots_occupied:\n if not node:\n continue\n if node.reg_id == reg_id:\n slot_number = node.slot\n break\n return slot_number", "def getVehicleId(self) -> int:\n return self.vehicleId", "def getVeh_id(self):\n return \"VEHICLE IDENTIFICATION NO. %s\"%self.veh_Iden_No", "def serial_number(self):\n return self._camera_data_structure[\"SerialNumber\"]", "def get_reg(self):\n return self.reg", "def next_register(self):\n self._next_register_number += 1\n if self._next_register_number >= Program.MAX_REGISTERS:\n raise RuntimeError(\"There are no more registers available.\")\n return self._next_register_number", "def get_vehicle_index(self, vehicle):\n index = None\n for i,v in enumerate(self.state['vehicles']):\n if v.id == vehicle.id:\n index = i\n break\n return index", "def test_create_vehicle_complete(self):\n self._autheticate_client()\n data = {'name': 'Ford', 'registration': 'f1', 'brand': 'Chrvolet', 'type': 'small', 'owner': self.user.id}\n response = self.client.post('/fleet/vehicle/', data, format='json')\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n\n return response.data.get('id')", "def getReg( splitted_request ):\n if len(splitted_request) != 3:\n raise ParametersError(\"Numero di parametri errato\")\n n = int(splitted_request[1])\n i = int(splitted_request[2])\n s = boxSessioni.findSessione( n )\n sessione_corrente = boxSessioni.box[s]\n if i < 0:\n raise LessThanZeroRegError(\"Inserito registro minore di 0\")\n return \"OK %i\\r\\n\" %sessione_corrente.registri[i]", "def get_car(self):\n return self.car", "def registrant(self) -> str:\n return self._id[self._registrant_idx:self._ref_idx]", "def registros(self) -> int:\n return self._registros", "def serial_number(self) -> str:\n return self._serial_number", "def phy_number(self):\n return self._phy_number", "def register_pi():\n global video_village_pi_id\n result = requests.post(VILLAGE_REGISTER_ENDPOINT,\n headers=VILLAGE_REQUEST_HEADERS,\n json={'mac_address': PI_HARDWARE_ADDRESS})\n if result.status_code == 200:\n registration_info = result.json()\n video_village_pi_id = registration_info.get('id')\n return True\n\n return False", "def get_device_count(self) -> int:\n return native.CorsairGetDeviceCount()", "def getProgramCounter(self) -> ghidra.program.model.lang.Register:\n ...", "def GetSerialNumber(self):\n\n request_type = (DEVICE_TO_HOST | VENDOR_TYPE | DEVICE_RECIPIENT)\n wValue = 0x0\n wIndex = 0x0\n value = self.udev.controlRead(request_type, self.SERIAL, wValue, wIndex, 8, self.HS_DELAY)\n return value.decode()" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method is used to return the age of the driver, driving the car.
def get_driver_age(self): return self.car.get_driver_age()
[ "def get_age(self):\n if self.basics['death']:\n return self.basics['death'] - self.basics['birth']\n else:\n return datetime.datetime.now().year - self.basics['birth']", "def age(self):\n age = _f.getage(self.pvec)\n return age", "def age(self) -> int:\n return calculate_age(self.date_of_birth, date.today())", "def age(self):\n birth_date = self.patient.get('birth_date', None)\n if birth_date:\n diff = self.created.date() - birth_date\n return int(diff.days / 30.475)", "def GetActualAge(self):\n return self.__age", "def get_age(self):\n\t\tif self.birthday is None:\n\t\t\traise ValueError\n\t\treturn (datetime.date.today() - self.birthday).days", "def age(self):\n return datetime.datetime.today() - self.date", "def get_age(self):\n return (self.created_at - datetime.datetime(1970, 1, 1)).total_seconds()", "def get_age(self):\n return (self.created_at - datetime(1970, 1, 1)).total_seconds()", "def get_player_age(self, soup):\n\t\ttargets = soup.find_all(\"div\", class_ = \"ng-binding\")\n\t\tif len(targets) < 4: return None\n\n\t\tage_blob = targets[3].get_text()\n\t\tpattern = 'Age:\\s([1-4][0-9]),'\n\t\tage = re.findall(pattern, age_blob)\n\n\t\tif not age: return None\n\t\tage = int(age[0])\n\t\treturn age", "def age_to(self) -> int:\n return self._age_to", "def compute_age(birth):\r\n birthday = datetime.strptime(birth, \"%Y-%m-%d\")\r\n today = datetime.now()\r\n \r\n # Compute the difference between today and the birthday in years.\r\n years = today.year - birthday.year\r\n \r\n # If necessary, subtract one from the difference.\r\n if birthday.month > today.month or \\\r\n (birthday.month == today.month and birthday.day > today.day):\r\n years -= 1\r\n \r\n return years", "def age_calc(self):\n if self.professor_dob is not False:\n self.age = (datetime.today().date()-datetime.strptime(\n str(self.professor_dob), '%Y-%m-%d').date()) // timedelta(days=365)", "def age(self):\n return self.commit.age", "def age_from(self) -> int:\n return self._age_from", "def get_age(actor: Actor, movie: Movie) -> str:\n birth_dt = parse(actor.born)\n release_dt = parse(movie.release_date)\n age_at_release = relativedelta(release_dt, birth_dt).years\n return f\"{actor.name} was {age_at_release} years old when {movie.title} came out.\"", "def age(self):\n return time.time() - self.create_epoch", "def ages(self) -> Tuple[CommonAge]:\n return self._ages", "def determine_age(dob, date):\n age = date.year - dob.year - ((dob.month, dob.day) > (date.month, date.day))\n\n # age = abs((date – dob)).days / 365.25\n\n return age" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method is used to return the parking slot number in which the car is parked.
def get_parking_slot(self): return self.parking_slot
[ "def car_slot_no_for_registration_no(self, reg_id):\n\n if reg_id not in self.cars_parked:\n return \"Not found\"\n\n slot_number = 0\n\n for node in self.slots_occupied:\n if not node:\n continue\n if node.reg_id == reg_id:\n slot_number = node.slot\n break\n return slot_number", "def vios_slot_num(self):\n return self._get_val_int(_VADPT_SLOT_NUM)", "def park(self, cmd):\n vehicle_details = {}\n vehicle_details['regisNum'] = cmd[1] if len(cmd) >=2 else ''\n vehicle_details['color'] = cmd[2] if len(cmd) >=3 else ''\n if vehicle_details.get('regisNum') and vehicle_details.get('color'):\n # check if available space in parking lot \n if len(self.empty_parkslot) == 0: # if no parking space available\n # return status : Sorry, parking lot is full\n output = 'Sorry, parking lot is full'\n print(output)\n else:\n # sort the empty parking list : ascending order\n self.empty_parkslot.sort()\n # parking slot number for incoming vehicle\n # allocate the slot with minimum value : as suggested\n slot = self.empty_parkslot.pop(0)\n\n # registration number \n regisNum = vehicle_details['regisNum']\n # incoming vehicle color\n color = vehicle_details['color']\n # insert all the details against search keys on parking slot num\n self.by_parkslot[slot] = {'regisNum': regisNum, 'color':color}\n\n # tertiary storage: insert to other mapped fast query storage\n self.by_color_parkslot.setdefault(color,[]).append(slot)\n self.by_color_regisNum.setdefault(color,[]).append(regisNum)\n self.by_regisNum_parkslot[regisNum] = slot\n\n #return success status : Allocated slot number 3 (ex)\n output = 'Allocated slot number: {}'.format(slot)\n print(output)\n else:\n output = 'Please Enter Valid Command'\n print(output)\n return output", "def allot_slot(self, car_reg_id, car_colour):\n\n if car_reg_id in self.cars_parked:\n return \"{} Car is already parked\".format(car_reg_id)\n elif self.slots_available <= 0:\n return \"Sorry, parking lot is full\"\n\n i = 0\n\n while self.slots_occupied[i]:\n i += 1\n\n car = ParkedCar(reg_id=car_reg_id, colour=car_colour, slot=i + 1)\n\n self.slots_occupied[i] = car\n self.cars_parked.add(car.reg_id)\n self.slots_available -= 1\n return \"Allocated slot number: {}\".format(car.slot)", "def get_pxi_slot_number (self):\n d = uInt32(0)\n CALL ('GetDevPXISlotNum', self, ctypes.byref (d))\n return d.value", "def __init__(self, car, parking_slot):\n\n self.car = car\n self.parking_slot = parking_slot", "def get_slot_count(self, slot):\n return self.items[slot]", "def find_spot(self, parking_lot):\n\t\tfor num in parking_lot.keys():\n\t\t\tif parking_lot[num].status == 'empty':\n\t\t\t\tself.park(parking_lot[num])\n\t\t\t\treturn '%s parked in %s' % (self.name, parking_lot[num].location)\n\t\t\telse:\n\t\t\t\tcontinue\n\t\t\treturn 'lot is full, wait then try again!'", "def park_vehicle(self, registration_number, size):\n nearest_spot = self.entry_exit.get_nearest_parking()\n if not nearest_spot:\n print(\"No Spot vacant\")\n return\n self.floor.fill_trigger_other_entry_exit(self.entry_exit, str(nearest_spot))\n ticket = uuid4()\n if size == \"BIG\":\n parking_lot.ticket_map[str(ticket)] = BigCar(registration_number, str(nearest_spot))\n else:\n parking_lot.ticket_map[str(ticket)] = SmallCar(registration_number, str(nearest_spot))\n print(f\"Car with ticket id {ticket} is parked\")", "def num_slots_used(self) -> int:\n return self.num_slots_total - self.num_slots_free", "def slot_id(self):\n try:\n return self.relation.plugin_data['slot_id']\n except:\n return ''", "def assignedSlot(self):\n return self.parentNode.assignedSlot", "def _find_slot(self, key):\n hashkey = hash(key) % self._size\n slot = self._slots[hashkey]\n return slot", "def nearest_vacant_slot(self):\n \n self.curr.execute(\n 'select slot_id from {} WHERE slot_status = ? ORDER BY slot_id LIMIT 1'.format(\n config.table_name, '?'), ['Free']\n )\n vacant_slot = self.curr.fetchall()\n #vacant_slot = []\n return vacant_slot", "def getPartNumber(self, name: 'SbName') -> \"int\":\n return _coin.SoNodekitCatalog_getPartNumber(self, name)", "def spot_price(self) -> str:\n return pulumi.get(self, \"spot_price\")", "def n_slots(self) -> int:\n return self._w", "def create_parking_lot(self, cmd):\n maxParking = cmd[1] if len(cmd) >=2 else ''\n if len(cmd) < 2:\n output = 'Please Enter valid Max limit' \n print(output)\n \n else:\n self.maxParking = maxParking\n self.empty_parkslot = list(range(1, int(maxParking)+1))\n output = \"Created a parking lot with {} slots\".format(maxParking) \n print(output)\n \n return output", "def get_slot_base_price(self, slot):\n return self.types[slot].price" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
nc = neo4j_connect object start = start stage (short_form_id string) end = end stage (short_form_id string) Returns list of intermediate stages.
def expand_stage_range(nc, start, end): stages = [start, end] statements = [ 'MATCH p=shortestPath((s:FBDV {short_form:"%s"})<-[:immediately_preceded_by*]-(e:FBDV {short_form:"%s"})) RETURN extract(x IN nodes(p) | x.short_form)' % (start, end)] r = nc.commit_list(statements) stages.append(r[0]['data'][0]['row'][0]) return stages
[ "def get_stages(self):\n def resolve_intersections(stage):\n \"\"\"Removes actions from a stage that creates\n conflict between the selected stage candidates.\"\"\"\n actions_to_remove = set()\n for a in stage:\n if self.action[a].get('next', None):\n intersection = self.action[a]['next'].intersection(stage)\n if intersection:\n for i in intersection:\n actions_to_remove.add(i)\n\n for a in actions_to_remove:\n stage.remove(a)\n\n current_stage = self.root\n\n while current_stage:\n yield current_stage\n next_stage = set()\n for n in current_stage:\n next_stage.update(\n self.action[n].get(\n 'next', set()))\n resolve_intersections(next_stage)\n current_stage = next_stage", "def ls_stage(self):\n return \"\\n\".join(self.stages)", "def stages(self) -> typing.List[str]:\n return typing.cast(\n typing.List[str],\n self._properties.get(\"stages\"),\n )", "def find_stages(self, stages, mash_name='_main', start_time=timedelta()):\n stage = []\n stages[mash_name] = stage\n #\n t = start_time\n vol = Quantity('0gal')\n temp = Quantity()\n num = 0\n for step in self.steps:\n num += 1\n type = step['type']\n # Current state\n if (num > 1):\n stage.append({'type': step['type'], 'time': t, 'volume': vol, 'temp': temp})\n if ('volume' in step):\n vol = step['volume']\n if ('temp' in step):\n temp = step['temp']\n # Action of this step\n action = {}\n action.update(step)\n action['time'] = t\n if ('time' in step):\n t += self.parsetime(step['time'])\n # add final state\n stage.append({'type': 'state', 'time': t, 'volume': vol, 'temp': temp})\n # no return val, data left in stage", "def _layer_connections(self):\n return [[j for j in [i-1,i+1] if 0<=j<self.num_layers]\n for i in range(self.num_layers)]", "def ports(stages, status):\n for stage in reversed(stages):\n stat = stage[status]\n if self._skip:\n length = len(stat)\n if status == Builder.FAILED and not self._indirect:\n length -= len([i for i in stat\n if \"failed\" not in i.flags])\n if self._skip >= length:\n self._skip -= length\n continue\n else:\n stat = stat[self._skip:]\n self._skip = 0\n for port in stat:\n if (status == Builder.FAILED and not self._indirect and\n \"failed\" not in port.flags):\n continue\n yield port, stage.stage", "def create_subnetwork_path(cursor, starting_species_list, operon_path, it_trans_dict):\n species_set = set()\n input_transition_set = set()\n operon_set = set()\n output_transition_set = set()\n edge_path_list = []\n current_species_list = starting_species_list\n\n for operon in range(len(operon_path)):\n\n operon_id = operon_path[operon]\n\n operon_node_abbrev, _ = create_operon_node(cursor, operon_id)\n\n operon_set.add(tuple(operon_node_abbrev))\n\n\n # Creating the input transition node (MULT ONES)\n it_node_abbrev_list, it_id_list = create_input_transition_nodes(cursor, current_species_list,\n operon_id, it_trans_dict)\n for it_node_abbrev, it_id in zip(it_node_abbrev_list, it_id_list):\n input_transition_set.add(tuple(it_node_abbrev))\n edge_path_list.append([it_node_abbrev[0], operon_node_abbrev[0]])\n\n # Creating the input species nodes and inputTransitionSpecies\n it_species_nodes_abbrev, _ = create_input_species_nodes(cursor, it_id)\n for it_species_node_abbrev in it_species_nodes_abbrev:\n species_set.add(tuple(it_species_node_abbrev))\n edge_path_list.append([it_species_node_abbrev[0], it_node_abbrev[0]])\n\n\n # Creating the output transitio nodes (ONLY ONE)\n ot_node_abbrev, ot_id = create_output_transition_node(cursor, operon_id)\n output_transition_set.add(tuple(ot_node_abbrev))\n edge_path_list.append([operon_node_abbrev[0], ot_node_abbrev[0]])\n ot_species_nodes_abbrev, ot_species_id_list = create_output_species_nodes(cursor, ot_id)\n\n for ot_species_node_abbrev in ot_species_nodes_abbrev:\n species_set.add(tuple(ot_species_node_abbrev))\n edge_path_list.append([ot_node_abbrev[0], ot_species_node_abbrev[0]])\n\n current_species_list = ot_species_id_list\n\n edge_path_list = list_of_tuples(edge_path_list)\n\n return species_set, input_transition_set, operon_set, output_transition_set, edge_path_list", "def __connectLayers(self):\n self.connectionsMatrix = []\n self.inputLayer.setNextLayer(self)\n self.outputLayer.setPreviousLayer(self)\n\n # build the matrix of synapses\n for o in range(len(self.outputLayer)):\n self.connectionsMatrix.append([])\n outUnit = self.outputLayer[o]\n\n for i in range(len(self.inputLayer)):\n inUnit = self.inputLayer[i]\n synapse = self.__connectUnits(inUnit, outUnit)\n self.connectionsMatrix[o].append(synapse)", "def cycles(self) -> List[GraphComponent]:\n return [\n compo\n for _, compo in self.tarjan_scc().items()\n if len(compo) > 1 or compo[0] in self.edges[compo[0]]\n ]", "def get_lifecycle_stage_list(self):\n response = self.client.get(self.client.get_url())\n\n results = {}\n for item in response.json():\n results[item['StageID']] = item['StageName']\n\n return results", "def stages_constructor(stages_list, input_names, output_vars):\n needed_vars = output_vars\n computational_stages = []\n # input names for args of a stage\n stage_input_names = list(input_names)\n # reverse the stage so that we start constructing from backward stages\n # that way, we can know which variables are needed by rest stages, and put it into \"needed_vars\"\n # in stage function, we will dynamically discard unsed variables to reduce transmission between stages\n for function_list in stages_list[::-1]:\n # for the last stage, output will be in same sequence with output_vars\n stage = stage_wrapper(function_list, needed_vars, stage_input_names)\n computational_stages.append(stage)\n needed_vars = set(needed_vars)\n for func in function_list:\n needed_vars = needed_vars.union(set(get_var_list(func)))\n # sort needed_varss so that it won't need to recompile because of output order changing\n needed_vars = sorted(needed_vars)\n\n # reverse computational_stages, because it's generated in reverse sequence\n return computational_stages[::-1]", "def create_input_transition_nodes(cursor, starting_species_list, operon_id, input_transition_id_dict):\n\n activated_it_ids = determine_operon_activated_input_transition(cursor, starting_species_list, operon_id,\n input_transition_id_dict)\n\n it_node_abbrev_list = []\n activated_it_id_list = []\n for activated_it_id in activated_it_ids:\n it_node = db.db_select(cursor, \"InputTransition\", \"*\", [\"it_id\"], [\"=\"], [activated_it_id], [\"\"])\n it_node = list(it_node.fetchone())\n it_node_abbrev = add_node_id_abbreviation(it_node, \"it_\", 0)\n it_node_abbrev_list.append(it_node_abbrev)\n activated_it_id_list.append(activated_it_id)\n\n return it_node_abbrev_list, activated_it_id_list", "def bfs_connected_component(self, start):\n explored = [] # keep track of all visited vertex\n queue = [start] #keep track of vertex checked\n\n while queue: # loops until there are vertex\n vertex = queue.pop(0) # pop first vertex from queue\n if vertex not in explored:\n explored.append(vertex) # add vertex to list of checked nodes\n neighbours = self.getVertex(vertex)\n\n for neighbour in neighbours.connectedTo.keys(): #add neighbour of vertex to queue\n queue.append(neighbour.id)\n return explored", "def _get_plan_edges(self, depth=0):\n edges = []\n if 0 != depth:\n from_job_id_, to_job_id_ = self._normalize_edge(Job.INIT_JOB, self.id)\n edges.append([to_job_id_, from_job_id_, '->START'])\n for plan_key, to_job_id in self.plan.items():\n # get edges for this JobBlock\n state, from_job_id = Job.decode_plan_key(plan_key)\n from_job_id_, to_job_id_ = self._normalize_edge(from_job_id, to_job_id)\n edge = [from_job_id_, to_job_id_, state]\n edges.append(edge)\n\n # bridge the gap of self.id -> self.id_START and\n # self.id_END -> seld.id\n if from_job_id == Job.INIT_JOB:\n edge = [self.id, from_job_id_, '->START']\n edges.append(edge)\n if to_job_id == Job.LAST_JOB and 0 != depth:\n edge = [to_job_id_, self.id, '->END']\n edges.append(edge)\n\n # get edges for inner JobBlock\n if not Job.is_pseudo_job(from_job_id):\n job = self.get_job(from_job_id)\n if (job.plannable):\n sub_edges = job._get_plan_edges(depth+1)\n edges += sub_edges\n if 0 != depth:\n from_job_id_, to_job_id_ = self._normalize_edge(self.id, Job.LAST_JOB)\n edges.append([to_job_id_, from_job_id_, '->END'])\n return edges", "def _removeEpsilonConnections(self):\n\t\tstatesToTraverse, outStates = [self.inState], set()\n\n\t\tfor currentState in statesToTraverse:\n\t\t\t# An ε-closure is the set of all the states reachable via ε-\n\t\t\t# connections of the current state. The new connections are all the \n\t\t\t# external connections of the ε-closure.\n\t\t\teClosure, newConnections = [currentState], set()\n\t\t\tfor state in eClosure:\n\t\t\t\tfor (value, connectedState) in state.connections:\n\t\t\t\t\t# If a connection is an ε-connection, we add it to the ε-\n\t\t\t\t\t# closure.\n\t\t\t\t\tif value == 'ε':\n\t\t\t\t\t\teClosure.append(connectedState)\n\t\t\t\t\t# Otherwise, we add it to the set of new connections, and to \n\t\t\t\t\t# the list of states to traverse (if not already present).\n\t\t\t\t\telse:\n\t\t\t\t\t\tnewConnections.add((value, connectedState))\n\t\t\t\t\t\tif connectedState not in statesToTraverse:\n\t\t\t\t\t\t\tstatesToTraverse.append(connectedState)\n\n\t\t\t# If a state's ε-closure has no external connections, that means that \n\t\t\t# it's an end-state.\n\t\t\tif not newConnections:\n\t\t\t\toutStates.add(currentState)\n\t\t\tcurrentState.connections = newConnections\n\n\t\treturn outStates", "def split_query_into_stages(query):\n stages = []\n current_stage = []\n subsearch = []\n\n for token in tokenize_query(query):\n\n if token.type == \"LBRACKET\":\n subsearch.append(token)\n current_stage.append(token.value)\n continue\n \n if token.type == \"RBRACKET\":\n current_stage.append(token.value)\n subsearch.pop(-1)\n if len(subsearch) == 0:\n stages.append(\" \".join(current_stage))\n current_stage = []\n continue\n\n if len(subsearch) > 0:\n current_stage.append(token.value)\n continue \n\n if token.type == \"PIPE\":\n if len(current_stage) > 0:\n stages.append(\" \".join(current_stage))\n current_stage = [token.value]\n continue\n \n current_stage.append(token.value)\n \n if len(current_stage) > 0:\n stages.append(\" \".join(current_stage))\n\n return stages", "def create(self, stage):\n return nx.Graph()", "def st_nodes(self):\n from spira.yevon.gdsii.sref import SRef\n from spira.yevon.geometry.ports import Port\n branch_nodes = list()\n for n in self.g.nodes():\n if 'device_reference' in self.g.node[n]:\n D = self.g.node[n]['device_reference']\n P = self.g.node[n]['process_polygon']\n # FIXME: Maybe implement node operators (__and__, etc)\n # if (D.purpose.symbol == 'B') and (P.layer.purpose.symbol == 'DEVICE_METAL'):\n # branch_nodes.append(n)\n if D.purpose.symbol == 'C':\n branch_nodes.append(n)\n elif D.purpose.symbol == 'D':\n branch_nodes.append(n)\n # elif D.purpose.symbol == 'P':\n # branch_nodes.append(n)\n elif D.purpose.symbol == 'T':\n branch_nodes.append(n)\n # elif (D.purpose.symbol == 'P') and (D.name[1] != 'E'):\n # branch_nodes.append(n)\n return branch_nodes", "def next_steps_for(self, step):\n self.expand_for(step)\n return self._adjacencies.get(step, [])" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plot filled region between `y1` and `y2`. This function works exactly the same as matplotlib's fill_between, except that it also plots a proxy artist (specifically, a rectangle of 0 size) so that it can be added it appears on a legend.
def fill_between(x, y1, y2=0, ax=None, **kwargs): ax = ax if ax is not None else plt.gca() ax.fill_between(x, y1, y2, **kwargs) p = plt.Rectangle((0, 0), 0, 0, **kwargs) ax.add_patch(p) return p
[ "def fill_between(x1, y1, x2, y2, x_axis_label=None, y_axis_label=None,\n x_axis_type='linear', y_axis_type='linear',\n title=None, plot_height=300, plot_width=450,\n fill_color='#1f77b4', line_color='#1f77b4', show_line=True,\n line_width=1, fill_alpha=1, line_alpha=1, p=None, **kwargs):\n if p is None:\n p = bokeh.plotting.figure(\n plot_height=plot_height, plot_width=plot_width,\n x_axis_type=x_axis_type, y_axis_type=y_axis_type,\n x_axis_label=x_axis_label, y_axis_label=y_axis_label, title=title)\n\n\n p.patch(x=np.concatenate((x1, x2[::-1])),\n y=np.concatenate((y1, y2[::-1])),\n alpha=fill_alpha,\n fill_color=fill_color,\n line_width=0,\n **kwargs)\n\n if show_line:\n p.line(x1,\n y1, \n line_width=line_width, \n alpha=line_alpha, \n color=line_color)\n p.line(x2, \n y2, \n line_width=line_width, \n alpha=line_alpha, \n color=line_color)\n\n return p", "def crtaj_fill(self, x, y1, y2, konfig):\r\n self.axes.fill_between(x,\r\n y1,\r\n y2,\r\n color=konfig.color,\r\n zorder=konfig.zorder,\r\n label=konfig.label)", "def fill_between(self, x, y1, y2=0, closed=True, where=None, interpolate=False,\n step=None, **kwargs):\n if closed:\n x = np.concatenate((x, [x[0]]))\n y1 = np.concatenate((y1, [y1[0]]))\n y2 = np.concatenate((y2, [y2[0]]))\n return super().fill_between(x, y1, y2, **kwargs)", "def fill(self, x, y, col=\"0.8\", label=None):\n self.ax.fill_between([x[0], x[1]], [y[1], y[1]], y[0], facecolor=col, alpha=0.5, label=label)", "def draw_line_mask(canvas, x1, y1, x2, y2, colour, threshold):\n dx = x2 - x1\n \"\"\"\n if not dx:\n # Vertical line\n draw_line((x1, y1, x2, y2), fill=col, width=1)\n return\n \"\"\"\n\n dy = y2 - y1\n steep = abs(dx) < abs(dy)\n if steep:\n x1, y1 = y1, x1\n x2, y2 = y2, x2\n dx, dy = dy, dx\n if x2 < x1:\n x1, x2 = x2, x1\n y1, y2 = y2, y1\n try:\n gradient = float(dy) / float(dx)\n except ZeroDivisionError:\n gradient = 1.0\n\n # Handle first endpoint\n xend = round(x1)\n yend = y1 + gradient * (xend - x1)\n xgap = rfpart(x1 + 0.5)\n xpxl1 = xend # this will be used in the main loop\n ypxl1 = ipart(yend)\n plot(canvas, xpxl1, ypxl1, steep, colour, rfpart(yend) * xgap, threshold)\n plot(canvas, xpxl1, ypxl1 + 1, steep, colour, fpart(yend) * xgap, threshold)\n intery = yend + gradient # first y-intersection for the main loop\n\n # handle second endpoint\n xend = round(x2)\n yend = y2 + gradient * (xend - x2)\n xgap = fpart(x2 + 0.5)\n xpxl2 = xend # this will be used in the main loop\n ypxl2 = ipart(yend)\n plot(canvas, xpxl2, ypxl2, steep, colour, rfpart(yend) * xgap, threshold)\n plot(canvas, xpxl2, ypxl2 + 1, steep, colour, fpart(yend) * xgap, threshold)\n\n # main loop\n for x in range(int(xpxl1 + 1), int(xpxl2)):\n plot(canvas, x, ipart(intery), steep, colour, rfpart(intery), threshold)\n plot(canvas, x, ipart(intery) + 1, steep, colour, fpart(intery), threshold)\n intery = intery + gradient", "def plot_yerr_filled(x, y=[None], axes=plt, color=(0,0,0), alpha=0.25, linestyle='-', *args, **kwargs):\n\ty_val = [None]*len(y)\n\ty_err = [None]*len(y)\n\tif y[0] != None:\n\t\tfor i in range(len(x)): # Validation of x\n\t\t\tif isinstance(x[i], uncertainties.UFloat):\n\t\t\t\tx[i] = x[i].n\n\t\tfor i in range(len(y)): # Validation of y\n\t\t\tif isinstance(y[i], uncertainties.UFloat):\n\t\t\t\ty_val[i] = y[i].n\n\t\t\t\ty_err[i] = y[i].s\n\t\t\telse:\n\t\t\t\ty_val[i] = y[i]\n\t\t\t\ty_err[i] = 0\n\telse:\n\t\ty = x;\n\t\tx = range(len(y))\n\t\tif isinstance(y[0], uncertainties.UFloat):\n\t\t\ty_val = [y[i].n for i in range(len(y))]\n\t\t\ty_err = [y[i].s for i in range(len(y))]\n\t\telse:\n\t\t\ty_val = y\n\t\t\ty_err = np.zeros(len(y))\n\taxes.fill_between(np.array(x), np.array(y_val)-np.array(y_err), np.array(y_val) + np.array(y_err), alpha=alpha, edgecolor=color, facecolor=color, linestyle=linestyle)\n\tlines = axes.plot(np.array(x), np.array(y_val), color=color, linestyle=linestyle, *args, **kwargs)\n\treturn lines", "def draw_cruved_rect(x1, x2, h1, h2, y1, y2, ax, fc='lightgray', ec='gray', lw=1, alpha=0.3):\n if h1 != 0 or h2 != 0:\n x05 = (x2+x1)/2\n v = np.array([[x1, y1],\n [x05, y1],\n [x05, y2],\n [x2, y2],\n [x2, y2 + h2],\n [x05, y2 + h2],\n [x05, y1 + h1],\n [x1, y1 + h1]])\n\n p = matplotlib.path.Path(v, codes = [1,4,4,4,2,4,4,4], closed=True)\n ax.add_patch(matplotlib.patches.PathPatch(p, lw=lw, ec=ec, fc=fc, alpha=alpha, zorder=-1))", "def plotyy(data1, data2=None, xname='dayrel', data1_styles=None,\n y2_opts={'color' : 'r', 'alpha' : 0.6, 'linewidth' : 2},\n xlims=None, xticks=None, ylims=None, yticks=None, y2_lims=None,\n xlabel='', y1_label='', y2_label='', legend=False,\n legend_kw={'fontsize' : 9, 'handlelength' : 2.5},\n x0_axvlines=None, grid=True):\n\n data1, data2 = atm.to_dataset(data1), atm.to_dataset(data2)\n\n for nm in data1.data_vars:\n if data1_styles is None:\n plt.plot(data1[xname], data1[nm], label=nm)\n elif isinstance(data1_styles[nm], dict):\n plt.plot(data1[xname], data1[nm], label=nm, **data1_styles[nm])\n else:\n plt.plot(data1[xname], data1[nm], data1_styles[nm], label=nm)\n atm.ax_lims_ticks(xlims, xticks, ylims, yticks)\n plt.grid(grid)\n if x0_axvlines is not None:\n for x0 in x0_axvlines:\n plt.axvline(x0, color='k')\n plt.xlabel(xlabel)\n plt.ylabel(y1_label)\n axes = [plt.gca()]\n\n if data2 is not None:\n plt.sca(plt.gca().twinx())\n for nm in data2.data_vars:\n plt.plot(data2[xname], data2[nm], label=nm, **y2_opts)\n if y2_lims is not None:\n plt.ylim(y2_lims)\n if 'linewidth' in y2_opts:\n y2_opts.pop('linewidth')\n atm.fmt_axlabels('y', y2_label, **y2_opts)\n atm.ax_lims_ticks(xlims, xticks)\n axes = axes + [plt.gca()]\n\n if legend:\n if data2 is None:\n plt.legend(**legend_kw)\n else:\n atm.legend_2ax(axes[0], axes[1], **legend_kw)\n\n return axes", "def _fill_between_x_or_y(\n self, ind_dir, ind, dep1, dep2=0, *,\n where=None, interpolate=False, step=None, **kwargs):\n # Common implementation between fill_between (*ind_dir*=\"x\") and\n # fill_betweenx (*ind_dir*=\"y\"). *ind* is the independent variable,\n # *dep* the dependent variable. The docstring below is interpolated\n # to generate both methods' docstrings.\n\n dep_dir = {\"x\": \"y\", \"y\": \"x\"}[ind_dir]\n\n if not mpl.rcParams[\"_internal.classic_mode\"]:\n kwargs = cbook.normalize_kwargs(kwargs, mcoll.Collection)\n if not any(c in kwargs for c in (\"color\", \"facecolor\")):\n kwargs[\"facecolor\"] = \\\n self._get_patches_for_fill.get_next_color()\n\n # Handle united data, such as dates\n ind, dep1, dep2 = map(\n ma.masked_invalid, self._process_unit_info(\n [(ind_dir, ind), (dep_dir, dep1), (dep_dir, dep2)], kwargs))\n\n for name, array in [\n (ind_dir, ind), (f\"{dep_dir}1\", dep1), (f\"{dep_dir}2\", dep2)]:\n if array.ndim > 1:\n raise ValueError(f\"{name!r} is not 1-dimensional\")\n\n if where is None:\n where = True\n else:\n where = np.asarray(where, dtype=bool)\n if where.size != ind.size:\n raise ValueError(f\"where size ({where.size}) does not match \"\n f\"{ind_dir} size ({ind.size})\")\n where = where & ~functools.reduce(\n np.logical_or, map(np.ma.getmaskarray, [ind, dep1, dep2]))\n\n ind, dep1, dep2 = np.broadcast_arrays(\n np.atleast_1d(ind), dep1, dep2, subok=True)\n\n polys = []\n for idx0, idx1 in cbook.contiguous_regions(where):\n indslice = ind[idx0:idx1]\n dep1slice = dep1[idx0:idx1]\n dep2slice = dep2[idx0:idx1]\n if step is not None:\n step_func = cbook.STEP_LOOKUP_MAP[\"steps-\" + step]\n indslice, dep1slice, dep2slice = \\\n step_func(indslice, dep1slice, dep2slice)\n\n if not len(indslice):\n continue\n\n N = len(indslice)\n pts = np.zeros((2 * N + 2, 2))\n\n if interpolate:\n def get_interp_point(idx):\n im1 = max(idx - 1, 0)\n ind_values = ind[im1:idx+1]\n diff_values = dep1[im1:idx+1] - dep2[im1:idx+1]\n dep1_values = dep1[im1:idx+1]\n\n if len(diff_values) == 2:\n if np.ma.is_masked(diff_values[1]):\n return ind[im1], dep1[im1]\n elif np.ma.is_masked(diff_values[0]):\n return ind[idx], dep1[idx]\n\n diff_order = diff_values.argsort()\n diff_root_ind = np.interp(\n 0, diff_values[diff_order], ind_values[diff_order])\n ind_order = ind_values.argsort()\n diff_root_dep = np.interp(\n diff_root_ind,\n ind_values[ind_order], dep1_values[ind_order])\n return diff_root_ind, diff_root_dep\n\n start = get_interp_point(idx0)\n end = get_interp_point(idx1)\n else:\n # Handle scalar dep2 (e.g. 0): the fill should go all\n # the way down to 0 even if none of the dep1 sample points do.\n start = indslice[0], dep2slice[0]\n end = indslice[-1], dep2slice[-1]\n\n pts[0] = start\n pts[N + 1] = end\n\n pts[1:N+1, 0] = indslice\n pts[1:N+1, 1] = dep1slice\n pts[N+2:, 0] = indslice[::-1]\n pts[N+2:, 1] = dep2slice[::-1]\n\n if ind_dir == \"y\":\n pts = pts[:, ::-1]\n\n polys.append(pts)\n\n collection = mcoll.PolyCollection(polys, **kwargs)\n\n # now update the datalim and autoscale\n pts = np.row_stack([np.column_stack([ind[where], dep1[where]]),\n np.column_stack([ind[where], dep2[where]])])\n if ind_dir == \"y\":\n pts = pts[:, ::-1]\n self.update_datalim(pts, updatex=True, updatey=True)\n self.add_collection(collection, autolim=False)\n self._request_autoscale_view()\n return collection", "def make_two_curve_plot(x_coords,\n y_coords1,\n y_coords2,\n y_name1,\n y_name2,\n x_label,\n y_label,\n title):\n pl.figure()\n # Added x- and y-limits for readability in the graphs\n pl.xlim([0, len(x_coords)])\n pl.ylim([0, max(y_coords1 + y_coords2) + 10])\n # pl.ylim([0, 900])\n # pl.ylim([0, 180])\n # Added colors and markers for readability in graphs\n pl.plot(x_coords, y_coords1, 'm-', label=y_name1)\n pl.plot(x_coords, y_coords2, 'c-.', label=y_name2)\n pl.legend()\n pl.xlabel(x_label)\n pl.ylabel(y_label)\n pl.title(title)\n pl.show()", "def set_rect(self, x1, y1, x2, y2):\n # the original shape has a extra point in the middle\n # of the line, which is the last tuple, I moved this point to the beginning:\n\n self.set_points([(x1, y1), (x2, y2), (x1, y1)])", "def align_yticks(ax1,ax2,color1=True,color2=True):\n \n # Get the data from the axes\n # Primary axis\n lims1 = ax1.get_ylim()\n ticks1 = ax1.get_yticks()\n \n # Secondary axis\n lims2 = ax2.get_ylim()\n ticks2 = ax2.get_yticks()\n \n # Non-dimensionalize the primary ticks\n oldTicks = (ticks1 - lims1[0])/(lims1[1] - lims1[0])\n \n # Set the new ticks\n newTicks = oldTicks * (lims2[1] - lims2[0]) + lims2[0]\n ax2.set_yticks(newTicks)\n \n # Set the limits again\n # This is relevant if there are ticks outside of the plotting window\n # I.E. newTicks < 0 or newTicks > 1\n ax2.set_ylim(lims2)\n \n # The new grid is now redundant\n ax2.grid('off')\n\n # Color the ticks and label based on the last plot color\n if color1:\n\n # get the last color plotted\n tmpHandle = ax1.get_lines()[-1]\n ax1.tick_params('y',colors=tmpHandle.get_color())\n ax1.set_ylabel(ax1.get_ylabel(),color=tmpHandle.get_color())\n \n # Color the ticks and label based on the last plot color\n if color2:\n \n # get the last color plotted\n tmpHandle = ax2.get_lines()[-1]\n ax2.tick_params('y',colors=tmpHandle.get_color())\n ax2.set_ylabel(ax2.get_ylabel(),color=tmpHandle.get_color())\n \n return ax1,ax2", "def my_draw_leg(self, theta1, theta2, alpha1, alpha2, ax=False):\n\n link1, link2, width = l1, l2, l_base\n cor_range = l1 + l2\n\n if ax == False:\n ax = plt.gca()\n ax.cla()\n\n ax.plot(-width / 2, 0, 'ok')\n ax.plot(width / 2, 0, 'ok')\n\n ax.plot([-width / 2, 0], [0, 0], 'k')\n ax.plot([width / 2, 0], [0, 0], 'k')\n\n ax.plot(-width / 2 + np.array([0, link1 * cos(theta1)]), [0, link1 * sin(theta1)], 'k')\n ax.plot(width / 2 + np.array([0, link1 * cos(theta2)]), [0, link1 * sin(theta2)], 'k')\n\n ax.plot(-width / 2 + link1 * cos(theta1) + np.array([0, link2 * cos(alpha1)]), \\\n link1 * sin(theta1) + np.array([0, link2 * sin(alpha1)]), 'k');\n ax.plot(width / 2 + link1 * cos(theta2) + np.array([0, link2 * cos(alpha2)]), \\\n np.array(link1 * sin(theta2) + np.array([0, link2 * sin(alpha2)])), 'k');\n\n curr_x = float(width / 2 + link1 * cos(theta2) + link2 * cos(alpha2))\n curr_y = float(np.array(link1 * sin(theta2) + link2 * sin(alpha2)))\n\n ax.plot(curr_x, curr_y, 'ro');\n\n ax.axis([-cor_range, cor_range, -l1, cor_range])\n ax.invert_yaxis()", "def plot_expression_overlap(self,g1,g2,axes=None,\n COLOR0='gray', COLOR1='#000098', COLOR2='#ffb900', COLOR3='#00ceb5',\n s0 = 1, s1 = 3, s2 = 3, s3 = 10,\n thr = 0.1,**kwargs):\n \n from matplotlib import cm\n from matplotlib.colors import to_rgba\n def hex_to_rgb(value):\n value = value.lstrip('#')\n lv = len(value)\n lv = list(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3))\n lv = [x/255 for x in lv]\n return lv\n \n sm = self\n \n nnm = sm.samap.adata.obsp['connectivities']\n su = nnm.sum(1).A.flatten()[:,None]\n su[su==0]=1\n\n nnm = nnm.multiply(1/su).tocsr()\n B1 = True\n if g1 not in sm.sam1.adata.var_names:\n if sm.id1+\"_\"+g1 not in sm.sam1.adata.var_names:\n if g1 not in sm.sam2.adata.var_names:\n if sm.id2+\"_\"+g1 not in sm.sam2.adata.var_names:\n raise ValueError(f\"{g1} not found in either dataset.\")\n else:\n a1 = sm.sam2.adata[:,sm.id2+\"_\"+g1].X.A.flatten()[:,None]\n B1=False\n else:\n a1 = sm.sam2.adata[:,g1].X.A.flatten()[:,None]\n B1=False\n else:\n a1 = sm.sam1.adata[:,sm.id1+\"_\"+g1].X.A.flatten()[:,None]\n else:\n a1 = sm.sam1.adata[:,g1].X.A.flatten()[:,None]\n \n B2=True\n if g2 not in sm.sam2.adata.var_names:\n if sm.id2+\"_\"+g2 not in sm.sam2.adata.var_names:\n if g2 not in sm.sam1.adata.var_names:\n if sm.id1+\"_\"+g2 not in sm.sam1.adata.var_names:\n raise ValueError(f\"{g2} not found in either dataset.\")\n else:\n a2 = sm.sam1.adata[:,sm.id1+\"_\"+g2].X.A.flatten()[:,None]\n B2=False\n else:\n a2 = sm.sam1.adata[:,g2].X.A.flatten()[:,None]\n B2=False\n else:\n a2 = sm.sam2.adata[:,sm.id2+\"_\"+g2].X.A.flatten()[:,None]\n else:\n a2 = sm.sam2.adata[:,g2].X.A.flatten()[:,None] \n\n d1 = np.append(a1,np.zeros(sm.sam2.adata.shape[0])) if B1 else np.append(np.zeros(sm.sam1.adata.shape[0]),a1)\n d2 = np.append(np.zeros(sm.sam1.adata.shape[0]),a2) if B2 else np.append(a2,np.zeros(sm.sam2.adata.shape[0]))\n\n davg1 = nnm.dot(d1).flatten()\n davg2 = nnm.dot(d2).flatten()\n davg1[davg1<thr]=0\n davg2[davg2<thr]=0\n \n davg3 = np.vstack((davg1,davg2)).min(0)\n ma = max([davg1.max(),davg2.max(),davg3.max()])\n if davg1.max()>0:\n davg1 = davg1/davg1.max()\n if davg2.max()>0:\n davg2 = davg2/davg2.max()\n if davg3.max()>0:\n davg3 = davg3/davg3.max() \n\n c1 = hex_to_rgb(COLOR1)+[0.0]\n c2 = hex_to_rgb(COLOR2)+[0.0]\n c3 = hex_to_rgb(COLOR3)+[0.0]\n\n c1 = np.vstack([c1]*davg1.size)\n c2 = np.vstack([c2]*davg1.size)\n c3 = np.vstack([c3]*davg1.size)\n c1[:,-1] = davg1# if not reverse else davg2\n c2[:,-1] = davg2# if not reverse else davg1\n c3[:,-1] = davg3\n\n ax = sm.samap.scatter(projection = 'X_umap', colorspec = COLOR0, axes=axes, s = s0)\n sm.samap.scatter(projection = 'X_umap', c = c1, axes = ax, s = s1,colorbar=False,**kwargs)\n sm.samap.scatter(projection = 'X_umap', c = c2, axes = ax, s = s2,colorbar=False,**kwargs)\n sm.samap.scatter(projection = 'X_umap', c = c3, axes = ax, s = s3,colorbar=False,**kwargs)\n return ax", "def shade_between(self, fobj1, fobj2=None, endpoints=None, color=None):\n\n shade_img = Image.new(\"RGBA\", (self.width, self.height), (0, 0, 0, 0))\n spix = shade_img.load()\n color = color if color else fobj1.pcolor\n\n fobj2 = fobj2 if fobj2 else self.x_axis\n if endpoints:\n endpoints = [self.pixel(n)[0] for n in endpoints]\n endpoints = [max(0, min(n, self.width - 1)) for n in endpoints]\n else:\n endpoints = (0, self.width - 1)\n\n for gx in xrange(*endpoints):\n f1val = fobj1(self.coord(gx)[0], self.gvars)\n f2val = fobj2(self.coord(gx)[0], self.gvars)\n\n f1pix = self.pixel(y=f1val)[1] # Pixel of 1st function value\n f2pix = self.pixel(y=f2val)[1] # Pixel of 2nd function value\n pix = [f1pix, f2pix]\n if None in pix:\n continue\n\n for gy in xrange(self.height - 1):\n if min(pix) <= gy <= max(pix):\n spix[gx, gy] = color\n\n alpha = shade_img.split()[3]\n alpha = ImageEnhance.Brightness(alpha).enhance(self.shade_opacity)\n shade_img.putalpha(alpha)\n self.gimg = Image.composite(shade_img, self.gimg, shade_img)\n self.gimg.save(self.fname)", "def _draw_legend(axes1, axes2):\n bars, barlabs = axes1.get_legend_handles_labels()\n times, timeslabs = axes2.get_legend_handles_labels()\n plt.legend(bars + times, barlabs + timeslabs, loc='best')", "def zoom_effect01(ax1, ax2, xmin, xmax, color='m', alpha_line=0.5,\n alpha_patch=0.15, loc1a=3, loc2a=2, loc1b=4, loc2b=1,\n linestyle='--', linewidth=1.5, xmin2=None, xmax2=None,\n alpha_patch2=None,ymin=0,ymax=1,ymin2=None,ymax2=None,\n **kwargs):\n\n trans1 = blended_transform_factory(ax1.transData, ax1.transAxes)\n trans2 = blended_transform_factory(ax2.transData, ax2.transAxes)\n\n xmin2 = xmin2 if xmin2 is not None else xmin\n xmax2 = xmax2 if xmax2 is not None else xmax\n\n ymin2 = ymin2 if ymin2 is not None else ymin\n ymax2 = ymax2 if ymax2 is not None else ymax\n\n\n alpha_patch2 = alpha_patch2 if alpha_patch2 is not None else alpha_patch\n\n bbox1 = Bbox.from_extents(xmin, ymin, xmax, ymax)\n bbox2 = Bbox.from_extents(xmin2, ymin2, xmax2, ymax2)\n\n mybbox1 = TransformedBbox(bbox1, trans1)\n mybbox2 = TransformedBbox(bbox2, trans2)\n\n prop_patches = kwargs.copy()\n prop_patches[\"ec\"] = \"none\"\n prop_patches[\"alpha\"] = alpha_patch\n prop_patches_2 = dict(**prop_patches)\n prop_patches_2[\"alpha\"] = alpha_patch2\n prop_lines = dict(color=color, alpha=alpha_line, linewidth=linewidth,\n linestyle=linestyle, **kwargs)\n c1, c2, bbox_patch1, bbox_patch2, p = \\\n connect_bbox(mybbox1, mybbox2,\n loc1a=loc1a, loc2a=loc2a, loc1b=loc1b, loc2b=loc2b,\n prop_lines=prop_lines, prop_patches=prop_patches,\n prop_patches_2=prop_patches_2)\n ax1.add_patch(bbox_patch1)\n ax2.add_patch(bbox_patch2)\n ax2.add_patch(c1)\n ax2.add_patch(c2)\n ax2.add_patch(p)\n\n return c1, c2, bbox_patch1, bbox_patch2, p", "def plot_xy(x1,x2,y,w0,w1,w2):\n class_1_x = []\n class_1_y = []\n class_0_x = []\n class_0_y = []\n\n for i in range(len(x1)):\n if y[i]==0:\n class_0_x.append(x1[i])\n class_0_y.append(x2[i])\n else:\n class_1_x.append(x1[i])\n class_1_y.append(x2[i])\n plot.figure(\"Decision Boundry\")\n plot.scatter(class_0_x, class_0_y, c='b', label='Class 0')\n plot.scatter(class_1_x, class_1_y, c='r', label='Class 1')\n\n x_1=[]\n min_=int(min(x1))\n max_=int(max(x1))\n for i in range(min_,max_,1):\n x_1.append(i)\n\n\n y_2=[]\n for i in range(len(x_1)):\n y_2.append(-(w0 + (w1 * x_1[i])) / w2)\n plot.plot(x_1, y_2, c='k', label='Decision Boundry')\n plot.xlabel('Independant Variable 1')\n plot.ylabel('Independant Variable 2')\n plot.legend()\n plot.show()", "def showTwoImages(img1, shift1, img2, shift2):\n fig = plt.figure(); plt.imshow(img1, origin='lower')\n fig = plt.figure(); plt.imshow(img2, origin='lower')\n fig = plt.figure()\n l1 = shift1[1]\n r1 = img1.shape[1]+shift1[1]\n b1 = shift1[0]\n t1 = img1.shape[0]+shift1[0]\n l2 = shift2[1]\n r2 = img2.shape[1]+shift2[1]\n b2 = shift2[0]\n t2 = img2.shape[0]+shift2[0]\n plt.imshow(img1, extent=(l1, r1, b1, t1), origin='lower')\n plt.imshow(img2, extent=(l2, r2, b2, t2), origin='lower', alpha=0.7)\n ax = fig.gca()\n ax.set_xlim([min(l1, l2), max(r1, r2)])\n ax.set_ylim([min(b1, b2), max(t1, t2)])", "def loss_visualisation_f2(min_x, min_y):\n x = getData_f2()\n y = f2(x)\n ax = plt.subplot(122)\n ax.plot(x, y)\n ax.set_xlabel('input')\n ax.set_ylabel('prediction (error)')\n ax.set_title('f2')\n ax.plot(min_x, min_y, markersize=10, marker='x')" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to save the csv file uploaded in html page to mysql df
def upload(): if request.method == 'POST': files = request.files['file'] # files.save('test.csv') data = pd.read_csv(files) obj = insert_to_mysql.MysqlIo() msg = obj.write_to_db(data) return render_template('message.html', msg=msg)
[ "def _saveCSV( self ):", "def upload_output(df_output):", "def filedownload(df):\r\n\r\n csv = df.to_csv(index=False)\r\n b64 = base64.b64encode(csv.encode()).decode() # strings <-> bytes conversions\r\n href = f'<a href=\"data:file/csv;base64,{b64}\" download=\"model_performance.csv\">Download CSV File</a>'\r\n return href", "def main():\n with open(\"dataset.csv\", \"r\") as fp:\n x = from_csv(fp) # read from csv by PT\n y = PrettyTable.get_html_string(x) # translate to html, PT\n table_html = y # store in var\n html_file=open('table.html','w') # create and write\n html_file=html_file.write(table_html) # add var html", "def csv_sync_db(req):\n if req.method == 'GET':\n with open('crawlResult.csv', 'r', encoding='utf-8-sig') as csvfile:\n reader = csv.reader(csvfile)\n for row in reader:\n if row[0] == '#': continue\n Product.objects.create(product_name=row[1], price=int(float(row[2])), category='', img_path=row[3])\n return HttpResponse('success', status=200)\n return HttpResponse('failed', status=404)", "def download_table(request, pk):\n filemeta = File.objects.get(pk=pk)\n sorted_category_list = json.loads(request.POST['sorted_category'])\n\n status = request.POST['file_saved_status']\n new_sorted_category_list = []\n\n for temp1 in sorted_category_list:\n # temp1 = [re.split(r\"([\\(])\", x)[0] for x in sublist]\n temp2 = [x.lstrip() for x in temp1]\n temp3 = [x.rstrip() for x in temp2]\n new_sorted_category_list.append(temp3)\n\n temp1 = filemeta.filename\n temp2 = os.path.splitext(temp1)\n custom_input_file_name = temp2[0]\n \n output_json_file_name = 'results__'+custom_input_file_name+'.csv'\n output_csv_file_path = os.path.join(MEDIA_ROOT, f'{filemeta.uploaded_by.organisation_name}/{filemeta.uploaded_by.user.username}/{filemeta.uploaded_date.date()}/output/{output_json_file_name}') \n\n # output_csv_file_path = filemeta.output_file_xlsx.path\n csv_file = pd.read_csv(output_csv_file_path, sep=',', header=0, encoding='utf-8-sig')\n\n if status == \"True\":\n filemeta.file_saved_status = True\n if 'Predicted_Category' in csv_file.columns:\n csv_file = csv_file.drop(\"Predicted_Category\", axis=1)\n csv_file.insert(0, \"Predicted_Category\", new_sorted_category_list)\n\n csv_file.to_csv(output_csv_file_path, index=False, encoding='utf-8-sig')\n\n filemeta.output_file_xlsx = output_csv_file_path\n filemeta.save()\n return HttpResponseRedirect(reverse('predict_csv', kwargs={\"pk\": filemeta.pk}))", "def handle_save_table(self): \n\n # Generates a dialog to get the file's name \n filename = unicode(QFileDialog.getSaveFileName(self, 'Save Table', '', \".csv(*.csv)\")) \n \n fcsv = file(filename, 'w')\n \n for currentRow in range(self.tablefrequency.rowCount()):\n \n a_0 = str(self.tablefrequency.item(currentRow, 0).text())\n a_1 = str(self.tablefrequency.item(currentRow, 1).text())\n a_2 = str(self.tablefrequency.item(currentRow, 2).text())\n a_3 = str(self.tablefrequency.item(currentRow, 3).text())\n \n fcsv.write(\"{0}, {1}, {2}, {3}\\n\".format(a_0, a_1, a_2, a_3))\n\n fcsv.close()", "def upload(request):\n return upload_view(request, CSVUploadForm, 'csv/upload.html', 'csv-preview', filetype=\"CSV\")", "def saveDataframe(df):\n current_date = datetime.datetime.now().strftime ('%d%b%Y-%H%M%S')\n current_folder = Path('.')\n csv_name = 'Comments_'+str(current_date)+'.csv'\n path_to_file = current_folder / 'output' / csv_name \n df.to_csv(path_to_file)\n print(\"file saved: \" + str(path_to_file))", "def on_toCsv_clicked(self):\n pth = self.path.text()\n print(pth)\n\n # Save data as .csv\n conn = sqlite3.connect('stock.db')\n stockModel = dm.StockModel(conn)\n stockModel.to_csv(pth)", "def save_data_to_csv(data_frame, csv_path):\n\tdata_frame.to_csv(csv_path, index=False)", "def process_csv(self, file_name: str):", "def POST_csv_data_to_db(csv_path):\n with open(csv_path, \"r\") as csv_file:\n\n # make list of headers off first line in csv\n headers = csv_file.readline().strip().lower().split(\",\")\n\n # need to skip data type line in csv\n _ = csv_file.readline()\n\n for line in csv_file:\n # turns headers and line values into \"header:line_value\" dict used in POST\n POST_data = dict(zip(headers, line.strip().split(\",\")))\n\n r = requests.post(\"http://localhost:8000/movies/\", data=POST_data)\n\n # raises error in script if request returns 400s or 500s\n r.raise_for_status()\n\n return", "def csv(self, request):\n buffer = io.BytesIO()\n filename = 'all_covid_history_data_{date}.csv'.format(date=datetime.date.today())\n GeneralData.objects.to_csv(buffer)\n response = HttpResponse(\n content_type='text/csv',\n status=200,\n )\n response.write(buffer.getvalue())\n response['Content-Disposition'] = 'attachment; filename={name}'.format(name=filename)\n return response", "def save_csv(self, df: pd.DataFrame, filename: str) -> None:\n fullname = self.absolute(filename)\n df.to_csv(fullname, index=False)", "def write_csv(self, df, file):\n blob_client = self.blobservice.get_blob_client(container=self.container_name, blob=file)\n output = df.to_csv(index=False, encoding='utf-8')\n return blob_client.upload_blob(output, blob_type='BlockBlob', overwrite=True)", "def test_export_csv_to_file(self):\n pass", "def save_csv(self, file_name, path = \"../data/clustered_microtrips/\"):\n if 'cluster' in self.df.columns:\n file_name = path + file_name + \".csv\"\n self.df.to_csv(file_name, sep=\";\")", "def get_table_download_link(df):\n csv = df.to_csv(index=False)\n b64 = base64.b64encode(csv.encode()).decode() # some strings <-> bytes conversions necessary here\n href = f'<a href=\"data:file/csv;base64,{b64}\" download=\"new_dataset.csv\">Download csv file</a>'\n return href" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method will check to see if going to the next or previous month will change the year and returns the corrected month and year. month the month to see if it is in the same year year the year that you are checking return month,year the corrected values of each
def monthConversion(month,year): if(month > 12): year+=1 month = 1 if(month < 1): year-=1 month = 12 return month,year
[ "def prev_month(month, year):\n prev_month = (month - 1) % 13\n prev_year = year\n if prev_month == 0:\n prev_month = 12\n prev_year -= 1\n return (prev_month, prev_year)", "def _check_year(self):\n if (self.last_team_update[0] < date.today().year):\n self.last_team_update[0] = date.today().year\n self.last_team_update[1] = 1", "def next_month(self, start_date):\n current = start_date.month\n potential = [m for m in self.months if m >= current]\n year_wraps = 0\n\n while True:\n if not potential:\n year_wraps += 1\n potential = list(self.months)\n\n yield potential.pop(0), start_date.year + year_wraps", "def get_next_month_year() -> str:\n today = datetime.datetime.today()\n year = today.year\n\n # Make sure January follows December!\n if today.month + 1 == 13:\n month = 1\n year += 1\n else:\n month = today.month + 1\n\n future = datetime.datetime.replace(today, month=month, year=year)\n return datetime.datetime.strftime(future, \"%b-%Y\")", "def advance(self):\n max_days = self.months[self.month - 1]\n if self.month == 2 and self.leapyear(self.year):\n max_days += 1\n if self.day == max_days:\n self.day = 1\n if self.month == 12:\n self.month = 1\n self.year += 1\n else:\n self.month += 1\n else:\n self.day += 1", "def test_Year(months):\n assert months[0].Year == ttcal.Year(2012)\n assert months[0].Month == months[0]", "def increment_month():\n global months\n global numMonths\n global monthNums\n if month == \"December\":\n month = \"January\"\n year += 1\n else:\n month = numMonths[monthNums[month] + 1]", "def test_2_from_31st_jan(self):\n input = datetime.datetime(2014, 1, 31)\n expected_output = datetime.datetime(2014, 7, 31)\n output = onthisday.six_months_from(input)\n self.assertEqual(expected_output, output)", "def calendar(month: int, year: int) -> str:\n# if month == 10 and year == 2020:\n# a = \"mon tue wed thu fri sat sun\\n\\\n# 1 2 3 4\\n\\\n# 5 6 7 8 9 10 11\\n\\\n# 12 13 14 15 16 17 18\\n\\\n# 19 20 21 22 23 24 25\\n\\\n# 26 27 28 29 30 31\"\n# return a\n# if month == 2 and year == 2016:\n# b = \"mon tue wed thu fri sat sun\\n\\\n# 1 2 3 4 5 6 7\\n\\\n# 8 9 10 11 12 13 14\\n\\\n# 15 16 17 18 19 20 21\\n\\\n# 22 23 24 25 26 27 28\\n\\\n# 29\"\n# return b\n# if month == 12 and year == 2021:\n# c = \"mon tue wed thu fri sat sun\\n\\\n# 1 2 3 4 5\\n\\\n# 6 7 8 9 10 11 12\\n\\\n# 13 14 15 16 17 18 19\\n\\\n# 20 21 22 23 24 25 26\\n\\\n# 27 28 29 30 31\"\n# return c\n# if month == 2 and year == 2021:\n# d = \"mon tue wed thu fri sat sun\\n\\\n# 1 2 3 4 5 6 7\\n\\\n# 8 9 10 11 12 13 14\\n\\\n# 15 16 17 18 19 20 21\\n\\\n# 22 23 24 25 26 27 28\"\n# return d\n if month == 10 and year == 2020:\n a = \"mon tue wed thu fri sat sun\\n\\\n 1 2 3 4\\n\\\n 5 6 7 8 9 10 11\\n\\\n 12 13 14 15 16 17 18\\n\\\n 19 20 21 22 23 24 25\\n\\\n 26 27 28 29 30 31\"\n return a\n if month == 2 and year == 2016:\n b = \"mon tue wed thu fri sat sun\\n\\\n 1 2 3 4 5 6 7\\n\\\n 8 9 10 11 12 13 14\\n\\\n 15 16 17 18 19 20 21\\n\\\n 22 23 24 25 26 27 28\\n\\\n 29\"\n return b\n if month == 12 and year == 2021:\n c = \"mon tue wed thu fri sat sun\\n\\\n 1 2 3 4 5\\n\\\n 6 7 8 9 10 11 12\\n\\\n 13 14 15 16 17 18 19\\n\\\n 20 21 22 23 24 25 26\\n\\\n 27 28 29 30 31\"\n return c\n if month == 2 and year == 2021:\n d = \"mon tue wed thu fri sat sun\\n\\\n 1 2 3 4 5 6 7\\n\\\n 8 9 10 11 12 13 14\\n\\\n 15 16 17 18 19 20 21\\n\\\n 22 23 24 25 26 27 28\"\n return d", "def relative_year(month, day):\n t = today()\n # If incoming date is Jan 1st\n if month == 1 and day == 1:\n # and current UTC is Dec 31st,\n # then increment the current year\n if t.month == 12 and t.day == 31:\n return t.year + 1\n return t.year", "def month_year_iter(start_month, start_year, end_month, end_year):\n ym_start= 12 * start_year + start_month - 1\n ym_end= 12 * end_year + end_month - 1\n for ym in range(ym_start, ym_end):\n y, m = divmod(ym, 12)\n yield y, m+1", "def change_month(self, event):\n if event.keysym == \"Right\":\n if self.calendar.month < 12:\n self.calendar.month += 1\n else:\n self.calendar.year += 1\n self.calendar.month = 1\n elif event.keysym == \"Left\":\n if self.calendar.month > 1:\n self.calendar.month -= 1\n elif self.calendar.year > 1970:\n self.calendar.year -= 1\n self.calendar.month = 12\n\n self.update_calendar()", "def next_first_of_month_in_20th():\n first = date(1901, 1, 1)\n yield first\n while first.year < 2001:\n if first.month == 12:\n first = first.replace(year=first.year + 1)\n first = first.replace(month=1)\n else:\n first = first.replace(month=first.month + 1)\n yield first", "def next_year(self):\r\n \r\n if self._selection_is_visible: self._clear_selection()\r\n\r\n self._build_calendar(self._year+1, self._month) # reconstruct calendar\r", "def month_year_iter(start_month, start_year, end_month, end_year):\n ym_start = 12 * start_year + start_month - 1\n ym_end = 12 * end_year + end_month\n for ym in range(ym_start, ym_end):\n y, m = divmod(ym, 12)\n yield y, m + 1", "def getNumberOfMonths(self,datepair) -> int:\n # if years\n # if years\n date2_parsed = False\n if datepair.get(\"fh\", None) is not None:\n gap = datepair[\"fh\"]\n else:\n gap = \"\"\n try:\n present_vocab = (\"present\", \"date\", \"now\")\n if \"syear\" in datepair:\n date1 = datepair[\"fyear\"]\n date2 = datepair[\"syear\"]\n\n if date2.lower() in present_vocab:\n date2 = datetime.now()\n date2_parsed = True\n\n try:\n if not date2_parsed:\n date2 = datetime.strptime(str(date2), \"%Y\")\n date1 = datetime.strptime(str(date1), \"%Y\")\n except:\n pass\n elif \"smonth_num\" in datepair:\n date1 = datepair[\"fmonth_num\"]\n date2 = datepair[\"smonth_num\"]\n\n if date2.lower() in present_vocab:\n date2 = datetime.now()\n date2_parsed = True\n\n for stype in (\"%m\" + gap + \"%Y\", \"%m\" + gap + \"%y\"):\n try:\n if not date2_parsed:\n date2 = datetime.strptime(str(date2), stype)\n date1 = datetime.strptime(str(date1), stype)\n break\n except:\n pass\n else:\n date1 = datepair[\"fmonth\"]\n date2 = datepair[\"smonth\"]\n\n if date2.lower() in present_vocab:\n date2 = datetime.now()\n date2_parsed = True\n\n for stype in (\n \"%b\" + gap + \"%Y\",\n \"%b\" + gap + \"%y\",\n \"%B\" + gap + \"%Y\",\n \"%B\" + gap + \"%y\",\n ):\n try:\n if not date2_parsed:\n date2 = datetime.strptime(str(date2), stype)\n date1 = datetime.strptime(str(date1), stype)\n break\n except:\n pass\n\n months_of_experience = relativedelta.relativedelta(date2, date1)\n months_of_experience = (\n months_of_experience.years * 12 + months_of_experience.months\n )\n return months_of_experience\n except Exception as e:\n return 0", "def prev_year(self):\r\n \r\n if self._selection_is_visible: self._clear_selection()\r\n\r\n self._build_calendar(self._year-1, self._month) # reconstruct calendar\r", "def calc_date(y: int, m: int):\n birth_year = y\n birth_month = m\n\n total_months = months_to_retire(birth_year)\n years_to_add, months_to_add = calc_retirement_age(total_months)\n\n # find retirement year\n retire_year = birth_year + years_to_add\n\n # find retirement month, correct year if needed\n retire_month = birth_month + months_to_add\n if retire_month > 12:\n retire_year += 1\n retire_month = retire_month - 12\n\n return retire_year, retire_month", "def same_month(self):\n return self.is_same_month" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate rapidity as a function of pesudorapidity, transverse momentum and mass
def rapidity(eta, pt, m): return np.log((np.sqrt(m**2 + pt**2 * np.cosh(eta)**2) + pt * np.sinh(eta)) / np.sqrt(m**2 + pt**2))
[ "def momentum_resolution(p) :\n return 0.005", "def _get_continuum_mass_estimate(self):\n\n pass", "def calculate_speed_enhancement_factor(particle_mass, molecular_mass):\n\n return ((particle_mass + molecular_mass) / particle_mass) ** 0.5", "def calc_motive(self):\n # For brevity, \"dimensionless\" prefix omitted from \"position\" and \"motive\" variable names.\n \n self[\"motive_data\"] = {}\n self[\"motive_data\"][\"dps\"] = DimensionlessLangmuirPoissonSoln()\n\n self[\"motive_data\"][\"spclmbs_max_dist\"] = self.calc_spclmbs_max_dist()\n self[\"motive_data\"][\"saturation_pt\"] = self.calc_saturation_pt()\n self[\"motive_data\"][\"virt_critical_pt\"] = self.calc_virt_critical_pt()\n\n if self.calc_output_voltage() < self[\"motive_data\"][\"saturation_pt\"][\"output_voltage\"]:\n # Accelerating mode.\n self[\"motive_data\"][\"max_motive_ht\"] = self[\"Emitter\"].calc_barrier_ht()\n elif self.calc_output_voltage() > self[\"motive_data\"][\"virt_critical_pt\"][\"output_voltage\"]:\n # Retarding mode.\n self[\"motive_data\"][\"max_motive_ht\"] = self[\"Collector\"].calc_barrier_ht()\n else:\n # Space charge limited mode.\n output_current_density = optimize.brentq(self.output_voltage_target_function,\\\n self[\"motive_data\"][\"saturation_pt\"][\"output_current_density\"],\\\n self[\"motive_data\"][\"virt_critical_pt\"][\"output_current_density\"])\n \n barrier = physical_constants[\"boltzmann\"] * self[\"Emitter\"][\"temp\"] * \\\n np.log(self[\"Emitter\"].calc_saturation_current_density()/output_current_density)\n self[\"motive_data\"][\"max_motive_ht\"] = barrier + self[\"Emitter\"].calc_barrier_ht()", "def demand(p, a=200, b=10, d=10, t=np.linspace(1,10,10)):\n\n return 1.0 / b * ( a - p * ( d + t ) / d )", "def mass(self):\n return self.volume * self.rho", "def momentum_thrust(self, M0, M4):\n\t\ta0 = self.speed_of_sound()\n\t\tf = self.fuel_ratio(M0=M0)\n\t\treturn a0 * M0 * ((1 + f) * (M4 / M0) * (self.T3t**0.5 / self.T0**0.5) * (1 / (1 + (self.gamma - 1) / 2 * M0**2)**0.5) - 1)", "def get_initial_mass(self):\r\n\t\treturn np.sum(self.values) * self.mass_ratio", "def measureMomentumSpreadCalc(self):\n #if self.view.checkBox_4_s.isChecked()==True:\n self.beamSigma = self.cam.getSigX(self.C2Vcam)\n self.Is = self.beamSigma/self.Dispersion\n self.pSpread = self.func.calcMomSpread(self.Cmagnets,self.dipole,self.Is,self.data.values['I_rough'])\n print str(datetime.datetime.now())[:-7], ', Momentum spread =', self.pSpread, 'MeV/c, =>', 100*self.pSpread/self.data.values['I_rough'], '%'\n\n #a = self.func.calcMomSpread(self.Cmagnets,'DIP01',self.Is,self.I)\n #print a\n #else:\n # print 'Not confirmed momentum measurement'", "def mass(self):\n return 4 / 3 * np.pi * self.radius ** 3 * self.rho", "def calculate_mass(self):\n\n atomic_symbols = [xyz[0] for xyz in self.xyzs]\n masses_amu = [Constants.atomic_masses[elm] for elm in atomic_symbols]\n\n return Constants.amu_to_kg * sum(masses_amu)", "def effective_mass(particle_object):\n\tparticle_mass = particle_object.mass\n\tamu_in_kg = const.atomic_mass\n\n\tm_hydrogen = 1.008\n\tm_particle = particle_mass\n\n\tm_effective = amu_in_kg * m_particle * m_hydrogen / (m_particle + m_hydrogen)\n\treturn amu_in_kg * m_hydrogen", "def kinetic_energy(ctx: Context, momentum: Q_, mass: Q_) -> Q_:\n return 0.5 * ctx.sum(momentum * momentum / mass)", "def f_molGas_dyn(self):\n# print self.M_gas, self.M_dyn\n return self.M_gas / self.M_dyn", "def calc_speedofsound(self, p, rho):\n from math import sqrt\n ga = self.ga\n return sqrt(ga*p/rho)", "def timescale_perihelion_precession(a,e,M):\n\tG = 3.9652611e-14 # G in au,solar mass, seconds\n\tc = 0.0020039888 # C in au/sec\n\n\treturn c**2 * a**2.5 * (1 - e**2) / (3*(G*M)**1.5)", "def total_momentum(particles):\n ptot = Vector([0, 0, 0])\n\n for p in particles:\n ptot += p.v*p.m\n\n return ptot", "def calcMass(time, mag_abs, velocity, tau=0.007, P_0m=840.0):\n\n # Theory:\n # I = P_0m*10^(-0.4*M_abs)\n # M = (2/tau)*integral(I/v^2 dt)\n\n # Compute the radiated energy\n intens_int = calcRadiatedEnergy(time, mag_abs, P_0m=P_0m)\n\n # Calculate the mass\n mass = (2.0/(tau*velocity**2))*intens_int\n\n return mass", "def reward_mass_bkg(self, mass):\n #massdiff = abs(mass - self.massgoal)\n #x = abs(massdiff/self.mass_width_bkg)\n #return x*x/(math.pi*(1.0 + (x*x)))\n x = abs(mass/self.mass_width_bkg)\n return x*np.exp(-x)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Configures all the main windows menues
def _setupMenues(self): self._menues["file"] = qt.QPopupMenu(self) self.menuBar().insertItem('&File',self._menues["file"]) self._actions["exit-faraday"].addTo(self._menues["file"]); self.menuBar().insertSeparator() self._menues["shell"] = qt.QPopupMenu(self) self.menuBar().insertItem('&Shell',self._menues["shell"]) self._actions["new_shell"].addTo(self._menues["shell"]); self._actions["close_shell"].addTo(self._menues["shell"]); self._actions["maximize-shell"].addTo(self._menues["shell"]); self.menuBar().insertSeparator() self._menues["edit"] = qt.QPopupMenu(self) self.menuBar().insertItem('&Edit',self._menues["edit"]) self._menues["edit"].insertItem('&Copy', self._copy) self._menues["edit"].insertItem('&Paste', self._paste) self._actions["repo-config"].addTo(self._menues["edit"]); self.menuBar().insertSeparator() self._menues["workspace"] = qt.QPopupMenu(self) self.menuBar().insertItem('&Workspace',self._menues["workspace"]) # self._actions["open-workspace"].addTo(self._menues["workspace"]) self._actions["create-workspace"].addTo(self._menues["workspace"]) self.menuBar().insertSeparator() self._menues["tools"] = qt.QPopupMenu(self) self.menuBar().insertItem('&Tools',self._menues["tools"]) self._actions["visualization"].addTo(self._menues["tools"]); self._actions["plugin"].addTo(self._menues["tools"]); self._actions["screenshot"].addTo(self._menues["tools"]); self.menuBar().insertSeparator() self._menues["view"] = qt.QPopupMenu(self) self.menuBar().insertItem('&View',self._menues["view"]) self._actions["toggle-hosttree"].addTo(self._menues["view"]); self._actions["toggle-logconsole"].addTo(self._menues["view"]); self._actions["maximize-shell"].addTo(self._menues["view"]); self.menuBar().insertSeparator() self._menues["help"] = qt.QPopupMenu(self) self.menuBar().insertItem('&Help',self._menues["help"]) self._menues["help"].insertItem('&About', self._showAboutDialog) self._actions["documentation"].addTo(self._menues["help"]);
[ "def _initMenu(self):\n #--- Menu Project ---#\n self.mi_newProject.setShortcut(\"Ctrl+Shift+N\")\n self.mi_newProject.triggered.connect(self.on_miNewProject)\n self.mi_loadProject.setShortcut(\"Ctrl+Shift+L\")\n self.mi_loadProject.triggered.connect(self.on_miLoadProject)\n #--- Menu Settings ---#\n self.mi_toolSettings.setShortcut(\"Ctrl+Shift+T\")\n self.mi_toolSettings.triggered.connect(self.on_miToolSettings)\n self.mi_projectSettings.setShortcut(\"Ctrl+Shift+P\")\n self.mi_projectSettings.triggered.connect(self.on_miProjectSettings)\n #--- Menu Help ---#\n #- Log Level\n for level in self.log.levels:\n menuItem = self.m_logLevel.addAction(level)\n menuItem.setCheckable(True)\n menuItem.triggered.connect(partial(self.on_miLogLevel, level))\n self.on_miLogLevel(self.log.level)\n #- Style\n for style in pQt.Style().styles:\n menuItem = self.m_style.addAction(style)\n menuItem.setCheckable(True)\n menuItem.triggered.connect(partial(self.on_miStyle, style))\n self.on_miStyle('darkGrey')", "def menu_bar(self):\n\n mv_logger.debug('MainView.menubar')\n\n color = [\"red\", \"green\", \"blue\", \"yellow\", \"cyan\", \"magenta\", \"white\", \"black\"]\n fonts = ['times 8', 'times 10', 'times 12', 'times 14', 'times 16', 'times 18', \n 'times 20', 'times 24', 'times 26', 'times 28', 'times 36', 'times 48']\n\n self.menubar = tk.Menu(self)\n self.dropdown_menu = tk.Menu(self.menubar, tearoff=0)\n self.font_color = tk.Menu(self.menubar)\n self.font_menu = tk.Menu(self.menubar)\n\n for c in color:\n self.dropdown_menu.add_command(label=c, command=lambda c=c: self.change_window('bg', c))\n self.font_color.add_command(label=c, command=lambda c=c: self.change_window('fg', c))\n\n\n for f in fonts:\n self.font_menu.add_command(label=f, command=lambda f=f: self.change_window('font', f))\n\n self.menubar.add_cascade(label='bg color', menu=self.dropdown_menu)\n self.menubar.add_cascade(label='Font size', menu=self.font_menu)\n self.menubar.add_cascade(label='Font color', menu=self.font_color)\n\n self.master.config(menu=self.menubar)", "def init_main_window(self, window):\n self.window = window\n self.setupUi(window)\n self.init_main_widgets()\n self.force_titles()", "def create_menubar(self):\n # The file menu\n self.file_menu = self.menuBar().addMenu(\"&File\")\n quit_action = create_action(self,\"&Quit\", slot=self.quit,\n shortcut=\"Ctrl+Q\", tip=\"Close the application\")\n add_actions(self.file_menu, (None, quit_action))\n\n # The configuration menu\n self.config_menu = self.menuBar().addMenu(\"&Config\")\n create_option_menu(self,\n self.config_menu,\n \"&Logging level\",\n self.set_loglevel,\n ['Debug','Info','Warning','Error','Critical'])\n \n create_option_menu(self,\n self.config_menu,\n \"&Plot window\",\n self.make_plot_window,\n self.roach_keys+['all'])\n create_option_menu(self,\n self.config_menu,\n \"Power &Scale\",\n self.set_power_scale,\n [\"Linear\",\"Logarithmic\"])\n create_option_menu(self,\n self.config_menu,\n \"&Refresh timer\",\n self.timer_action,\n [\"Start\", \"Stop\"])\n # The help menu\n self.help_menu = self.menuBar().addMenu(\"&Help\")\n about_action = create_action(self,\"&About\",\n shortcut='F1', slot=self.on_about,\n tip='About the demo')\n add_actions(self.help_menu, (about_action,))", "def init_main_window(self):\r\n gui_main = Tk()\r\n gui_main.geometry(f\"{WIDTH}x{HEIGHT}\")\r\n gui_main.resizable(width=False, height=False)\r\n gui_main.title(\"HUJI Boggle!\")\r\n gui_main.configure(background=BG_COLOR)\r\n return gui_main", "def createMenus(self):\n\t\tself.fileMenu = self.menuBar().addMenu(\"&File\")\n\t\tself.editMenu = self.menuBar().addMenu(\"&Edit\")\n\t\tself.helpMenu = self.menuBar().addMenu(\"&Help\")", "def updateMenuAndWindowTitle(self):\n self.updateMenu()\n self.updateWindowTitle()", "def initMenus(self):\n menu_items = eval(file_io.load_config(MENU_FILE))\n menubar = self.menuBar()\n\n for menu in menu_items:\n newMenu = menubar.addMenu(menu[0])\n for action in menu[1]:\n if action[\"name\"] == \"sep\":\n newMenu.addSeparator()\n continue\n newAction = QtGui.QAction(action[\"name\"], self)\n newAction.setShortcut(action[\"shortcut\"])\n newAction.setStatusTip(action[\"tip\"])\n newAction.triggered.connect(action[\"cb\"])\n newMenu.addAction(newAction)", "def CreateExteriorWindowComponents(self):\r\n self.CreateMenu()\r\n self.CreateStatusBar()", "def setupMenu(self):\n print(f'\\nsetupMenu')\n # Create actions for file menu\n open_act = QAction('Open...', self)\n open_act.setShortcut('Ctrl+O')\n open_act.triggered.connect(self.openImageFile)\n\n save_act = QAction('Save', self)\n save_act.setShortcut('Ctrl+S')\n save_act.triggered.connect(self.saveImageFile)\n\n # Create menu bar\n menu_bar = self.menuBar()\n menu_bar.setNativeMenuBar(False)\n\n # Create file menu and add actions\n file_menu = menu_bar.addMenu('File')\n file_menu.addAction(open_act)\n file_menu.addAction(save_act)", "def apply_defaults(self):\n # reset window geometry\n self.parent.update_idletasks()\n w = self.parent.winfo_screenwidth()\n h = self.parent.winfo_screenheight()\n rootsize = (self.DEFAULT_GUI_MIN_WIDTH, self.DEFAULT_GUI_MIN_HEIGHT)\n x = w / 2 - rootsize[0] / 2\n y = h / 2 - rootsize[1] / 2\n self.prefs[\"window_geometry\"] = \"%dx%d+%d+%d\" % (rootsize + (x, y))\n # reset tags\n self.prefs[\"tags\"] = self.DEFAULT_TAGS\n self.prefs[\"mo_class\"] = self.DEFAULT_MO_CLASS\n self.prefs[\"nomo_class\"] = self.DEFAULT_NOMO_CLASS\n self.prefs[\"id_regex\"] = self.DEFAULT_ID_REGEX\n self.prefs[\"id_format\"] = self.DEFAULT_ID_FORMAT\n self.prefs[\"existing_ids_only\"] = self.DEFAULT_EXISTING_IDS_ONLY\n self.prefs[\"save_directory\"] = self.DEFAULT_SAVE_DIRECTORY", "def _add_menus(self):\r\n self.menu_bar.Append(self.mfile, \"&File\")\r\n self.menu_bar.Append(self.medit, \"&Edit\")\r\n self.menu_bar.Append(self.mview, \"&View\")", "def _configureCB(self):\n self.oAppMenubar.filemenu.add_command(label='Open <Ctrl+o>', underline=0, command=self.oToolbar.oAppToolbar.BtnOpenFile.invoke)\n self.oAppMenubar.filemenu.add_command(label='Status <Ctrl+t>', underline=0, command=self.oToolbar.oAppToolbar.BtnInitXplore.invoke)\n self.oAppMenubar.filemenu.add_command(label='Quit', underline=0, command=self.oToolbar.oAppToolbar.BtnExit.invoke)\n self.oAppMenubar.settingsmenu.add_command(label='Global Settings', underline=0, command=self.wGlobSettingsCB)\n self.oAppMenubar.utilitiesmenu.add_command(label='More', underline=0, command=None)\n self.oAppMenubar.calibrationmenu.add_command(label='Current Source', underline=0, command=self.vCurrentSourceCalibCB)\n self.oAppMenubar.calibrationmenu.add_command(label='Voltage Source', underline=0, command=self.vVoltageSourceCalibCB)\n self.oAppMenubar.calibrationmenu.add_command(label='Current Measure', underline=0, command=self.vCurrentMeasureCalibCB)\n self.oAppMenubar.calibrationmenu.add_command(label='Voltage Measure', underline=0, command=self.vVoltageMeasureCalibCB)\n self.oAppMenubar.helpmenu.add_command(label='About', underline=0, command=self.vAboutInQCB)\n self.oAppMenubar.helpmenu.add_command(label='Keyboard Shortcuts', underline=0, command=self.vKBSCCB)\n self.oAppMenubar.helpmenu.add_command(label='Xplore User Manual<F1>', underline=0, command=self.vInQHelpCB)\n self.oAppMenubar.helpmenu.add_command(label='HowTO Videos', underline=0, command=self.vHowTOVideosCB)\n self.Export_Instance = 0\n self.About_Instance = 0\n self.KBSC_Instance = 0\n self.CalibIS_Instance = 0\n self.CalibVS_Instance = 0\n self.CalibIM_Instance = 0\n self.CalibVM_Instance = 0\n return", "def apply_config(self):\n # window location\n try:\n wx = self.config['Main']['window x']\n wy = self.config['Main']['window y']\n self.master.geometry('+{}+{}'.format(wx,wy))\n except:\n print('No previous window location found.\\n')\n\n # work directory\n try:\n os.chdir(self.config['Main']['work directory'])\n self.cwd = os.getcwd()\n self.show_cwd()\n except:\n print('No previous work directory found.\\n')\n self.chdir()\n\n self.show_daqconfig()", "def _setupMainToolbar(self):\n self._actions[\"new_shell\"].addTo(self.main_toolbar)\n self._actions[\"toggle-hosttree\"].addTo(self.main_toolbar)\n self._actions[\"toggle-logconsole\"].addTo(self.main_toolbar)\n self._actions[\"maximize-shell\"].addTo(self.main_toolbar)\n\n self._actions[\"clear-hosttree\"].addTo(self.main_toolbar)\n self._actions[\"repo-config\"].addTo(self.main_toolbar)\n self._actions[\"visualization\"].addTo(self.main_toolbar)\n self._actions[\"plugin\"].addTo(self.main_toolbar)\n self._actions[\"screenshot\"].addTo(self.main_toolbar)\n self._actions[\"sfont\"].addTo(self.main_toolbar)\n self._actions[\"bfont\"].addTo(self.main_toolbar)\n if CONF.getDebugStatus():\n self._actions[\"debug\"].addTo(self.main_toolbar)", "def gui_conf():\n\n title = 'GUI'\n\n content = {\n\n title: {\n 'theme': 'DarkBlack1',\n 'icon_set': 'midnite',\n 'template': '',\n 'grab_anywhere': 'True',\n 'advanced_mode': 'False'\n },\n }\n\n return content", "def browser_menu():\n def on_setup_menus(browser):\n \"\"\"\n on browser setupMenus was called\n \"\"\"\n # main menu\n menu = browser.form.menubar.addMenu(\"Import Video\")\n\n # import\n action = QAction(APP_ICON, _(\"IMPORT_VIDEO\"), mw)\n action.triggered.connect(lambda: show_dialog())\n menu.addAction(action)\n\n # check update\n action = QAction(_('CHECK_UPDATE'), browser)\n action.triggered.connect(lambda: check_updates(background=False, parent=browser))\n menu.addAction(action)\n\n # About\n action = QAction(_('ABOUT'), browser)\n action.triggered.connect(lambda: show_about_dialog(browser))\n menu.addAction(action)\n\n addHook('browser.setupMenus', on_setup_menus)", "def init_ui(self, ):\n self.mm = MenuManager.get()\n p = self.mm.menus['Jukebox']\n self.menu = self.mm.create_menu(\"Genesis\", p, command=self.run)", "def __initMenus(self):\n self.__menuItems=[\"Login\", \"Play\", \"Setup\", \"Quit\"]\n #self.__menuItems=[\"Login\", \"Play\", \"Single Player\", \"Multiplayer\", \"Setup\", \"Quit\"]" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets up the main toolbar
def _setupMainToolbar(self): self._actions["new_shell"].addTo(self.main_toolbar) self._actions["toggle-hosttree"].addTo(self.main_toolbar) self._actions["toggle-logconsole"].addTo(self.main_toolbar) self._actions["maximize-shell"].addTo(self.main_toolbar) self._actions["clear-hosttree"].addTo(self.main_toolbar) self._actions["repo-config"].addTo(self.main_toolbar) self._actions["visualization"].addTo(self.main_toolbar) self._actions["plugin"].addTo(self.main_toolbar) self._actions["screenshot"].addTo(self.main_toolbar) self._actions["sfont"].addTo(self.main_toolbar) self._actions["bfont"].addTo(self.main_toolbar) if CONF.getDebugStatus(): self._actions["debug"].addTo(self.main_toolbar)
[ "def create_toolbars(self):\n self.create_tools()\n self.plugin_manager.create_toolbars()", "def __init__(self, *args):\n _aui.AuiToolBar_swiginit(self,_aui.new_AuiToolBar(*args))", "def create_tool_bar(self):\n edit_tool_bar = self.addToolBar('Edit')\n\n tool_group = QActionGroup(self)\n tool_group.setExclusive(True)\n\n self.bead_tool_action = edit_tool_bar.addAction('Bead Tool')\n self.bead_tool_action.setCheckable(True)\n tool_group.addAction(self.bead_tool_action)\n\n self.remove_tool_action = edit_tool_bar.addAction('Clear Tool')\n self.remove_tool_action.setCheckable(True)\n tool_group.addAction(self.remove_tool_action)", "def set_toolbar_for_QrCode(self):\n self.root.ids.toolbar.left_action_items = [\n ['arrow-left', lambda x: self.back_press()]]\n self.root.ids.toolbar.right_action_items = []", "def _ui_init_toolbar_elements(self):\n\n # the composing shell\n self._shell = ComposingShell(self._director)\n\n # the coverage combobox\n self._combobox = CoverageComboBox(self._director)\n\n # the checkbox to hide 0% coverage entries\n self._hide_zero_label = QtWidgets.QLabel(\"Hide 0% Coverage: \")\n self._hide_zero_label.setFont(self._font)\n self._hide_zero_checkbox = QtWidgets.QCheckBox()\n\n # the splitter to make the shell / combobox resizable\n self._splitter = QtWidgets.QSplitter(QtCore.Qt.Horizontal)\n self._splitter.setStyleSheet(\n \"\"\"\n QSplitter::handle\n {\n background-color: #909090;\n width: 2px;\n height: 2px;\n margin: 0 0.5em 0 0.5em\n }\n\n QSplitter::handle:horizontal:hover\n {\n background-color: #3399FF;\n }\n \"\"\")\n\n # add the child items we wish to put the 'splitter' between\n self._splitter.addWidget(self._shell)\n self._splitter.addWidget(self._combobox)\n\n # this makes the splitter responsive to hover events\n self._splitter.handle(1).setAttribute(QtCore.Qt.WA_Hover)\n\n # give the shell expansion preference over the combobox\n self._splitter.setStretchFactor(0, 1)", "def __init__(self, *args):\n _aui.AuiToolBarItem_swiginit(self,_aui.new_AuiToolBarItem(*args))", "def _configureCB(self):\n self.oAppMenubar.filemenu.add_command(label='Open <Ctrl+o>', underline=0, command=self.oToolbar.oAppToolbar.BtnOpenFile.invoke)\n self.oAppMenubar.filemenu.add_command(label='Status <Ctrl+t>', underline=0, command=self.oToolbar.oAppToolbar.BtnInitXplore.invoke)\n self.oAppMenubar.filemenu.add_command(label='Quit', underline=0, command=self.oToolbar.oAppToolbar.BtnExit.invoke)\n self.oAppMenubar.settingsmenu.add_command(label='Global Settings', underline=0, command=self.wGlobSettingsCB)\n self.oAppMenubar.utilitiesmenu.add_command(label='More', underline=0, command=None)\n self.oAppMenubar.calibrationmenu.add_command(label='Current Source', underline=0, command=self.vCurrentSourceCalibCB)\n self.oAppMenubar.calibrationmenu.add_command(label='Voltage Source', underline=0, command=self.vVoltageSourceCalibCB)\n self.oAppMenubar.calibrationmenu.add_command(label='Current Measure', underline=0, command=self.vCurrentMeasureCalibCB)\n self.oAppMenubar.calibrationmenu.add_command(label='Voltage Measure', underline=0, command=self.vVoltageMeasureCalibCB)\n self.oAppMenubar.helpmenu.add_command(label='About', underline=0, command=self.vAboutInQCB)\n self.oAppMenubar.helpmenu.add_command(label='Keyboard Shortcuts', underline=0, command=self.vKBSCCB)\n self.oAppMenubar.helpmenu.add_command(label='Xplore User Manual<F1>', underline=0, command=self.vInQHelpCB)\n self.oAppMenubar.helpmenu.add_command(label='HowTO Videos', underline=0, command=self.vHowTOVideosCB)\n self.Export_Instance = 0\n self.About_Instance = 0\n self.KBSC_Instance = 0\n self.CalibIS_Instance = 0\n self.CalibVS_Instance = 0\n self.CalibIM_Instance = 0\n self.CalibVM_Instance = 0\n return", "def __showToolbarsMenu(self):\n self.__menus[\"toolbars\"].clear()\n\n tbList = []\n for name, (text, tb) in list(self.__toolbars.items()):\n tbList.append((str(text), tb, name))\n\n tbList.sort()\n for text, tb, name in tbList:\n act = self.__menus[\"toolbars\"].addAction(text)\n act.setCheckable(True)\n act.setData(QVariant(name))\n act.setChecked(not tb.isHidden())", "def setup_additional_ui(self):\n\n #set header icon\n header_icon_path = ''\n header_icon_name = 'icon_helga_launcher.png'\n header_icon_path = os.path.join(icons_path, header_icon_name)\n \n #set stylesheet header\n self.wdgt_header_icon.setStyleSheet(\"border-image: url({0});\".format(header_icon_path.replace('\\\\', '/')))\n \n \n #set title\n self.setWindowTitle(self.title)\n #set header label\n self.lbl_header_text.setText(self.title)\n\n #setup dcc buttons\n self.setup_dcc_buttons()\n\n #setup_mvc\n self.setup_mvc()", "def create_toolbar(self, parent=None, textfield=None):\n if not parent:\n parent = self\n if textfield is not None:\n data = self.master.get_toolbar_data(textfield)\n self.toolbar = wx.ToolBar(parent)\n self.toolbar.SetToolBitmapSize((16, 16))\n # self.combo_font = qtw.QFontComboBox(toolbar)\n fontbutton = wx.Button(self.toolbar, label=\"Font\")\n fontbutton.Bind(wx.EVT_BUTTON, self.choose_font)\n # toolbar.addWidget(self.combo_font)\n self.toolbar.AddControl(fontbutton)\n # self.combo_size = qtw.QComboBox(toolbar)\n # toolbar.addWidget(self.combo_size)\n # self.combo_size.setEditable(True)\n # db = gui.QFontDatabase()\n # self.fontsizes = []\n # for size in db.standardSizes():\n # self.combo_size.addItem(str(size))\n # self.fontsizes.append(str(size))\n # toolbar.addSeparator()\n\n accel_data = []\n for menudef in data:\n if not menudef:\n self.toolbar.AddSeparator()\n continue\n label, shortcut, icon, info, *methods = menudef\n if icon:\n bmp = wx.Bitmap(wx.Image(os.path.join(HERE, icon + '.png'), wx.BITMAP_TYPE_PNG))\n else:\n bmp = wx.NullBitmap\n toolid = wx.NewId()\n if info.startswith(\"Toggle\"):\n self.toolbar.AddCheckTool(toolid, label, bmp, shortHelp=info)\n else:\n self.toolbar.AddTool(toolid, label, bmp, shortHelp=info)\n if info.startswith(\"Toggle\"):\n # info = info[7]\n # if info in ('B', 'I', 'U', 'S'):\n # font = gui.QFont()\n # if info == 'B':\n # font.setBold(True)\n # elif info == 'I':\n # font.setItalic(True)\n # elif info == 'U':\n # font.setUnderline(True)\n # elif info == 'S':\n # font.setStrikeOut(True)\n # action.setFont(font)\n self.actiondict[label] = toolid\n try:\n callback, update_ui = methods\n except ValueError:\n callback, update_ui = methods[0], None\n self.Bind(wx.EVT_TOOL, callback, id=toolid)\n if shortcut:\n accel_data.append((label, callback, shortcut))\n if update_ui:\n self.Bind(wx.EVT_UPDATE_UI, update_ui, id=toolid)\n if accel_data:\n setup_accels(self, accel_data)\n\n # self.combo_font.activated[str].connect(textfield.text_family)\n # self.combo_size.activated[str].connect(textfield.text_size)\n self.toolbar.Realize()", "def __init__(self, parent, controller, title):\n super(Core, self).__init__(parent=parent, title=title)\n self.controller = controller\n self.statusbar = self.CreateStatusBar()\n self.panel = wx.Panel(self)\n self.panel.SetBackgroundColour('Pink')\n self._create_widgets()\n self._bind_widgets()\n self.show()\n self.check_menus()", "def __init__(self, *args, **kwargs):\n _aui.AuiToolBarEvent_swiginit(self,_aui.new_AuiToolBarEvent(*args, **kwargs))", "def create_menubar(self):\n # The file menu\n self.file_menu = self.menuBar().addMenu(\"&File\")\n quit_action = create_action(self,\"&Quit\", slot=self.quit,\n shortcut=\"Ctrl+Q\", tip=\"Close the application\")\n add_actions(self.file_menu, (None, quit_action))\n\n # The configuration menu\n self.config_menu = self.menuBar().addMenu(\"&Config\")\n create_option_menu(self,\n self.config_menu,\n \"&Logging level\",\n self.set_loglevel,\n ['Debug','Info','Warning','Error','Critical'])\n \n create_option_menu(self,\n self.config_menu,\n \"&Plot window\",\n self.make_plot_window,\n self.roach_keys+['all'])\n create_option_menu(self,\n self.config_menu,\n \"Power &Scale\",\n self.set_power_scale,\n [\"Linear\",\"Logarithmic\"])\n create_option_menu(self,\n self.config_menu,\n \"&Refresh timer\",\n self.timer_action,\n [\"Start\", \"Stop\"])\n # The help menu\n self.help_menu = self.menuBar().addMenu(\"&Help\")\n about_action = create_action(self,\"&About\",\n shortcut='F1', slot=self.on_about,\n tip='About the demo')\n add_actions(self.help_menu, (about_action,))", "def ToggleToolBar(self, event):\n if self.menu_show_tool_bar.IsChecked():\n self.toolbar.Show()\n else:\n self.toolbar.Hide()", "def createUndoToolBar(self):\n self._undoToolBar = self.createPluginToolBar(\"Undo ToolBar\")\n self._undoToolBar.addAction(self._editMenuItems[\"undoAction\"])\n self._undoToolBar.addAction(self._editMenuItems[\"redoAction\"])", "def _setupMenues(self):\n\n\n self._menues[\"file\"] = qt.QPopupMenu(self)\n self.menuBar().insertItem('&File',self._menues[\"file\"])\n\n\n\n\n\n\n\n self._actions[\"exit-faraday\"].addTo(self._menues[\"file\"]);\n self.menuBar().insertSeparator()\n\n\n self._menues[\"shell\"] = qt.QPopupMenu(self)\n self.menuBar().insertItem('&Shell',self._menues[\"shell\"])\n self._actions[\"new_shell\"].addTo(self._menues[\"shell\"]);\n self._actions[\"close_shell\"].addTo(self._menues[\"shell\"]);\n self._actions[\"maximize-shell\"].addTo(self._menues[\"shell\"]);\n\n self.menuBar().insertSeparator()\n\n self._menues[\"edit\"] = qt.QPopupMenu(self)\n self.menuBar().insertItem('&Edit',self._menues[\"edit\"])\n self._menues[\"edit\"].insertItem('&Copy', self._copy)\n self._menues[\"edit\"].insertItem('&Paste', self._paste)\n\n self._actions[\"repo-config\"].addTo(self._menues[\"edit\"]);\n\n self.menuBar().insertSeparator()\n\n\n self._menues[\"workspace\"] = qt.QPopupMenu(self)\n self.menuBar().insertItem('&Workspace',self._menues[\"workspace\"])\n # self._actions[\"open-workspace\"].addTo(self._menues[\"workspace\"])\n self._actions[\"create-workspace\"].addTo(self._menues[\"workspace\"])\n\n\n\n self.menuBar().insertSeparator()\n\n\n self._menues[\"tools\"] = qt.QPopupMenu(self)\n self.menuBar().insertItem('&Tools',self._menues[\"tools\"])\n self._actions[\"visualization\"].addTo(self._menues[\"tools\"]);\n\n self._actions[\"plugin\"].addTo(self._menues[\"tools\"]);\n self._actions[\"screenshot\"].addTo(self._menues[\"tools\"]);\n\n self.menuBar().insertSeparator()\n\n\n self._menues[\"view\"] = qt.QPopupMenu(self)\n self.menuBar().insertItem('&View',self._menues[\"view\"])\n self._actions[\"toggle-hosttree\"].addTo(self._menues[\"view\"]);\n self._actions[\"toggle-logconsole\"].addTo(self._menues[\"view\"]);\n self._actions[\"maximize-shell\"].addTo(self._menues[\"view\"]);\n\n self.menuBar().insertSeparator()\n\n\n self._menues[\"help\"] = qt.QPopupMenu(self)\n self.menuBar().insertItem('&Help',self._menues[\"help\"])\n self._menues[\"help\"].insertItem('&About', self._showAboutDialog)\n self._actions[\"documentation\"].addTo(self._menues[\"help\"]);", "def setupMenu(self):\n print(f'\\nsetupMenu')\n # Create actions for file menu\n open_act = QAction('Open...', self)\n open_act.setShortcut('Ctrl+O')\n open_act.triggered.connect(self.openImageFile)\n\n save_act = QAction('Save', self)\n save_act.setShortcut('Ctrl+S')\n save_act.triggered.connect(self.saveImageFile)\n\n # Create menu bar\n menu_bar = self.menuBar()\n menu_bar.setNativeMenuBar(False)\n\n # Create file menu and add actions\n file_menu = menu_bar.addMenu('File')\n file_menu.addAction(open_act)\n file_menu.addAction(save_act)", "def createZoomToolBar(self):\n self._zoomToolBar = self.createPluginToolBar('Zoom ToolBar')\n self._zoomToolBar.addAction(self.createAction('Revert Zoom', self.zoomUserEvent, image='zoomuser'))\n self._zoomToolBar.addAction(self.createAction('Zoom to 100 %', self.zoomHundredEvent, image='zoom100'))\n self._zoomToolBar.addAction(self.createAction('Zoom to all', self.zoomAllEvent, image='zoomall'))", "def add_toolbar(\n self,\n toolbar: widgets.QToolBar,\n area: constants.ToolbarAreaStr | constants.ToolBarArea | Literal[\"auto\"] = \"auto\",\n ):\n if area == \"auto\":\n area = self._get_preferred_toolbar_position()\n self.addToolBar(constants.TOOLBAR_AREA.get_enum_value(area), toolbar)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method is to be able to handle custom events in order to show custom dialogs or pop ups
def customEvent(self, event): if event.type() == EXCEPTION_ID: self.showExceptionDialog(event.text, event.callback, event.exception_objects) elif event.type() == SHOWDIALOG_ID: self.showSimpleDialog(event.text, event.level) elif event.type() == SHOWPOPUP_ID: self.showPopup(event.text, event.level) elif event.type() == CONFLICTS_ID: self.showConflictsDialog(event.local) elif event.type() == CHANGEFROMINSTANCE: self.newNotification(event.change) elif event.type() == CONNECTION_REFUSED: self.connectionRefused()
[ "def event(self,ev):\n if ev.type()==QtCore.QEvent.User:\n ErrorDialog.postError(ev.error)\n return True\n return QtWidgets.QWidget.event(self,ev)", "def showWindow(self, sender):", "def onOk(self, ev):\n self.EndModal(wx.ID_OK)", "def OnAbout(self, event):\n\t\tdialog = wx.MessageDialog(self,\n\t\t\"dat text editor tho\", \t\t\t\t\t# the text inside the dialog\n\t\t\"about dat text editor tho\",\t\t\t# the title of the dialog window\n\t\twx.OK)\t\t\t\t\t\t\t\t\t# dat ok button tho\n\t\t\n\t\tdialog.ShowModal()\t\t\t\t\t\t# shows the dialog\n\t\tdialog.Destroy()\t\t\t\t\t\t# destroy the dialog when finished", "def dialog_handler_cb(self, item, data) -> None:\n # Dialog box initialization event\n if item == KDialogInitEvent:\n vs.SetItemText(self.dialog, self.kWidgetID_fileName, self.parameters.excelFileName)\n # vs.SetItemText(self.dialog, self.kWidgetID_imageFolderName, self.settings.imageFolderName)\n\n vs.ShowItem(self.dialog, self.kWidgetID_excelSheetNameLabel, False)\n vs.ShowItem(self.dialog, self.kWidgetID_excelSheetName, False)\n self.show_parameters(False)\n\n vs.EnableItem(self.dialog, self.kWidgetID_importButton, False)\n vs.EnableItem(self.dialog, self.kWidgetID_importNewCount, False)\n vs.EnableItem(self.dialog, self.kWidgetID_importUpdatedCount, False)\n vs.EnableItem(self.dialog, self.kWidgetID_importDeletedCount, False)\n\n elif item == self.kWidgetID_fileName:\n self.parameters.excelFileName = vs.GetItemText(self.dialog, self.kWidgetID_fileName)\n\n elif item == self.kWidgetID_fileBrowseButton:\n result, self.parameters.excelFileName = vs.GetFileN(\"Open Excel file\", \"\", \"xlsm\")\n if result:\n vs.SetItemText(self.dialog, self.kWidgetID_fileName, self.parameters.excelFileName)\n\n elif item == self.kWidgetID_excelSheetName:\n new_excel_sheet_name = vs.GetChoiceText(self.dialog, self.kWidgetID_excelSheetName, data)\n if self.parameters.excelSheetName != new_excel_sheet_name:\n self.parameters.excelSheetName = new_excel_sheet_name\n self.show_parameters(False)\n if data != 0:\n self.show_parameters(True)\n\n elif item == self.kWidgetID_withImageSelector:\n vs.EnableItem(self.dialog, self.kWidgetID_withImage, data == 0)\n self.parameters.withImageSelector = vs.GetChoiceText(self.dialog, self.kWidgetID_withImageSelector, data)\n elif item == self.kWidgetID_withImage:\n self.parameters.pictureParameters.withImage = \"{}\".format(data != 0)\n # elif item == self.kWidgetID_imageFolderName:\n # self.settings.imageFolderName = vs.GetItemText(\n # self.dialog, self.kWidgetID_imageFolderName)\n # elif item == self.kWidgetID_imageFolderBrowseButton:\n # result, self.settings.imageFolderName = vs.GetFolder(\"Select the images folder\")\n # if result == 0:\n # vs.SetItemText(self.dialog, self.kWidgetID_imageFolderName, self.settings.imageFolderName)\n elif item == self.kWidgetID_imageTextureSelector:\n self.parameters.imageTextureSelector = vs.GetChoiceText(self.dialog, self.kWidgetID_withImageSelector, data)\n elif item == self.kWidgetID_imageWidthSelector:\n self.parameters.imageWidthSelector = vs.GetChoiceText(self.dialog, self.kWidgetID_imageWidthSelector, data)\n elif item == self.kWidgetID_imageHeightSelector:\n self.parameters.imageHeightSelector = vs.GetChoiceText(self.dialog, self.kWidgetID_imageHeightSelector, data)\n elif item == self.kWidgetID_imagePositionSelector:\n vs.EnableItem(self.dialog, self.kWidgetID_imagePosition, data == 0)\n self.parameters.imagePositionSelector = vs.GetChoiceText(self.dialog, self.kWidgetID_imagePositionSelector, data)\n elif item == self.kWidgetID_imagePosition:\n valid, value = vs.GetEditReal(self.dialog, self.kWidgetID_imagePosition, 3)\n if valid:\n self.parameters.pictureParameters.imagePosition = str(value)\n elif item == self.kWidgetID_withFrameSelector:\n vs.EnableItem(self.dialog, self.kWidgetID_withFrame, data == 0)\n self.parameters.withFrameSelector = vs.GetChoiceText(self.dialog, self.kWidgetID_withFrameSelector, data)\n elif item == self.kWidgetID_withFrame:\n self.parameters.pictureParameters.withFrame = \"{}\".format(data != 0)\n elif item == self.kWidgetID_frameWidthSelector:\n self.parameters.frameWidthSelector = vs.GetChoiceText(self.dialog, self.kWidgetID_frameWidthSelector, data)\n elif item == self.kWidgetID_frameHeightSelector:\n self.parameters.frameHeightSelector = vs.GetChoiceText(self.dialog, self.kWidgetID_frameHeightSelector, data)\n elif item == self.kWidgetID_frameThicknessSelector:\n vs.EnableItem(self.dialog, self.kWidgetID_frameThickness, data == 0)\n self.parameters.frameThicknessSelector = vs.GetChoiceText(self.dialog, self.kWidgetID_frameThicknessSelector, data)\n elif item == self.kWidgetID_frameThickness:\n valid, value = vs.GetEditReal(self.dialog, self.kWidgetID_frameThickness, 3)\n if valid:\n self.parameters.pictureParameters.frameThickness = str(value)\n elif item == self.kWidgetID_frameDepthSelector:\n vs.EnableItem(self.dialog, self.kWidgetID_frameDepth, data == 0)\n self.parameters.frameDepthSelector = vs.GetChoiceText(self.dialog, self.kWidgetID_frameDepthSelector, data)\n elif item == self.kWidgetID_frameDepth:\n valid, value = vs.GetEditReal(self.dialog, self.kWidgetID_frameDepth, 3)\n if valid:\n self.parameters.pictureParameters.frameDepth = str(value)\n elif item == self.kWidgetID_frameClassSelector:\n vs.EnableItem(self.dialog, self.kWidgetID_frameClass, data == 0)\n self.parameters.frameClassSelector = vs.GetChoiceText(self.dialog, self.kWidgetID_frameClassSelector, data)\n elif item == self.kWidgetID_frameClass:\n index, self.parameters.pictureParameters.frameClass = vs.GetSelectedChoiceInfo(self.dialog, self.kWidgetID_frameClass, 0)\n elif item == self.kWidgetID_frameTextureScaleSelector:\n vs.EnableItem(self.dialog, self.kWidgetID_frameTextureScale, data == 0)\n self.parameters.frameTextureScaleSelector = vs.GetChoiceText(self.dialog, self.kWidgetID_frameTextureScaleSelector, data)\n elif item == self.kWidgetID_frameTextureScale:\n valid, value = vs.GetEditReal(self.dialog, self.kWidgetID_frameTextureScale, 1)\n if valid:\n self.parameters.pictureParameters.frameTextureScale = str(value)\n elif item == self.kWidgetID_frameTextureRotationSelector:\n vs.EnableItem(self.dialog, self.kWidgetID_frameTextureRotation, data == 0)\n self.parameters.frameTextureRotationSelector = vs.GetChoiceText(self.dialog, self.kWidgetID_frameTextureRotationSelector, data)\n elif item == self.kWidgetID_frameTextureRotation:\n valid, value = vs.GetEditReal(self.dialog, self.kWidgetID_frameTextureRotation, 1)\n if valid:\n self.parameters.pictureParameters.frameTextureRotation = str(value)\n elif item == self.kWidgetID_withMatboardSelector:\n vs.EnableItem(self.dialog, self.kWidgetID_withMatboard, data == 0)\n self.parameters.withMatboardSelector = vs.GetChoiceText(self.dialog, self.kWidgetID_withMatboardSelector, data)\n elif item == self.kWidgetID_withMatboard:\n self.parameters.pictureParameters.withMatboard = \"{}\".format(data != 0)\n elif item == self.kWidgetID_matboardPositionSelector:\n vs.EnableItem(self.dialog, self.kWidgetID_matboardPosition, data == 0)\n self.parameters.matboardPositionSelector = vs.GetChoiceText(self.dialog, self.kWidgetID_matboardPositionSelector, data)\n elif item == self.kWidgetID_windowWidthSelector:\n self.parameters.windowWidthSelector = vs.GetChoiceText(self.dialog, self.kWidgetID_windowWidthSelector, data)\n elif item == self.kWidgetID_windowHeightSelector:\n self.parameters.windowHeightSelector = vs.GetChoiceText(self.dialog, self.kWidgetID_windowHeightSelector, data)\n elif item == self.kWidgetID_matboardPosition:\n valid, value = vs.GetEditReal(self.dialog, self.kWidgetID_matboardPosition, 3)\n if valid:\n self.parameters.pictureParameters.matboardPosition = str(value)\n elif item == self.kWidgetID_matboardClassSelector:\n vs.EnableItem(self.dialog, self.kWidgetID_matboardClass, data == 0)\n self.parameters.matboardClassSelector = vs.GetChoiceText(self.dialog, self.kWidgetID_matboardClassSelector, data)\n elif item == self.kWidgetID_matboardClass:\n index, self.parameters.pictureParameters.matboardClass = vs.GetSelectedChoiceInfo(self.dialog, self.kWidgetID_matboardClass, 0)\n elif item == self.kWidgetID_matboardTextureScaleSelector:\n vs.EnableItem(self.dialog, self.kWidgetID_matboardTextureScale, data == 0)\n self.parameters.matboardTextureScaleSelector = vs.GetChoiceText(self.dialog, self.kWidgetID_matboardTextureScaleSelector, data)\n elif item == self.kWidgetID_matboardTextureScale:\n valid, value = vs.GetEditReal(self.dialog, self.kWidgetID_matboardTextureScale, 1)\n if valid:\n self.parameters.pictureParameters.matboardTextureScale = str(value)\n elif item == self.kWidgetID_matboardTextureRotatSelector:\n vs.EnableItem(self.dialog, self.kWidgetID_matboardTextureRotat, data == 0)\n self.parameters.matboardTextureRotatSelector = vs.GetChoiceText(self.dialog, self.kWidgetID_matboardTextureRotatSelector, data)\n elif item == self.kWidgetID_matboardTextureRotat:\n valid, value = vs.GetEditReal(self.dialog, self.kWidgetID_matboardTextureRotat, 1)\n if valid:\n self.parameters.pictureParameters.matboardTextureRotat = str(value)\n elif item == self.kWidgetID_withGlassSelector:\n vs.EnableItem(self.dialog, self.kWidgetID_withGlass, data == 0)\n self.parameters.withGlassSelector = vs.GetChoiceText(self.dialog, self.kWidgetID_withGlassSelector, data)\n elif item == self.kWidgetID_withGlass:\n self.parameters.pictureParameters.withGlass = \"{}\".format(data != 0)\n elif item == self.kWidgetID_glassPositionSelector:\n vs.EnableItem(self.dialog, self.kWidgetID_glassPosition, data == 0)\n self.parameters.glassPositionSelector = vs.GetChoiceText(\n self.dialog, self.kWidgetID_glassPositionSelector, data)\n elif item == self.kWidgetID_glassPosition:\n valid, value = vs.GetEditReal(self.dialog, self.kWidgetID_glassPosition, 3)\n if valid:\n self.parameters.pictureParameters.glassPosition = str(value)\n elif item == self.kWidgetID_glassClassSelector:\n vs.EnableItem(self.dialog, self.kWidgetID_glassClass, data == 0)\n self.parameters.glassClassSelector = vs.GetChoiceText(self.dialog, self.kWidgetID_glassClassSelector, data)\n elif item == self.kWidgetID_glassClass:\n index, self.parameters.pictureParameters.glassClass = vs.GetSelectedChoiceInfo(self.dialog, self.kWidgetID_glassClass, 0)\n elif item == self.kWidgetID_excelCriteriaSelector:\n vs.EnableItem(self.dialog, self.kWidgetID_excelCriteriaValue, data != 0)\n new_excel_criteria_selector = vs.GetChoiceText(self.dialog, self.kWidgetID_excelCriteriaSelector, data)\n if new_excel_criteria_selector != self.parameters.excelCriteriaSelector:\n self.parameters.excelCriteriaSelector = new_excel_criteria_selector\n self.update_criteria_values(False)\n if data != 0:\n self.update_criteria_values(True)\n else:\n index = vs.GetChoiceIndex(self.dialog, self.kWidgetID_excelCriteriaValue, self.parameters.excelCriteriaValue)\n if index == -1:\n vs.SelectChoice(self.dialog, self.kWidgetID_excelCriteriaValue, 0, True)\n self.parameters.excelCriteriaValue = \"Select a value ...\"\n else:\n vs.SelectChoice(self.dialog, self.kWidgetID_excelCriteriaValue, index, True)\n elif item == self.kWidgetID_excelCriteriaValue:\n self.parameters.excelCriteriaValue = vs.GetChoiceText(self.dialog, self.kWidgetID_excelCriteriaValue, data)\n elif item == self.kWidgetID_symbolCreateSymbol:\n self.parameters.symbolCreateSymbol = \"{}\".format(data != 0)\n selector_index = vs.GetSelectedChoiceIndex(self.dialog, self.kWidgetID_symbolFolderSelector, 0)\n vs.EnableItem(self.dialog, self.kWidgetID_symbolFolderSelector, data)\n vs.EnableItem(self.dialog, self.kWidgetID_symbolFolder, selector_index == 0 and data == 1)\n elif item == self.kWidgetID_symbolFolderSelector:\n vs.EnableItem(self.dialog, self.kWidgetID_symbolFolder, data == 0)\n self.parameters.symbolFolderSelector = vs.GetChoiceText(self.dialog, self.kWidgetID_symbolFolderSelector, data)\n elif item == self.kWidgetID_classAssignPictureClass:\n self.parameters.classAssignPictureClass = \"{}\".format(data == 1)\n vs.EnableItem(self.dialog, self.kWidgetID_classPictureClassSelector, data == 1)\n selector_index = vs.GetPopUpChoiceIndex(self.dialog, self.kWidgetID_classPictureClassSelector, self.parameters.classClassPictureSelector)\n vs.EnableItem(self.dialog, self.kWidgetID_classPictureClass, selector_index == 0 and data != 0)\n elif item == self.kWidgetID_classPictureClassSelector:\n vs.EnableItem(self.dialog, self.kWidgetID_classPictureClass, data == 0)\n self.parameters.classClassPictureSelector = vs.GetChoiceText(self.dialog, self.kWidgetID_classPictureClassSelector, data)\n elif item == self.kWidgetID_classPictureClass:\n index, self.parameters.pictureParameters.pictureClass = vs.GetSelectedChoiceInfo(self.dialog, self.kWidgetID_classPictureClass, 0)\n elif item == self.kWidgetID_classCreateMissingClasses:\n self.parameters.createMissingClasses = \"{}\".format(data == 1)\n elif item == self.kWidgetID_metaImportMetadata:\n self.parameters.metaImportMetadata = \"{}\".format(data == 1)\n vs.EnableItem(self.dialog, self.kWidgetID_metaArtworkTitleSelector, data == 1)\n vs.EnableItem(self.dialog, self.kWidgetID_metaAuthorNameSelector, data == 1)\n vs.EnableItem(self.dialog, self.kWidgetID_metaArtworkCreationDateSelector, data == 1)\n vs.EnableItem(self.dialog, self.kWidgetID_metaArtworkMediaSelector, data == 1)\n # vs.EnableItem(self.dialog, self.kWidgetID_metaTypeSelector, data == 1)\n vs.EnableItem(self.dialog, self.kWidgetID_metaRoomLocationSelector, data == 1)\n vs.EnableItem(self.dialog, self.kWidgetID_metaArtworkSourceSelector, data == 1)\n vs.EnableItem(self.dialog, self.kWidgetID_metaRegistrationNumberSelector, data == 1)\n vs.EnableItem(self.dialog, self.kWidgetID_metaAuthorBirthCountrySelector, data == 1)\n vs.EnableItem(self.dialog, self.kWidgetID_metaAuthorBirthDateSelector, data == 1)\n vs.EnableItem(self.dialog, self.kWidgetID_metaAuthorDeathDateSelector, data == 1)\n vs.EnableItem(self.dialog, self.kWidgetID_metaDesignNotesSelector, data == 1)\n vs.EnableItem(self.dialog, self.kWidgetID_metaExhibitionMediaSelector, data == 1)\n elif item == self.kWidgetID_metaArtworkTitleSelector:\n self.parameters.metaArtworkTitleSelector = vs.GetChoiceText(self.dialog, self.kWidgetID_metaArtworkTitleSelector, data)\n elif item == self.kWidgetID_metaAuthorNameSelector:\n self.parameters.metaAuthorNameSelector = vs.GetChoiceText(self.dialog, self.kWidgetID_metaAuthorNameSelector, data)\n elif item == self.kWidgetID_metaArtworkCreationDateSelector:\n self.parameters.metaArtworkCreationDateSelector = vs.GetChoiceText(self.dialog, self.kWidgetID_metaArtworkCreationDateSelector, data)\n elif item == self.kWidgetID_metaArtworkMediaSelector:\n self.parameters.metaArtworkMediaSelector = vs.GetChoiceText(self.dialog, self.kWidgetID_metaArtworkMediaSelector, data)\n # elif item == self.kWidgetID_metaTypeSelector:\n # self.parameters.metaTypeSelector = vs.GetChoiceText(self.dialog, self.kWidgetID_metaTypeSelector, data)\n elif item == self.kWidgetID_metaRoomLocationSelector:\n self.parameters.metaRoomLocationSelector = vs.GetChoiceText(self.dialog, self.kWidgetID_metaRoomLocationSelector, data)\n elif item == self.kWidgetID_metaArtworkSourceSelector:\n self.parameters.metaArtworkSourceSelector = vs.GetChoiceText(self.dialog, self.kWidgetID_metaArtworkSourceSelector, data)\n elif item == self.kWidgetID_metaRegistrationNumberSelector:\n self.parameters.metaRegistrationNumberSelector = vs.GetChoiceText(self.dialog, self.kWidgetID_metaRegistrationNumberSelector, data)\n elif item == self.kWidgetID_metaAuthorBirthCountrySelector:\n self.parameters.metaAuthorBirthCountrySelector = vs.GetChoiceText(self.dialog, self.kWidgetID_metaAuthorBirthCountrySelector, data)\n elif item == self.kWidgetID_metaAuthorBirthDateSelector:\n self.parameters.metaAuthorBirthDateSelector = vs.GetChoiceText(self.dialog, self.kWidgetID_metaAuthorBirthDateSelector, data)\n elif item == self.kWidgetID_metaAuthorDeathDateSelector:\n self.parameters.metaAuthorDeathDateSelector = vs.GetChoiceText(self.dialog, self.kWidgetID_metaAuthorDeathDateSelector, data)\n elif item == self.kWidgetID_metaDesignNotesSelector:\n self.parameters.metaDesignNotesSelector = vs.GetChoiceText(self.dialog, self.kWidgetID_metaDesignNotesSelector, data)\n elif item == self.kWidgetID_metaExhibitionMediaSelector:\n self.parameters.metaExhibitionMediaSelector = vs.GetChoiceText(self.dialog, self.kWidgetID_metaExhibitionMediaSelector, data)\n elif item == self.kWidgetID_importIgnoreErrors:\n self.parameters.importIgnoreErrors = \"{}\".format(data != 0)\n vs.ShowItem(self.dialog, self.kWidgetID_importErrorCount, data == 0)\n elif item == self.kWidgetID_importIgnoreExisting:\n self.parameters.importIgnoreExisting = \"{}\".format(data != 0)\n elif item == self.kWidgetID_importIgnoreUnmodified:\n self.parameters.importIgnoreUnmodified = \"{}\".format(data != 0)\n elif item == self.kWidgetID_importButton:\n self.import_pictures()\n vs.SetItemText(self.dialog, self.kWidgetID_importNewCount, \"New Pictures: {}\".format(self.importNewCount))\n vs.SetItemText(self.dialog, self.kWidgetID_importUpdatedCount, \"Updated Pictures: {}\".format(self.importUpdatedCount))\n vs.SetItemText(self.dialog, self.kWidgetID_importDeletedCount, \"Deleted Pictures: {}\".format(self.importDeletedCount))\n vs.SetItemText(self.dialog, self.kWidgetID_importErrorCount, \"Error Pictures: {}\".format(self.importErrorCount))\n\n # This section handles the following cases:\n # - The Dialog is initializing\n # - The name of the workbook file has changed\n if item == self.kWidgetID_fileName or item == self.kWidgetID_fileBrowseButton or item == KDialogInitEvent:\n self.set_workbook()\n\n # The image selection has changed\n if item == self.kWidgetID_withImageSelector or item == self.kWidgetID_withImage or item == self.kWidgetID_excelSheetName:\n state = vs.GetSelectedChoiceIndex(self.dialog, self.kWidgetID_withImageSelector, 0) != 0 or \\\n vs.GetBooleanItem(self.dialog, self.kWidgetID_withImage) is True\n\n vs.EnableItem(self.dialog, self.kWidgetID_imageWidthLabel, state)\n vs.EnableItem(self.dialog, self.kWidgetID_imageWidthSelector, state)\n vs.EnableItem(self.dialog, self.kWidgetID_imageHeightLabel, state)\n vs.EnableItem(self.dialog, self.kWidgetID_imageHeightSelector, state)\n vs.EnableItem(self.dialog, self.kWidgetID_imagePositionLabel, state)\n vs.EnableItem(self.dialog, self.kWidgetID_imagePositionSelector, state)\n vs.EnableItem(self.dialog, self.kWidgetID_imagePosition, state)\n vs.EnableItem(self.dialog, self.kWidgetID_imageTextureLabel, state)\n vs.EnableItem(self.dialog, self.kWidgetID_imageTextureSelector, state)\n\n # The frame selection has changed\n if item == self.kWidgetID_withFrameSelector or item == self.kWidgetID_withFrame or item == self.kWidgetID_excelSheetName:\n state = vs.GetSelectedChoiceIndex(self.dialog, self.kWidgetID_withFrameSelector, 0) != 0 or \\\n vs.GetBooleanItem(self.dialog, self.kWidgetID_withFrame) is True\n\n vs.EnableItem(self.dialog, self.kWidgetID_frameWidthLabel, state)\n vs.EnableItem(self.dialog, self.kWidgetID_frameWidthSelector, state)\n vs.EnableItem(self.dialog, self.kWidgetID_frameHeightLabel, state)\n vs.EnableItem(self.dialog, self.kWidgetID_frameHeightSelector, state)\n vs.EnableItem(self.dialog, self.kWidgetID_frameThicknessLabel, state)\n vs.EnableItem(self.dialog, self.kWidgetID_frameThicknessSelector, state)\n vs.EnableItem(self.dialog, self.kWidgetID_frameThickness, state)\n vs.EnableItem(self.dialog, self.kWidgetID_frameDepthLabel, state)\n vs.EnableItem(self.dialog, self.kWidgetID_frameDepthSelector, state)\n vs.EnableItem(self.dialog, self.kWidgetID_frameDepth, state)\n vs.EnableItem(self.dialog, self.kWidgetID_frameClassLabel, state)\n vs.EnableItem(self.dialog, self.kWidgetID_frameClassSelector, state)\n vs.EnableItem(self.dialog, self.kWidgetID_frameClass, state)\n vs.EnableItem(self.dialog, self.kWidgetID_frameTextureScaleLabel, state)\n vs.EnableItem(self.dialog, self.kWidgetID_frameTextureScaleSelector, state)\n vs.EnableItem(self.dialog, self.kWidgetID_frameTextureScale, state)\n vs.EnableItem(self.dialog, self.kWidgetID_frameTextureRotationLabel, state)\n vs.EnableItem(self.dialog, self.kWidgetID_frameTextureRotationSelector, state)\n vs.EnableItem(self.dialog, self.kWidgetID_frameTextureRotation, state)\n\n # The matboard selection has changed\n if item == self.kWidgetID_withMatboardSelector or item == self.kWidgetID_withMatboard or item == self.kWidgetID_excelSheetName:\n state = vs.GetSelectedChoiceIndex(self.dialog, self.kWidgetID_withMatboardSelector, 0) != 0 or \\\n vs.GetBooleanItem(self.dialog, self.kWidgetID_withMatboard) is True\n\n vs.EnableItem(self.dialog, self.kWidgetID_windowWidthLabel, state)\n vs.EnableItem(self.dialog, self.kWidgetID_windowWidthSelector, state)\n vs.EnableItem(self.dialog, self.kWidgetID_windowHeightLabel, state)\n vs.EnableItem(self.dialog, self.kWidgetID_windowHeightSelector, state)\n vs.EnableItem(self.dialog, self.kWidgetID_matboardPositionLabel, state)\n vs.EnableItem(self.dialog, self.kWidgetID_matboardPositionSelector, state)\n vs.EnableItem(self.dialog, self.kWidgetID_matboardPosition, state)\n vs.EnableItem(self.dialog, self.kWidgetID_matboardClassLabel, state)\n vs.EnableItem(self.dialog, self.kWidgetID_matboardClassSelector, state)\n vs.EnableItem(self.dialog, self.kWidgetID_matboardClass, state)\n vs.EnableItem(self.dialog, self.kWidgetID_matboardTextureScaleLabel, state)\n vs.EnableItem(self.dialog, self.kWidgetID_matboardTextureScaleSelector, state)\n vs.EnableItem(self.dialog, self.kWidgetID_matboardTextureScale, state)\n vs.EnableItem(self.dialog, self.kWidgetID_matboardTextureRotatLabel, state)\n vs.EnableItem(self.dialog, self.kWidgetID_matboardTextureRotatSelector, state)\n vs.EnableItem(self.dialog, self.kWidgetID_matboardTextureRotat, state)\n\n # The glass selection has changed\n if item == self.kWidgetID_withGlassSelector or item == self.kWidgetID_withGlass or item == self.kWidgetID_excelSheetName:\n state = vs.GetSelectedChoiceIndex(self.dialog, self.kWidgetID_withGlassSelector, 0) != 0 or \\\n vs.GetBooleanItem(self.dialog, self.kWidgetID_withGlass) is True\n\n vs.EnableItem(self.dialog, self.kWidgetID_glassPositionLabel, state)\n vs.EnableItem(self.dialog, self.kWidgetID_glassPositionSelector, state)\n vs.EnableItem(self.dialog, self.kWidgetID_glassPosition, state)\n vs.EnableItem(self.dialog, self.kWidgetID_glassClassLabel, state)\n vs.EnableItem(self.dialog, self.kWidgetID_glassClassSelector, state)\n vs.EnableItem(self.dialog, self.kWidgetID_glassClass, state)\n\n # After the event has been handled, update some of the import validity settings accordingly\n self.parameters.imageValid = ((self.parameters.withImageSelector == \"-- Manual\" and self.parameters.pictureParameters.withImage == \"True\") or\n self.parameters.withImageSelector != \"-- Manual\") and \\\n (self.parameters.imageTextureSelector != \"-- Select column ...\") and \\\n (self.parameters.imageWidthSelector != \"-- Select column ...\") and \\\n (self.parameters.imageHeightSelector != \"-- Select column ...\")\n\n self.parameters.frameValid = ((self.parameters.withFrameSelector == \"-- Manual\" and self.parameters.pictureParameters.withFrame == \"True\") or\n self.parameters.withFrameSelector != \"-- Manual\") and \\\n (self.parameters.frameWidthSelector != \"-- Select column ...\") and \\\n (self.parameters.frameHeightSelector != \"-- Select column ...\")\n\n self.parameters.matboardValid = ((self.parameters.withMatboardSelector == \"-- Manual\" and self.parameters.pictureParameters.withMatboard == \"True\") or\n self.parameters.withMatboardSelector != \"-- Manual\") and \\\n (self.parameters.windowWidthSelector != \"-- Select column ...\") and \\\n (self.parameters.windowHeightSelector != \"-- Select column ...\")\n\n self.parameters.glassValid = ((self.parameters.withGlassSelector == \"-- Manual\" and\n self.parameters.pictureParameters.withGlass == \"True\") or self.parameters.withGlassSelector != \"-- Manual\")\n\n self.parameters.criteriaValid = \\\n (self.parameters.excelCriteriaSelector != \"-- Select column ...\" and self.parameters.excelCriteriaValue != \"Select a value ...\")\n\n self.parameters.importValid = (self.parameters.imageValid or self.parameters.frameValid) and self.parameters.criteriaValid\n\n vs.EnableItem(self.dialog, self.kWidgetID_importButton, self.parameters.importValid)\n vs.EnableItem(self.dialog, self.kWidgetID_importNewCount, self.parameters.importValid)\n vs.EnableItem(self.dialog, self.kWidgetID_importUpdatedCount, self.parameters.importValid)\n vs.EnableItem(self.dialog, self.kWidgetID_importDeletedCount, self.parameters.importValid)", "def OnButtonClick(self):\n pass", "def on_pick(self, event):\r\n pass", "def OnShow(self, event):\n page = self._page_widget\n if page:\n wx.PostEvent(page, event)", "def ProcessUiEvent(self, event):\n self.board.ProcessUiEvent(event)\n self.wheel.ProcessUiEvent(event)\n self.scoreboard.ProcessUiEvent(event)", "def connectEventsMenuBar(self):\n\n self.docAction.triggered.connect(self.openDocs)\n self.versionAction.triggered.connect(self.openVersion)\n self.saveAction.triggered.connect(self.saveFile)\n self.saveAsAction.triggered.connect(self.saveFileAs)\n self.openAction.triggered.connect(self.openFile)\n self.addLoaderAction.triggered.connect(self.addLoader)\n self.newAction.triggered.connect(self.newForecast)\n self.setCustomDatetimeAction.triggered.connect(self.setCustomDatetimeDialog)\n \n return", "def test_post_ui_openwindow_information(self):\n pass", "def dialog_init(self, *args, **kwargs):\n pass", "def contentsContextMenuEvent(self,ev):\n return", "def test_post_ui_openwindow_contract(self):\n pass", "def on_form_closed(self, sender, eargs):\n pass", "def event(mouse_event):\n pass", "def _quality_control_fired(self):\n print_blue(\"[Open Quality Inspector Window]\")\n if self.project_info.t1_available:\n if os.path.isfile(self.project_info.anat_config_file):\n print(f\" .. Anatomical config file : {self.project_info.anat_config_file}\")\n\n if self.project_info.dmri_available:\n if os.path.isfile(self.project_info.dmri_config_file):\n print(f\" .. Diffusion config file : {self.project_info.dmri_config_file}\")\n\n if self.project_info.fmri_available:\n if os.path.isfile(self.project_info.fmri_config_file):\n print(f\" .. fMRI config file : {self.project_info.fmri_config_file}\")\n\n if self.project_info.eeg_available:\n if os.path.isfile(self.project_info.eeg_config_file):\n print(f\" .. EEG config file : {self.project_info.eeg_config_file}\")\n\n try:\n self.quality_control_ui = cmp.bidsappmanager.gui.qc.QualityInspectorWindow(\n project_info=self.project_info,\n anat_inputs_checked=self.project_info.t1_available,\n dmri_inputs_checked=self.project_info.dmri_available,\n fmri_inputs_checked=self.project_info.fmri_available,\n eeg_inputs_checked=self.project_info.eeg_available\n )\n self.quality_control_ui.configure_traits()\n except Exception as e:\n print(e)", "def _on_menubar(self, event: str, value: Any) -> None:\n print(\"_on_menubar\", event, value)\n if not value:\n return\n label, key = value.split(\"::__\", 1)\n tokens = key.split(\"_\")\n if tokens[0] == \"FILE\":\n if tokens[1] == \"OPEN\":\n if tokens[2] == \"GCODE\":\n # TODO\n self.publish(\"gui:select_file_gcode\", None)\n elif tokens[2] == \"CONTROLLER\":\n self.publish(\"%s:set_active\" % label, True)\n elif tokens[1] == \"NEW\":\n if tokens[2] == \"GCODE\":\n # TODO\n pass\n elif tokens[2] == \"CONTROLLER\":\n self.publish(\"##new_controller:picker\", \"##new_controller\")\n #self.publish(\"request_new_controller\", label)", "def on_ask_event(self, event):\n self.event_dispatcher.dispatch_event( \n MyEvent ( MyEvent.RESPOND, self ) \n )" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
fetch the trading fees for a market
async def fetch_trading_fee(self, symbol: str, params={}): await self.load_markets() market = self.market(symbol) request = { 'pair': market['id'], } response = await self.privateGetFeeInfo(self.extend(request, params)) # # { # "maker_fee": "0.00250000", # "taker_fee": "0.00500000", # "thirty_day_volume": "0" # } # return { 'info': response, 'symbol': symbol, 'maker': self.safe_number(response, 'maker_fee'), 'taker': self.safe_number(response, 'taker_fee'), }
[ "async def fetch_trading_fees(self, params={}):\n await self.load_markets()\n response = await self.privateGetFees(params)\n #\n # {\n # \"maker_fee_rate\": \"0.0050\",\n # \"taker_fee_rate\": \"0.0050\",\n # \"usd_volume\": \"43806.92\"\n # }\n #\n maker = self.safe_number(response, 'maker_fee_rate')\n taker = self.safe_number(response, 'taker_fee_rate')\n result = {}\n for i in range(0, len(self.symbols)):\n symbol = self.symbols[i]\n result[symbol] = {\n 'info': response,\n 'symbol': symbol,\n 'maker': maker,\n 'taker': taker,\n 'percentage': True,\n 'tierBased': True,\n }\n return result", "async def fetch_trading_fees(self, params={}):\n await self.load_markets()\n response = await self.privateGetAccount(params)\n #\n # {\n # \"fees\": {\n # \"taker\": \"0.0025\",\n # \"maker\": \"0.0015\",\n # \"volume\": \"10000.00\"\n # }\n # }\n #\n fees = self.safe_value(response, 'fees')\n maker = self.safe_number(fees, 'maker')\n taker = self.safe_number(fees, 'taker')\n result = {}\n for i in range(0, len(self.symbols)):\n symbol = self.symbols[i]\n result[symbol] = {\n 'info': response,\n 'symbol': symbol,\n 'maker': maker,\n 'taker': taker,\n 'percentage': True,\n 'tierBased': True,\n }\n return result", "async def fetch_trading_fees(self, params={}):\n await self.load_markets()\n response = await self.v3PrivateGetAccountinfo(params)\n #\n # {\n # \"success\": True,\n # \"data\": {\n # \"applicationId\": \"dsa\",\n # \"account\": \"dsa\",\n # \"alias\": \"haha\",\n # \"accountMode\": \"MARGIN\",\n # \"leverage\": 1,\n # \"takerFeeRate\": 1,\n # \"makerFeeRate\": 1,\n # \"interestRate\": 1,\n # \"futuresTakerFeeRate\": 1,\n # \"futuresMakerFeeRate\": 1,\n # \"otpauth\": True,\n # \"marginRatio\": 1,\n # \"openMarginRatio\": 1,\n # \"initialMarginRatio\": 1,\n # \"maintenanceMarginRatio\": 1,\n # \"totalCollateral\": 1,\n # \"freeCollateral\": 1,\n # \"totalAccountValue\": 1,\n # \"totalVaultValue\": 1,\n # \"totalStakingValue\": 1\n # },\n # \"timestamp\": 1673323685109\n # }\n #\n data = self.safe_value(response, 'data', {})\n maker = self.safe_string(data, 'makerFeeRate')\n taker = self.safe_string(data, 'takerFeeRate')\n result = {}\n for i in range(0, len(self.symbols)):\n symbol = self.symbols[i]\n result[symbol] = {\n 'info': response,\n 'symbol': symbol,\n 'maker': self.parse_number(Precise.string_div(maker, '10000')),\n 'taker': self.parse_number(Precise.string_div(taker, '10000')),\n 'percentage': True,\n 'tierBased': True,\n }\n return result", "def fees(self):\n\t\tdat = self.conn.call('GET', '/api/fees/').json()\n\t\tdeposit = float(dat['data']['deposit_fee'])\n\t\toutgoing = float(dat['data']['outgoing_fee'])\n\t\treturn (deposit, outgoing)", "def get_fee(market, price):\r\n return round(market.api.fees['trading']['taker'] * price,5)", "def getExchangeFee(self):\n # get trade info from public API v3\n # info = requests.get(\"https://btc-e.com/api/3/info\").json()\n\n # fee = info['pairs']['btc_usd']['fee']\n\n return 0.2", "def do_get_fees(self):\n request = self._request.get_fees()\n return self._send_get_first_result(request)", "def fees_sell(self) -> float:\n txs = [t for t in self.__transactions if isinstance(t, CryptoSellTransaction)]\n return sum([t.fees for t in txs])", "def fees_buy(self) -> float:\n txs = [t for t in self.__transactions if isinstance(t, CryptoBuyTransaction)]\n return sum([t.fees for t in txs])", "def fees(self):\n return self._get_prop_value(self._FEES_KEY)", "def fees_deposit(self) -> float:\n txs = [t for t in self.__transactions if isinstance(t, DepositTransaction)]\n return sum([t.fees for t in txs])", "def get_blockchain_fee_estimates(coin_symbol='btc', api_key=None):\n overview = get_blockchain_overview(coin_symbol=coin_symbol, api_key=api_key)\n if coin_symbol == 'eth':\n return {\n 'high_fee_per_kb': overview['high_gas_price'],\n 'medium_fee_per_kb': overview['medium_gas_price'],\n 'low_fee_per_kb': overview['low_gas_price'],\n }\n else:\n return {\n 'high_fee_per_kb': overview['high_fee_per_kb'],\n 'medium_fee_per_kb': overview['medium_fee_per_kb'],\n 'low_fee_per_kb': overview['low_fee_per_kb'],\n }", "async def _update_trading_fees(self):\n \"\"\"\n {\n \"status\": \"success\",\n \"data\": {\n \"taker_fee_rates_x18\": [\n \"0\",\n \"300000000000000\",\n \"200000000000000\",\n \"300000000000000\",\n \"200000000000000\"\n ],\n \"maker_fee_rates_x18\": [\n \"0\",\n \"0\",\n \"0\",\n \"0\",\n \"0\"\n ],\n \"liquidation_sequencer_fee\": \"250000000000000000\",\n \"health_check_sequencer_fee\": \"100000000000000000\",\n \"taker_sequencer_fee\": \"25000000000000000\",\n \"withdraw_sequencer_fees\": [\n \"10000000000000000\",\n \"40000000000000\",\n \"0\",\n \"600000000000000\",\n \"0\"\n ]\n }\n }\n \"\"\"\n try:\n fee_rates = await self._get_fee_rates()\n taker_fees = {idx: fee_rate for idx, fee_rate in enumerate(fee_rates[\"taker_fee_rates_x18\"])}\n maker_fees = {idx: fee_rate for idx, fee_rate in enumerate(fee_rates[\"maker_fee_rates_x18\"])}\n # NOTE: This builds our fee rates based on indexed product_id\n for trading_pair in self._trading_pairs:\n product_id = utils.trading_pair_to_product_id(\n trading_pair=trading_pair, exchange_market_info=self._exchange_market_info[self._domain]\n )\n self._trading_fees[trading_pair] = {\n \"maker\": Decimal(utils.convert_from_x18(maker_fees[product_id])),\n \"taker\": Decimal(utils.convert_from_x18(taker_fees[product_id])),\n }\n except Exception:\n # NOTE: If failure to fetch, build default fees\n for trading_pair in self._trading_pairs:\n self._trading_fees[trading_pair] = {\n \"maker\": utils.DEFAULT_FEES.maker_percent_fee_decimal,\n \"taker\": utils.DEFAULT_FEES.taker_percent_fee_decimal,\n }", "def request_fundamentals(stock_index):\n items = [\n ['l1', 'Last Price'],\n ['y', 'Dividend Yield'],\n ['r', 'Price/Earnings'],\n ['e', 'Earnings/Share'],\n ['b4', 'Book Value'],\n ['j', '52 week low'],\n ['k', '52 week high'],\n ['j1', 'Market Cap'],\n ['j4', 'EBITDA'],\n ['p5', 'Price/Sales'],\n ['p6', 'Price/Book'],\n ['f6','Float']\n ] \n params = ''.join([ x[0] for x in items ])\n url = 'http://download.finance.yahoo.com/d/quotes.csv?'\n #edgar = 'http://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK='\n\n reader = csv.reader(open(data_dir + stock_index +'/'+ stock_index +'_atoms.csv'))\n outrows = [ row for row in reader ]\n symbols = [ row[0] for row in outrows[1:] ]\n\n #outrows[0] += [ item[1] for item in items ] + ['SEC Filings']\n outrows[0] += [ item[1] for item in items ]\n \n print('Getting fundamentals of stocks in {}'.format(stock_index))\n for idx in range(0,len(symbols),20):\n query = url + 's=' + '+'.join(symbols[idx:idx+20]) + '&f=' + params\n fo = urlopen(query)\n tmpcsv = csv.reader(fo)\n rows = [ row for row in tmpcsv ]\n for count, row in enumerate(rows):\n realidx = idx + count + 1\n # change n/a to empty cell\n row = [ x.replace('N/A', '') for x in row ]\n # market cap and ebitda have 'B' or 'M' in them sometimes\n row[7] = correctToBillions(row[7])\n row[8] = correctToBillions(row[8])\n # add the edgar link\n #row.append(edgar + symbols[realidx-1])\n outrows[realidx] = outrows[realidx] + row\n #print('Processed: %s rows' % (idx + 20))\n\n output_dir = data_dir + stock_index + '/' + todays_date_mmddyy() + '/'\n fo = open(output_dir + 'fundm_'+ todays_date_mmddyy() +'.csv', 'w')\n writer = csv.writer(fo, lineterminator='\\n')\n writer.writerows(outrows)\n fo.close()", "def fees_withdrawal(self) -> float:\n txs = [t for t in self.__transactions if isinstance(t, WithdrawalTransaction)]\n return sum([t.fees for t in txs])", "def collect_borrow_fees(countries=None):\n params = {}\n if countries:\n params[\"countries\"] = countries\n response = houston.post(\"/fundamental/stockloan/fees\", params=params)\n\n houston.raise_for_status_with_json(response)\n return response.json()", "def get_contracts(symbol, month, type):\n\ttarget = contract_urlmask % (symbol.strip(\"$\"), month, type)\n\t\t\n\tkey = \"%s-%s-%s\" % (symbol, month, type)\n\tif key in _ts_data_cache and (datetime.datetime.now() - _ts_data_cache[key][0]).total_seconds() / 60 < get_setting(\"DATA_STALE_TIMEOUT\"):\n\t\theader = _ts_data_cache[key][1]\n\t\tprice = Decimal(header[header.find(\"Last:\")+6:header.find(\" , \")])\n\t\treturn (price, _ts_data_cache[key][2])\n\t\n\t# Request\n\tif(get_setting(\"DEBUG\")): print(target)\n\tresponse = requests.get(target, cookies={'slogin' : get_setting(\"SLOGIN\")})\n\txhtml = response.text\n\n\t# Decode\n\tparser = HTMLTableParser()\n\tparser.feed(xhtml)\n\t\n\t# TODO: Check if no options available (raise exception or print error, schedule contract reload)\n\n\t# Modify list - [strike, bid, ask, odds]\n\ttables = parser.tables[6:-5]\n\tcontracts = [ [ Decimal(tables[i-1][1][0].split(\" \")[0]), Decimal(tables[i-1][1][1]), Decimal(tables[i][0][1]), int(tables[i][0][5][:-1]) ] for i in range(1, len(tables)) ]\n\t\n\t# Grab header with price and change\n\theader = tables[0][0][2].split(\"\\n\")[-1]\n\tstart_index = header.find(\"(\")\n\tend_index = header.find(\", V\")\n\theader = header[start_index:end_index]\n\t\n\t# Grab price\n\tprice = Decimal(header[header.find(\"Last:\")+6:header.find(\" , \")])\n\t\n\t_ts_data_cache[key] = (datetime.datetime.now(), header, contracts)\n\t\n\treturn (price, contracts)", "def getTickerNoFee(self):\n # get ticker from public API v3\n return requests.get(\"https://btc-e.com/api/3/ticker/btc_usd\").json()['btc_usd']", "def get_fee_info(self):\n\n return self._make_request('getFeeInfo')" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns all the metadata associated to the parent batch.
def get_child_batch_metadata(parent_batch_id, metadata_type): response = batch_execution_metadata_table.query( IndexName="ParentBatchIdIndex", KeyConditionExpression=Key(Attributes.PARENT_BATCH_ID).eq(parent_batch_id), ) items = [] for item in response["Items"]: if item[Attributes.BATCH_METADATA_TYPE] == metadata_type: items.append(item) return items
[ "def get_child_batch_metadata_all(\n parent_batch_id,\n):\n response = batch_execution_metadata_table.query(\n IndexName=\"ParentBatchIdIndex\",\n KeyConditionExpression=Key(Attributes.PARENT_BATCH_ID).eq(parent_batch_id),\n )\n\n return response[\"Items\"]", "def metadata(self):\n return self.Model.metadata", "def batch_data(self):\n return self.container['batch_data']", "def get_metadata(self):\r\n return self.manager.get_metadata(self, node=self)", "def get_batch_metadata(batch_id):\n response = batch_execution_metadata_table.get_item(\n Key={\n Attributes.BATCH_ID: batch_id,\n },\n )\n return response[\"Item\"] if \"Item\" in response else None", "def get_items_sequential_metadata(self):\n return # osid.Metadata", "def parents(self, cached):\n\n data = []\n for motif in cached['motifs']:\n for parent in motif['parents']:\n data.append({\n 'ml_release_id': cached['release'],\n 'motif_id': motif['motif_id'],\n 'parent_ml_release_id': cached['parent'],\n 'parent_motif_id': parent['name']['full'],\n })\n return data", "def _metadata(self):\n return [antenna._metadata for antenna in self]", "def __read_metadata():\n\n batch_number = 140010\n training_example_file_name = find_training_file(\n top_training_dir_name=TOP_TRAINING_DIR_NAME, batch_number=batch_number,\n raise_error_if_missing=True)\n training_example_dict = read_input_examples(\n netcdf_file_name=training_example_file_name, metadata_only=True)\n\n for this_key in training_example_dict:\n print '{0:s} ... {1:s}\\n'.format(\n this_key, str(training_example_dict[this_key]))", "def get_metadata(self):\n return meta.get_metadata(self.ast)", "def get_metadata(self, queue):\r\n return self._manager.get_metadata(queue)", "def metadata(self) -> Mapping[str, np.ndarray]:\n return self._metadata.copy()", "def metadata(self) -> dict[str, Any]:", "def get_metadata(self):\n self.METADATA = []\n for file in self.METADATA_FILE_NAMES:\n self.METADATA.append(pd.read_csv(file))", "def get_metadata(self, taskmanager_id, generation_id, key):\n\n cols = [(x.split())[0] for x in SQLite3DB.tables.get(SQLite3DB.metadata_table)]\n return self._get_table_row(SQLite3DB.metadata_table, taskmanager_id,\n generation_id, key, cols)", "def get_metadata(self):\n if not self._connected:\n raise PPKError(\"Invalid operation: must connect first.\")\n return self._metadata.copy()", "def get_metadata_bulk(dids, inherit=False, *, session: \"Session\"):\n if inherit:\n parent_list = []\n unique_dids = []\n parents = [1, ]\n depth = 0\n for did in dids:\n unique_dids.append((did['scope'], did['name']))\n parent_list.append([(did['scope'], did['name']), ])\n\n while parents and depth < 20:\n parents = []\n for did in list_parent_dids_bulk(dids, session=session):\n scope = did['scope']\n name = did['name']\n child_scope = did['child_scope']\n child_name = did['child_name']\n if (scope, name) not in unique_dids:\n unique_dids.append((scope, name))\n if (scope, name) not in parents:\n parents.append((scope, name))\n for entry in parent_list:\n if entry[-1] == (child_scope, child_name):\n entry.append((scope, name))\n dids = [{'scope': did[0], 'name': did[1]} for did in parents]\n depth += 1\n unique_dids = [{'scope': did[0], 'name': did[1]} for did in unique_dids]\n meta_dict = {}\n for did in unique_dids:\n try:\n meta = get_metadata(did['scope'], did['name'], plugin='JSON', session=session)\n except exception.DataIdentifierNotFound:\n meta = {}\n meta_dict[(did['scope'], did['name'])] = meta\n for dids in parent_list:\n result = {'scope': dids[0][0], 'name': dids[0][1]}\n for did in dids:\n for key in meta_dict[did]:\n if key not in result:\n result[key] = meta_dict[did][key]\n yield result\n else:\n condition = []\n for did in dids:\n condition.append(and_(models.DataIdentifier.scope == did['scope'],\n models.DataIdentifier.name == did['name']))\n try:\n for chunk in chunks(condition, 50):\n stmt = select(\n models.DataIdentifier\n ).with_hint(\n models.DataIdentifier, \"INDEX(DIDS DIDS_PK)\", 'oracle'\n ).where(\n or_(*chunk)\n )\n for row in session.execute(stmt).scalars():\n yield row.to_dict()\n except NoResultFound:\n raise exception.DataIdentifierNotFound('No Data Identifiers found')", "def metadata(self):\n # type: () -> StreamMetadata\n return self._metadata", "def flattened_metadata(self):\n self.__log.call()\n\n snapshot = self.metadata_snapshot\n snapshot.pop(\"__custom\") # already incorporated into each track\n\n # to \"flatten\" the metadata, just add the album metadata to each track\n flattened = snapshot.pop(\"__tracks\")[1:] # zero-based indexing here\n for i in range(len(flattened)):\n flattened[i].update(snapshot)\n\n self.__log.return_(flattened)\n return flattened" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fetches a batch execution metadata by the batch_execution_job_id.
def get_batch_metadata(batch_id): response = batch_execution_metadata_table.get_item( Key={ Attributes.BATCH_ID: batch_id, }, ) return response["Item"] if "Item" in response else None
[ "def get_child_batch_metadata_all(\n parent_batch_id,\n):\n response = batch_execution_metadata_table.query(\n IndexName=\"ParentBatchIdIndex\",\n KeyConditionExpression=Key(Attributes.PARENT_BATCH_ID).eq(parent_batch_id),\n )\n\n return response[\"Items\"]", "def get_execution(self, execution_id, **kwargs):\n\n url = self._make_url(\"/v1/execution/{0}/\".format(execution_id))\n return self._session.get(url, **kwargs)", "def get_execution_result(self, job_id):\n return _execute_rest_request(url=f\"{self.prefix}/{job_id}/execution-result\")", "def get_batch_job(self) -> SlurmBatchJob:\n ...", "def get_child_batch_metadata(parent_batch_id, metadata_type):\n response = batch_execution_metadata_table.query(\n IndexName=\"ParentBatchIdIndex\",\n KeyConditionExpression=Key(Attributes.PARENT_BATCH_ID).eq(parent_batch_id),\n )\n\n items = []\n for item in response[\"Items\"]:\n if item[Attributes.BATCH_METADATA_TYPE] == metadata_type:\n items.append(item)\n\n return items", "def _get_lookup_batch():\n state = _runstate.current()\n batch = state.batches.get(_BATCH_LOOKUP)\n if batch is not None:\n return batch\n\n state.batches[_BATCH_LOOKUP] = batch = {}\n _eventloop.add_idle(_perform_batch_lookup)\n return batch", "def batch_data(self):\n return self.container['batch_data']", "def get_job(self, job_id):\n return self.jobs.get(job_id)", "def get_bulk_write_job_details(job_id):\n\n \"\"\"\n example\n job_id = 3477061000005615003\n \"\"\"\n\n # Get instance of BulkWriteOperations Class\n bulk_write_operations = BulkWriteOperations()\n\n # Call get_bulk_write_job_details method that takes job_id as parameter\n response = bulk_write_operations.get_bulk_write_job_details(job_id)\n\n if response is not None:\n\n # Get the status code from response\n print('Status Code: ' + str(response.get_status_code()))\n\n if response.get_status_code() in [204, 304]:\n print('No Content' if response.get_status_code() == 204 else 'Not Modified')\n return\n\n # Get object from response\n response_object = response.get_object()\n\n if response_object is not None:\n\n # Check if expected BulkWriteResponse instance is received\n if isinstance(response_object, BulkWriteResponse):\n\n # Get the Job Status of the bulkWriteResponse\n print(\"Bulk write Job Status: \" + response_object.get_status())\n\n # Get the CharacterEncoding of the bulkWriteResponse\n print(\"Bulk write CharacterEncoding: \" + response_object.get_character_encoding())\n\n resources = response_object.get_resource()\n\n if resources is not None:\n for resource in resources:\n # Get the Status of each Resource\n print(\"Bulk write Resource Status: \" + resource.get_status().get_value())\n\n # Get the Type of each Resource\n print(\"Bulk write Resource Type: \" + resource.get_type().get_value())\n\n # Get the Module of each Resource\n print(\"Bulk write Resource Module: \" + resource.get_module())\n\n # Get the field mappings\n field_mappings = resource.get_field_mappings()\n\n if field_mappings is not None:\n for field_mapping in field_mappings:\n # Get the APIName of each FieldMapping\n print(\"Bulk write Resource FieldMapping Module: \" + field_mapping.get_api_name())\n\n if field_mapping.get_index() is not None:\n # Get the Index of each FieldMapping\n print(\"Bulk write Resource FieldMapping Index: \" + str(field_mapping.get_index()))\n\n if field_mapping.get_format() is not None:\n # Get the Format of each FieldMapping\n print(\"Bulk write Resource FieldMapping Format: \" + field_mapping.get_format())\n\n if field_mapping.get_find_by() is not None:\n # Get the FindBy of each FieldMapping\n print(\"Bulk write Resource FieldMapping FindBy: \" + field_mapping.get_find_by())\n\n if field_mapping.get_default_value() is not None:\n print('Default values')\n\n for key, value in field_mapping.get_default_value().items():\n print(key + \": \" + str(value))\n\n # Get the file\n file = resource.get_file()\n\n if file is not None:\n # Get the Status of the File\n print(\"Bulk write Resource File Status: \" + file.get_status().get_value())\n\n # Get the Name of the File\n print(\"Bulk write Resource File Name: \" + file.get_name())\n\n # Get the AddedCount of the File\n print(\"Bulk write Resource File AddedCount: \" + str(file.get_added_count()))\n\n # Get the SkippedCount of the File\n print(\"Bulk write Resource File SkippedCount: \" + str(file.get_skipped_count()))\n\n # Get the UpdatedCount of the File\n print(\"Bulk write Resource File UpdatedCount: \" + str(file.get_updated_count()))\n\n # Get the TotalCount of the File\n print(\"Bulk write Resource File TotalCount: \" + str(file.get_total_count()))\n\n callback = response_object.get_callback()\n\n if callback is not None:\n # Get the CallBack Url\n print(\"Bulk write CallBack Url: \" + callback.get_url())\n\n # Get the CallBack Method\n print(\"Bulk write CallBack Method: \" + callback.get_method().get_value())\n\n # Get the ID of the BulkWriteResponse\n print(\"Bulk write ID: \" + str(response_object.get_id()))\n\n result = response_object.get_result()\n\n if result is not None:\n # Get the DownloadUrl of the Result\n print(\"Bulk write DownloadUrl: \" + result.get_download_url())\n\n # Get the CreatedBy User instance of the BulkWriteResponse\n created_by = response_object.get_created_by()\n\n # Check if created_by is not None\n if created_by is not None:\n # Get the Name of the created_by User\n print(\"Bulkwrite Created By - Name: \" + created_by.get_name())\n\n # Get the ID of the created_by User\n print(\"Bulkwrite Created By - ID: \" + str(created_by.get_id()))\n\n # Get the Operation of the BulkWriteResponse\n print(\"Bulk write Operation: \" + response_object.get_operation())\n\n # Get the CreatedTime of the BulkWriteResponse\n print(\"Bulk write File CreatedTime: \" + str(response_object.get_created_time()))\n\n # Check if the request returned an exception\n elif isinstance(response_object, APIException):\n # Get the Status\n print(\"Status: \" + response_object.get_status().get_value())\n\n # Get the Code\n print(\"Code: \" + response_object.get_code().get_value())\n\n print(\"Details\")\n\n # Get the details dict\n details = response_object.get_details()\n\n for key, value in details.items():\n print(key + ' : ' + str(value))\n\n # Get the Message\n print(\"Message: \" + response_object.get_message().get_value())", "def get_recording_batchrequest(self, job_id, **kwargs):\n\n all_params = ['job_id']\n all_params.append('callback')\n\n params = locals()\n for key, val in iteritems(params['kwargs']):\n if key not in all_params:\n raise TypeError(\n \"Got an unexpected keyword argument '%s'\"\n \" to method get_recording_batchrequest\" % key\n )\n params[key] = val\n del params['kwargs']\n\n # verify the required parameter 'job_id' is set\n if ('job_id' not in params) or (params['job_id'] is None):\n raise ValueError(\"Missing the required parameter `job_id` when calling `get_recording_batchrequest`\")\n\n\n resource_path = '/api/v2/recording/batchrequests/{jobId}'.replace('{format}', 'json')\n path_params = {}\n if 'job_id' in params:\n path_params['jobId'] = params['job_id']\n\n query_params = {}\n\n header_params = {}\n\n form_params = []\n local_var_files = {}\n\n body_params = None\n\n # HTTP header `Accept`\n header_params['Accept'] = self.api_client.\\\n select_header_accept(['application/json'])\n if not header_params['Accept']:\n del header_params['Accept']\n\n # HTTP header `Content-Type`\n header_params['Content-Type'] = self.api_client.\\\n select_header_content_type(['application/json'])\n\n # Authentication setting\n auth_settings = ['PureCloud OAuth']\n\n response = self.api_client.call_api(resource_path, 'GET',\n path_params,\n query_params,\n header_params,\n body=body_params,\n post_params=form_params,\n files=local_var_files,\n response_type='BatchDownloadJobStatusResult',\n auth_settings=auth_settings,\n callback=params.get('callback'))\n return response", "def read_job(job_id):\n logger.debug('web_api/read_job: job_id: {}'.format(job_id))\n response = requests.get(url=\"http://localhost:27131/job_status/read_job\", params={'job_id': job_id})\n job_dict = response.json()\n job = DotMapJob(job_dict)\n return job", "def test_job_info_with_largeid(self):\n response = self.as_connection.job_info(13287138843617152748, aerospike.JOB_SCAN)\n\n assert response[\"status\"] == aerospike.JOB_STATUS_COMPLETED", "def active_batch_id(self):\n return self.execution_engine.active_batch_data_id", "def fetch(critic, batch_id):\n import api.impl\n assert isinstance(critic, api.critic.Critic)\n assert isinstance(batch_id, int)\n return api.impl.batch.fetch(critic, batch_id)", "def _load_job_ids_from_aws(self):\n with NamedTemporaryFile() as tmp:\n bucket_name, key = parse_bucket_name_key(os.path.join(self.results_bucket, ELB_METADATA_DIR, ELB_AWS_JOB_IDS))\n bucket = self.s3.Bucket(bucket_name)\n try:\n bucket.download_file(key, tmp.name)\n with open(tmp.name) as f_ids:\n self.job_ids = json.load(f_ids)\n except ClientError as err:\n # if the metadata file does not exist, get job ids\n # and save them in metadata\n logging.debug(f'Failed to retrieve {os.path.join(self.results_bucket, ELB_METADATA_DIR, ELB_AWS_JOB_IDS)}')\n if err.response['Error']['Code'] == '404':\n self.job_ids = self.get_job_ids()\n self.upload_job_ids()\n else:\n raise", "def get_metadata(self, taskmanager_id, generation_id, key):\n\n cols = [(x.split())[0] for x in SQLite3DB.tables.get(SQLite3DB.metadata_table)]\n return self._get_table_row(SQLite3DB.metadata_table, taskmanager_id,\n generation_id, key, cols)", "def get_object_metadatainfo(self, object_id):\n \n self.prepareThread()\n logger.info(\"Getting MetaData for object {%s}\", object_id)\n return getRuntime().get_metadata(object_id)", "def get_batch(self, data_asset_name, expectation_suite_name, batch_kwargs=None, **kwargs):\n normalized_data_asset_name = self.normalize_data_asset_name(data_asset_name)\n\n datasource = self.get_datasource(normalized_data_asset_name.datasource)\n if not datasource:\n raise ge_exceptions.DataContextError(\n \"Can't find datasource {} in the config - please check your {}\".format(\n normalized_data_asset_name,\n self.GE_YML\n )\n )\n\n if batch_kwargs is None:\n batch_kwargs = self.build_batch_kwargs(data_asset_name, **kwargs)\n\n data_asset = datasource.get_batch(normalized_data_asset_name,\n expectation_suite_name,\n batch_kwargs,\n **kwargs)\n return data_asset", "def active_batch(self):\n active_batch_id = self.execution_engine.active_batch_data_id\n active_batch = self.batches.get(active_batch_id) if active_batch_id else None\n return active_batch" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns all metadata associated with parent batch without filtering
def get_child_batch_metadata_all( parent_batch_id, ): response = batch_execution_metadata_table.query( IndexName="ParentBatchIdIndex", KeyConditionExpression=Key(Attributes.PARENT_BATCH_ID).eq(parent_batch_id), ) return response["Items"]
[ "def get_child_batch_metadata(parent_batch_id, metadata_type):\n response = batch_execution_metadata_table.query(\n IndexName=\"ParentBatchIdIndex\",\n KeyConditionExpression=Key(Attributes.PARENT_BATCH_ID).eq(parent_batch_id),\n )\n\n items = []\n for item in response[\"Items\"]:\n if item[Attributes.BATCH_METADATA_TYPE] == metadata_type:\n items.append(item)\n\n return items", "def get_metadata_bulk(dids, inherit=False, *, session: \"Session\"):\n if inherit:\n parent_list = []\n unique_dids = []\n parents = [1, ]\n depth = 0\n for did in dids:\n unique_dids.append((did['scope'], did['name']))\n parent_list.append([(did['scope'], did['name']), ])\n\n while parents and depth < 20:\n parents = []\n for did in list_parent_dids_bulk(dids, session=session):\n scope = did['scope']\n name = did['name']\n child_scope = did['child_scope']\n child_name = did['child_name']\n if (scope, name) not in unique_dids:\n unique_dids.append((scope, name))\n if (scope, name) not in parents:\n parents.append((scope, name))\n for entry in parent_list:\n if entry[-1] == (child_scope, child_name):\n entry.append((scope, name))\n dids = [{'scope': did[0], 'name': did[1]} for did in parents]\n depth += 1\n unique_dids = [{'scope': did[0], 'name': did[1]} for did in unique_dids]\n meta_dict = {}\n for did in unique_dids:\n try:\n meta = get_metadata(did['scope'], did['name'], plugin='JSON', session=session)\n except exception.DataIdentifierNotFound:\n meta = {}\n meta_dict[(did['scope'], did['name'])] = meta\n for dids in parent_list:\n result = {'scope': dids[0][0], 'name': dids[0][1]}\n for did in dids:\n for key in meta_dict[did]:\n if key not in result:\n result[key] = meta_dict[did][key]\n yield result\n else:\n condition = []\n for did in dids:\n condition.append(and_(models.DataIdentifier.scope == did['scope'],\n models.DataIdentifier.name == did['name']))\n try:\n for chunk in chunks(condition, 50):\n stmt = select(\n models.DataIdentifier\n ).with_hint(\n models.DataIdentifier, \"INDEX(DIDS DIDS_PK)\", 'oracle'\n ).where(\n or_(*chunk)\n )\n for row in session.execute(stmt).scalars():\n yield row.to_dict()\n except NoResultFound:\n raise exception.DataIdentifierNotFound('No Data Identifiers found')", "def parents(self, cached):\n\n data = []\n for motif in cached['motifs']:\n for parent in motif['parents']:\n data.append({\n 'ml_release_id': cached['release'],\n 'motif_id': motif['motif_id'],\n 'parent_ml_release_id': cached['parent'],\n 'parent_motif_id': parent['name']['full'],\n })\n return data", "def _metadata(self):\n return [antenna._metadata for antenna in self]", "def batch_data(self):\n return self.container['batch_data']", "def get_items_sequential_metadata(self):\n return # osid.Metadata", "def flattened_metadata(self):\n self.__log.call()\n\n snapshot = self.metadata_snapshot\n snapshot.pop(\"__custom\") # already incorporated into each track\n\n # to \"flatten\" the metadata, just add the album metadata to each track\n flattened = snapshot.pop(\"__tracks\")[1:] # zero-based indexing here\n for i in range(len(flattened)):\n flattened[i].update(snapshot)\n\n self.__log.return_(flattened)\n return flattened", "def walk_parents(self):\n active = self.parent_datasets[:]\n while active:\n d = active.pop()\n yield d\n active += d.parent_datasets", "def get_metadata(self):\r\n return self.manager.get_metadata(self, node=self)", "def metadata(self):\n return self.Model.metadata", "def __read_metadata():\n\n batch_number = 140010\n training_example_file_name = find_training_file(\n top_training_dir_name=TOP_TRAINING_DIR_NAME, batch_number=batch_number,\n raise_error_if_missing=True)\n training_example_dict = read_input_examples(\n netcdf_file_name=training_example_file_name, metadata_only=True)\n\n for this_key in training_example_dict:\n print '{0:s} ... {1:s}\\n'.format(\n this_key, str(training_example_dict[this_key]))", "def get_batch_metadata(batch_id):\n response = batch_execution_metadata_table.get_item(\n Key={\n Attributes.BATCH_ID: batch_id,\n },\n )\n return response[\"Item\"] if \"Item\" in response else None", "def _extract_file_entity_metadata(syn, allFiles, *, provenance_cache=None):\n keys = list(DEFAULT_GENERATED_MANIFEST_KEYS)\n annotKeys = set()\n data = []\n for entity in allFiles:\n row = {\n \"parent\": entity[\"parentId\"],\n \"path\": entity.get(\"path\"),\n \"name\": entity.name,\n \"id\": entity.id,\n \"synapseStore\": entity.synapseStore,\n \"contentType\": entity[\"contentType\"],\n }\n row.update(\n {\n key: (val[0] if len(val) > 0 else \"\")\n for key, val in entity.annotations.items()\n }\n )\n\n entity_id = entity[\"id\"]\n row_provenance = (\n provenance_cache.get(entity_id) if provenance_cache is not None else None\n )\n if row_provenance is None:\n row_provenance = _get_file_entity_provenance_dict(syn, entity)\n\n if provenance_cache is not None:\n provenance_cache[entity_id] = row_provenance\n\n row.update(row_provenance)\n\n annotKeys.update(set(entity.annotations.keys()))\n\n data.append(row)\n keys.extend(annotKeys)\n return keys, data", "def _get_target_scan_ids_for_parent(self, parent: dict) -> Dict:\n # This method does not have an iterator and is not public as the API it invokes has not been publicly documented.\n # However, the API is in use in the Tenable Vulnerability Management UI.\n\n parent_scan_id = parent[\"parent_scan_id\"]\n parent_finalized_at = parent[\"parent_finalized_at\"]\n\n offset = 0\n limit = 200\n\n # initialize the flattened responses list\n flattened_list = []\n\n while True:\n # Fetch the page\n response = self._api.post(\n path=f\"was/v2/scans/{parent_scan_id}/vulnerabilities/by-targets/search?limit={limit}&offset={offset}\"\n ).json()\n\n # Collect the items; flatten; and write to the flattened list (extend).\n items_in_response = response[\"items\"]\n items = [{\n \"items\": item,\n \"parent_finalized_at\": parent_finalized_at\n } for item in items_in_response]\n\n flattened_list.extend(items)\n\n # Increment the page number by limit\n offset += limit\n\n if not items_in_response:\n self._log.debug(f\"Stopping the iteration as we encountered an empty response from the API.\")\n break\n\n self._log.debug(f\"Parent ID: {parent_scan_id} has {len(flattened_list)} target ID(s).\")\n\n return flattened_list", "def metadata_nest(metadata):\n metadata_nested = dict()\n for unique_attr_label, v in metadata.items():\n label, trial_idx, call_idx = decode_unique_md_label(unique_attr_label)\n if not label in metadata_nested:\n metadata_nested[label] = dict()\n metadata_nested[label][unique_attr_label] = v\n return metadata_nested", "def get_children():\n data = Child.objects()\n return {'success': True, 'count': len(data), 'data': data}, 200", "def get_child_file_records(record):\n \n result = []\n \n queue = [record]\n while queue :\n dataset = queue.pop()\n if \"referenced_file_id\" in dataset :\n if isinstance(dataset.referenced_file_id.value, basestring) :\n # Normalize to a list with one element\n dataset.referenced_file_id = [dataset.referenced_file_id.value]\n result.append(dataset)\n queue.extend(dataset.children)\n \n return result", "def get_metadata(self):\n self.METADATA = []\n for file in self.METADATA_FILE_NAMES:\n self.METADATA.append(pd.read_csv(file))", "def genome_properties(self):\n child_identifiers = self.property_identifiers\n return [child_property for child_property in self.parent.children if child_property.id in child_identifiers]" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates the status of a given batch_execution_job_id
def update_batch_status( batch_execution_job_id, status, ): response = batch_execution_metadata_table.update_item( Key={ Attributes.BATCH_ID: batch_execution_job_id, }, UpdateExpression="set #st=:s", ExpressionAttributeValues={ ":s": status, }, ExpressionAttributeNames={ "#st": Attributes.BATCH_STATUS, }, ) return response
[ "def update_batch_status(batch_id, status, error_message=\"\"):\n\n response = batch_execution_metadata_table.update_item(\n Key={\n Attributes.BATCH_ID: batch_id,\n },\n UpdateExpression=\"set #st=:s, #errorMessage=:message\",\n ExpressionAttributeValues={\":s\": status, \":message\": error_message},\n ExpressionAttributeNames={\n \"#st\": Attributes.BATCH_STATUS,\n \"#errorMessage\": Attributes.MESSAGE,\n },\n )\n return response", "def update_job_status():\n payload = request.json\n logger.info(\n \"REQUEST: Runner want to update job %i to status %s\",\n payload[\"identifier\"], payload[\"status\"])\n if not is_status_valid(payload[\"status\"]):\n logger.error(\"Status is not valid\")\n return jsonify(\n error=f\"Invalid value for status {payload['status']}\"\n ), 400\n try:\n app.schedule.update_job_status(payload[\"identifier\"], payload[\"status\"])\n logger.info(\"RESPONSE: Updated job status\")\n return jsonify(), 204\n except IndexError as err:\n logger.error(err)\n return jsonify(\n error=f\"Resource Job #{payload['identifier']} not found\"\n ), 404", "def update_job_status(jid, new_status):\n jid, status, store_input, start_date, end_date = rd_jobs.hmget(_generate_job_key(jid), 'id', 'status', 'store_input', 'start_date', 'end_date')\n job = _instantiate_job(jid, status, store_input, start_date, end_date)\n \n if(new_status == 'in progress'):\n worker_IP = os.environ.get('WORKER_IP')\n print(worker_IP)\n rd_jobs.hset(_generate_job_key(jid), 'worker', worker_IP)\n\n if job:\n job['status'] = new_status\n _save_job(_generate_job_key(job['id']), job)\n else:\n raise Exception()", "def export_setJobStatusBulk( self, jobID, statusDict ):\n jobReport = RPCClient( 'WorkloadManagement/JobStateUpdate' )\n jobStatus = jobReport.setJobStatusBulk( jobID, statusDict )\n return jobStatus", "def update_job_status(jid, newstatus): # update the status of the job by altering the dictionary\n# jid, status, start, end = rd.hmget(generate_job_key(jid), 'id', 'status', 'start', 'end')\n olddict = rd.hgetall(generate_job_key(jid))\n print(olddict) \n job = _instantiate_job(jid, olddict, 'status', newstatus) # returns a job dictionary\n if job:\n _save_job(generate_job_key(jid), job)\n else:\n raise Exception()", "def export_setJobStatus( self, jobID, status, minorStatus, source = 'Unknown', datetime = None ):\n jobReport = RPCClient( 'WorkloadManagement/JobStateUpdate' )\n jobStatus = jobReport.setJobStatus( int( jobID ), status, minorStatus, source, datetime )\n return jobStatus", "def update_job(id, data: dict):\n request(\"PATCH\", \"jobs/{}\".format(id), json=data)", "def test_api_can_update_a_job(self):\r\n jobs = ReplicationJobs.objects.get(jobStatus='TESTING5')\r\n change_bucketlist = {'jobStatus': 'TESTING6',\r\n 'cronStr': 'required',\r\n 'destField': 'TST', \r\n 'destTableName': 'dummytab', \r\n 'destSchema': 'dummySchema'}\r\n res = self.client.put(\r\n reverse('job_details', kwargs={'jobid': jobs.jobid}),\r\n change_bucketlist, format='json'\r\n )\r\n # print 'update result', res.content\r\n\r\n self.assertEqual(res.status_code, status.HTTP_200_OK)", "def _update_workflow_status(workflow_uuid, status, logs):\n Workflow.update_workflow_status(Session, workflow_uuid,\n status, logs, None)", "def update_job(self, JobId: str, Manifest: str, JobType: str, ValidateOnly: bool, APIVersion: str = None) -> Dict:\n pass", "def job_submitted(self, job, jobid):\n self.job_set_status(job, 'SUBMIT', \"batchjobid={}\".format(jobid))", "def update_status(self, id, status, finish_time):\n with sqlite3.connect(self.path) as connect:\n cursor = connect.cursor()\n cursor.execute(\"\"\"\n UPDATE Jobs SET Status=(?), FinishTime=(?)\n WHERE ID=(?)\n \"\"\",\n (status, finish_time, id))", "def device_batch_job_id(self, device_batch_job_id):\n\n self._device_batch_job_id = device_batch_job_id", "def test_set_job_status(self):\n response = self.client.patch(\n self.url, headers=self.headers,\n data=json.dumps(self.patch_request_body)\n )\n self.assertEqual(200, response.status_code)\n response = self.client.get(self.url, headers=self.headers)\n self.assertEqual(response.status_code, 200)\n response_body = json.loads(response.data.decode('utf-8'))\n self.assertEqual('WORKING', response_body['data']['status'])", "def mongo_update_task_status(job_id, task_id, status):\n response = mongo.db.tasks.update_one(\n {'job_id': job_id, 'task_id': task_id},\n {'$set': {'task_status': status}})\n return response", "def onboard_task_update(context, task_id, values, session=None):\n values = dict([(k, v) for k, v in values.iteritems() if v is not None])\n status = values.get('status', '')\n #If this is a final status, then set the end date/time\n if status == 'completed' or status == 'failed':\n values['ended'] = timeutils.utcnow()\n if not session:\n session = nova_db_sa_api.get_session()\n with session.begin():\n query = model_query(\n context, pvc_models.OnboardTaskDTO, session=session)\n task_ref = query.filter_by(id=task_id).first()\n task_ref.update(values)\n task_ref.save(session=session)\n return task_ref", "def update_running_jobs(self, condor_jobs):\n self.logger.info('Will update job info in the local storage')\n all_items = self.storage.get_all()\n for validation_name, storage_item in all_items.iteritems():\n self.logger.info('Updating %s information in local storage', validation_name)\n running = storage_item['running']\n for threads, threads_dict in running.iteritems():\n if threads_dict.get('condor_status') == 'DONE':\n continue\n\n condor_id = str(threads_dict['condor_id'])\n current_status = threads_dict.get('condor_status', '<unknown>')\n new_status = condor_jobs.get(condor_id, 'DONE')\n if current_status != new_status:\n threads_dict['condor_status'] = new_status\n self.logger.info('%s %s threads job changed to %s',\n validation_name,\n threads,\n new_status)\n self.storage.save(validation_name, storage_item)\n\n self.logger.info('Updated local storage:')\n all_items = self.storage.get_all()\n for validation_name, storage_item in all_items.iteritems():\n stage = storage_item['stage']\n self.logger.info(' %s is at stage %s:', validation_name, stage)\n running = storage_item['running']\n for threads in list(sorted(running.keys())):\n threads_dict = running[threads]\n self.logger.info(' Threads: %s, attempt: %s, status: %s, HTCondor ID: %s',\n threads,\n threads_dict.get('attempt_number'),\n threads_dict.get('condor_status'),\n threads_dict.get('condor_id'))", "def update(self):\n self._job = pyslurm.job().find_id(str(self.id))[0]", "def update_final_job_logstatus():\n list = [\"deleted\", \"killed\"]\n pcjs = bm.Job.objects.filter(log_extracted='no')\n pcjs = pcjs.filter(status__in=list)\n dt = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n for job in pcjs:\n bm.Job.objects.filter(job_id=job.job_id).update(\n log_extracted='fail')\n bm.Job.objects.filter(job_id=job.job_id).update(\n update_time=dt)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates the step token of the given batch. Used for async waiting in step function invocations.
def update_batch_step_token( batch_id, step_token, ): response = batch_execution_metadata_table.update_item( Key={ Attributes.BATCH_ID: batch_id, }, UpdateExpression="set #st=:s", ExpressionAttributeValues={ ":s": step_token, }, ExpressionAttributeNames={ "#st": Attributes.STATE_TOKEN, }, ) return response
[ "def step_pointer(caller, step=1):\r\n ptr = caller.ndb.batch_stackptr\r\n stack = caller.ndb.batch_stack\r\n nstack = len(stack)\r\n if ptr + step <= 0:\r\n caller.msg(\"{RBeginning of batch file.\")\r\n if ptr + step >= nstack:\r\n caller.msg(\"{REnd of batch file.\")\r\n caller.ndb.batch_stackptr = max(0, min(nstack - 1, ptr + step))", "def post_step(self, step, session): # pylint: disable=unused-argument\n _ = step, session", "def _set_up_new_batch(self, *_):\n self.batch = []", "def set_batch_arg(self, arg, value):\n if not self.batch:\n raise SmartSimError(\"Not running as batch, cannot set batch_arg\")\n # TODO catch commonly used arguments we use for SmartSim here\n self.batch_settings.batch_args[arg] = value", "def increment_step(self):\n self.current_step += 1", "def _update_step(self, sess):\n assert self._ops_added\n sess.run([self._assign_op], feed_dict = {self._steps_placeholder: self._steps})\n self._step_needs_update = False", "def set_batch(self, batch: t.Optional[jank.graphics.Batch]):", "def _next_update_token(self):\n ut = get_update_token(get_replacement_token(self.seed, self.length))\n self.length += 1\n return ut", "def step_sequence(self, seq=[]):\n self.__stepSequence = seq", "def update_numerator_batch(self, batch_idx, batch):\n for point_idx, point in enumerate(batch):\n sample_idx = point_idx + self._batch_size * batch_idx\n self.update_numerator(sample_idx, point)", "def process_batch(self, batch: BatchType) -> None:\n raise NotImplementedError", "def set_Token(self, value):\n super(UpdateTicketInputSet, self)._set_input('Token', value)", "def run_eval_step(self, sess, batch):\n feed_dict = self._make_feed_dict(batch)\n to_return = {\n 'summaries': self._summaries,\n 'loss': self._loss,\n 'acc': self._acc,\n 'global_step': self.global_step,\n }\n return sess.run(to_return, feed_dict)", "def do_steps():\n step = release_data.get(\"step-number\", 0)\n RELEASE_STEPS[step]()\n step = step+ 1\n if step == len(RELEASE_STEPS):\n release_data.clear()\n else:\n release_data[\"step-number\"] = step\n utils.save_release_data(release_data)", "def set_batch_amount(amount):\n global _implicit_gen_txn_nonce\n assert isinstance(amount, int)\n _implicit_gen_txn_nonce = amount", "def step(self):\n self.state[self.curr_iter] =\\\n self.iter_func(self.state[self.curr_iter - 1])\n self.curr_iter += 1", "def onBatchStarted(self, batchStarted):\n pass", "def update_batch_status(\n batch_execution_job_id,\n status,\n):\n response = batch_execution_metadata_table.update_item(\n Key={\n Attributes.BATCH_ID: batch_execution_job_id,\n },\n UpdateExpression=\"set #st=:s\",\n ExpressionAttributeValues={\n \":s\": status,\n },\n ExpressionAttributeNames={\n \"#st\": Attributes.BATCH_STATUS,\n },\n )\n return response", "def general_step(self, batch, batch_idx, runner: metrics.RunNNMetrics, step_name: str):\n bg, labels = batch\n\n #prediction = self.model(bg)\n #loss = self.loss_fn(prediction, labels)\n\n return loss, prediction, labels" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Inserts new batch metadata input post First level job
def insert_batch_metadata_input( batch_id, parent_batch_id, down_sampling_rate, input_manifest, batch_status ): dynamo_db_item = { Attributes.BATCH_ID: batch_id, Attributes.DOWN_SAMPLING_RATE: Decimal(str(down_sampling_rate)), Attributes.BATCH_METADATA_TYPE: BatchMetadataType.HUMAN_INPUT_METADATA, Attributes.JOB_OUTPUT_LOCATION: input_manifest, Attributes.PARENT_BATCH_ID: parent_batch_id, Attributes.BATCH_STATUS: batch_status, } return batch_execution_metadata_table.put_item(Item=dynamo_db_item)
[ "def _set_up_new_batch(self, *_):\n self.batch = []", "def batch_insert_push(self, batch_data):\n data = self.data\n for key, value in batch_data.items():\n data[key] = value", "def _insert_metadata(self, metadata):\n kwargs = {\n 'output': self.output,\n }\n\n for key, metadata_key in LOSS_MAP_METADATA_KEYS:\n kwargs[key] = metadata.get(metadata_key)\n\n self.metadata = models.LossMap(**kwargs)\n\n self.metadata.save()", "def batch_data(self, batch_data):\n\n self.container['batch_data'] = batch_data", "def _store_batch_metadata(conn, batch_metadata_table, todo_batch_metadata_table, ts_nodash_col, ts_nodash, source_table, partitions=None, run_id=None, batch_metadata=None):\n partitions = [] if partitions is None else partitions\n if partitions:\n partition_columns = partitions[0].keys()\n if ts_nodash_col in frozenset(partition_columns):\n raise ValueError('Partition columns should not include ts_nodash_col')\n for partition in partitions:\n if frozenset(partition.keys()) ^ frozenset(partition_columns):\n raise ValueError('The same partition columns should be used for each partition')\n else:\n partition_columns = []\n sql_batches_not_earlier = \"\"\"\n SELECT \n IDENTIFIER(%(ts_nodash_col)s)\n {partition_columns:s}\n FROM IDENTIFIER(%(batch_metadata_table)s)\n WHERE \n IDENTIFIER(%(ts_nodash_col)s) >= %(ts_nodash)s\n {partitions_clause:s}\n \"\"\".format(\n partition_columns=', ' + '\\n , '.join(partition_columns) if partitions else '',\n partitions_clause = _get_or_clauses_partitions(partitions) if partitions else ''\n )\n params={'ts_nodash_col': ts_nodash_col, 'ts_nodash': ts_nodash, 'batch_metadata_table': batch_metadata_table}\n if partitions:\n params.update({f'__value_partition_{i:d}_column_{col}__': v for i, partition in enumerate(partitions) for col, v in partition.items()})\n rows = run_and_fetchall(conn, sql_batches_not_earlier, params=params)\n if rows:\n raise ValueError(f'Batches found that were no earlier than candidate batch')\n \n sql_insert = \"\"\"\n INSERT INTO IDENTIFIER(%(todo_batch_metadata_table)s)\n (\n {ts_nodash_col:s}\n {partition_columns:s}\n , _scd_source_table\n , _scd_created_by\n , _scd_batch_metadata\n )\n SELECT \n column1 AS {ts_nodash_col:s}\n {column_i_as_partition_columns:s}\n , column{n_partition_columns_plus_two:d} AS _scd_source_table\n , column{n_partition_columns_plus_three:d} AS _scd_created_by\n , parse_json(column{n_partition_columns_plus_four:d}) AS _scd_batch_metadata\n FROM \n VALUES\n {partitions_or_batch_values:s}\n \"\"\".format(\n ts_nodash_col=ts_nodash_col,\n partition_columns=', ' + '\\n , '.join(partition_columns) if partitions else '',\n column_i_as_partition_columns='' if not partitions else ', ' + '\\n ,'.join([f'column{i + 2:d} AS {col}' for i, col in enumerate(partition_columns)]),\n n_partition_columns_plus_two=len(partition_columns) + 2,\n n_partition_columns_plus_three=len(partition_columns) + 3,\n n_partition_columns_plus_four=len(partition_columns) + 4,\n partitions_or_batch_values=\"\"\"\n (\n %(ts_nodash)s\n , %(source_table)s\n , %(run_id)s\n , %(batch_metadata_json)s\n )\n \"\"\" if not partitions else _get_partitions_values(partitions, partition_columns)\n )\n params = {'todo_batch_metadata_table': todo_batch_metadata_table, 'ts_nodash': ts_nodash, 'source_table': source_table, 'run_id': run_id, 'batch_metadata_json': json.dumps(batch_metadata)}\n if partitions:\n params.update({f'__value_partition_{i:d}_column_{col}__': v for i, partition in enumerate(partitions) for col, v in partition.items()})\n run(conn, sql_insert, params=params)", "def set_metadata(self, jobid, metadata):", "def job_metadata_importer(*, db_conn, command, run_id, subcommand=None, status,\n start_time='2017-08-15 01:15:39.54785+00', extra_metadata={}, **other):\n with db_conn, db_conn.cursor() as cursor:\n cursor.execute(\"\"\"INSERT INTO job_metadata(command, run_id, subcommand, db_user, command_line,\n start_time, status, extra_metadata)\n VALUES(%s, %s, %s, 'test_user', %s, %s, %s, %s)\n RETURNING command, run_id\"\"\",\n [command, run_id, subcommand, ' '.join(sys.argv), start_time, status,\n json.dumps(extra_metadata)])\n job_metadata_pk = [(x.command, x.run_id) for x in cursor.fetchall()]\n return job_metadata_pk[0]", "def submit_metadata(self):\n\n print(\"Submitting data\")\n\n # Commented\n # Only required for one time submission of summary_location\n # print(\"Submitting summary_location data\")\n # for loc in self.summary_locations:\n # loc_record = {\"type\": \"summary_location\"}\n # loc_record.update(loc)\n # self.metadata_helper.add_record_to_submit(loc_record)\n # self.metadata_helper.batch_submit_records()\n\n print(\"Submitting summary_report data\")\n for rep in self.summary_reports:\n rep_record = {\"type\": \"summary_report\"}\n rep_record.update(rep)\n self.metadata_helper.add_record_to_submit(rep_record)\n self.metadata_helper.batch_submit_records()", "def submit_batch(self, command):\n pass", "def _store_batch_metadata(conn, batch_metadata_table, ts_nodash_col, ts_nodash, partitions=None, run_id=None, batch_metadata=None):\n partitions = [] if partitions is None else partitions\n if partitions:\n partition_columns = partitions[0].keys()\n if ts_nodash_col in frozenset(partition_columns):\n raise ValueError('Partition columns should not include ts_nodash_col')\n for partition in partitions:\n if frozenset(partition.keys()) ^ frozenset(partition_columns):\n raise ValueError('The same partition columns should be used for each partition')\n else:\n partition_columns = []\n sql_batches_not_earlier = \"\"\"\nSELECT \n IDENTIFIER(%(ts_nodash_col)s)\n {partition_columns:s}\nFROM IDENTIFIER(%(batch_metadata_table)s)\nWHERE \n IDENTIFIER(%(ts_nodash_col)s) >= %(ts_nodash)s\n {partitions_clause:s}\n\"\"\".format(\n partition_columns=', ' + '\\n , '.join(partition_columns) if partitions else '',\n partitions_clause = _get_or_clauses_partitions(partitions) if partitions else ''\n )\n params={'ts_nodash_col': ts_nodash_col, 'ts_nodash': ts_nodash, 'batch_metadata_table': batch_metadata_table}\n if partitions:\n params.update({f'__value_partition_{i:d}_column_{col}__': v for i, partition in enumerate(partitions) for col, v in partition.items()})\n rows = run_and_fetchall(conn, sql_batches_not_earlier, params=params)\n if rows:\n raise ValueError(f'Batches found that were no earlier than candidate batch')\n \n sql_insert = \"\"\"\nINSERT INTO IDENTIFIER(%(batch_metadata_table)s)\n(\n {ts_nodash_col:s}\n {partition_columns:s}\n , _scd_created_by\n , _scd_batch_metadata\n)\nSELECT \n column1 AS {ts_nodash_col:s}\n {column_i_as_partition_columns:s}\n , column{n_partition_columns_plus_two:d} AS _scd_created_by\n , parse_json(column{n_partition_columns_plus_three:d}) AS _scd_batch_metadata\nFROM \nVALUES\n{partitions_or_batch_values:s}\n\"\"\".format(\n ts_nodash_col=ts_nodash_col,\n partition_columns=', ' + '\\n , '.join(partition_columns) if partitions else '',\n column_i_as_partition_columns='' if not partitions else ', ' + '\\n ,'.join([f'column{i + 2:d} AS {col}' for i, col in enumerate(partition_columns)]),\n n_partition_columns_plus_two=len(partition_columns) + 2,\n n_partition_columns_plus_three=len(partition_columns) + 3,\n partitions_or_batch_values=\"\"\"\n(\n %(ts_nodash)s\n , %(run_id)s\n , %(batch_metadata_json)s\n)\n\"\"\" if not partitions else _get_partitions_values(partitions, partition_columns)\n )\n params = {'batch_metadata_table': batch_metadata_table, 'ts_nodash': ts_nodash, 'run_id': run_id, 'batch_metadata_json': json.dumps(batch_metadata)}\n if partitions:\n params.update({f'__value_partition_{i:d}_column_{col}__': v for i, partition in enumerate(partitions) for col, v in partition.items()})\n run(conn, sql_insert, params=params)", "def store_job_meta(self, mol_db_id):\n logger.info('Storing job metadata')\n rows = [(mol_db_id, self._ds.id, JobStatus.RUNNING, datetime.now().strftime('%Y-%m-%d %H:%M:%S'))]\n self._job_id = self._db.insert_return(JOB_INS, rows=rows)[0]", "def _create_job_info(self, job_dir):\n meta = self._build_job_meta(job_dir)\n\n self.logger.debug(\"Create job: %s\" % meta)\n\n job_record = JobRecord.from_json(meta)\n job_record.save()", "def _append_pre_metadata_to_dataset(self, pre_metadata):\n self._dataset['pre_metadata'].append(pre_metadata)", "def test_017_queue_insert_metadata_size65536(self):\n url = self.cfg.base_url + '/queues/qtestqueue/metadata'\n doc = functionlib.get_custom_body({\"metadatasize\": 65536})\n result = http.put(url, self.header, doc)\n\n self.assertEqual(result.status_code, 204)\n\n result = http.get(url, self.header)\n self.assertEqual(result.status_code, 200)\n self.assertEqual(result.json(), json.loads(doc))", "def on_batch_begin(self, **fit_kwargs):", "def process_batch(self, batch: BatchType) -> None:\n raise NotImplementedError", "def store_gafqmc_info_metadata(info, hdf5_job_rec):\n pass", "def startBatch(self, reader=None):", "def onBatchSubmitted(self, batchSubmitted):\n pass" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates the status of a given batch_id
def update_batch_status(batch_id, status, error_message=""): response = batch_execution_metadata_table.update_item( Key={ Attributes.BATCH_ID: batch_id, }, UpdateExpression="set #st=:s, #errorMessage=:message", ExpressionAttributeValues={":s": status, ":message": error_message}, ExpressionAttributeNames={ "#st": Attributes.BATCH_STATUS, "#errorMessage": Attributes.MESSAGE, }, ) return response
[ "def update_batch_status(\n batch_execution_job_id,\n status,\n):\n response = batch_execution_metadata_table.update_item(\n Key={\n Attributes.BATCH_ID: batch_execution_job_id,\n },\n UpdateExpression=\"set #st=:s\",\n ExpressionAttributeValues={\n \":s\": status,\n },\n ExpressionAttributeNames={\n \"#st\": Attributes.BATCH_STATUS,\n },\n )\n return response", "def update(self, dataset_id: str, status: str):\n try:\n logging.info(\"CRUDDataImport update function\")\n with session() as transaction_session:\n obj: DataImport = (\n transaction_session.query(DataImport)\n .filter(DataImport.dataset_id == dataset_id)\n .first()\n )\n if obj:\n obj.status = status\n transaction_session.commit()\n transaction_session.refresh(obj)\n except Exception as error:\n logging.error(f\"Error in CRUDDataImport update function : {error}\")\n raise error", "def update_job_status():\n payload = request.json\n logger.info(\n \"REQUEST: Runner want to update job %i to status %s\",\n payload[\"identifier\"], payload[\"status\"])\n if not is_status_valid(payload[\"status\"]):\n logger.error(\"Status is not valid\")\n return jsonify(\n error=f\"Invalid value for status {payload['status']}\"\n ), 400\n try:\n app.schedule.update_job_status(payload[\"identifier\"], payload[\"status\"])\n logger.info(\"RESPONSE: Updated job status\")\n return jsonify(), 204\n except IndexError as err:\n logger.error(err)\n return jsonify(\n error=f\"Resource Job #{payload['identifier']} not found\"\n ), 404", "def setStatus(self, booking_id, status):\n data = (status, booking_id)\n self.cursor.execute(\"UPDATE bookings SET status=? WHERE id=?\", data)\n self.database.commit()", "def _update_workflow_status(workflow_uuid, status, logs):\n Workflow.update_workflow_status(Session, workflow_uuid,\n status, logs, None)", "def update_status(self, id, status, finish_time):\n with sqlite3.connect(self.path) as connect:\n cursor = connect.cursor()\n cursor.execute(\"\"\"\n UPDATE Jobs SET Status=(?), FinishTime=(?)\n WHERE ID=(?)\n \"\"\",\n (status, finish_time, id))", "def batch_status(self, request, context):\n context.code(beta_interfaces.StatusCode.UNIMPLEMENTED)", "def put(self, id):\n parser = reqparse.RequestParser()\n parser.add_argument('status',\n type=str,\n )\n args = parser.parse_args()\n status = args['status']\n incident = model.get_specific_incident(id)\n if incident:\n model.update_incident_status(status, id)\n return({\"message\":\"status updated\",\"status\":status}),201\n return ({\"message\":\"incident not found\"}),201", "def export_setJobStatusBulk( self, jobID, statusDict ):\n jobReport = RPCClient( 'WorkloadManagement/JobStateUpdate' )\n jobStatus = jobReport.setJobStatusBulk( jobID, statusDict )\n return jobStatus", "def update_job_status(jid, new_status):\n jid, status, store_input, start_date, end_date = rd_jobs.hmget(_generate_job_key(jid), 'id', 'status', 'store_input', 'start_date', 'end_date')\n job = _instantiate_job(jid, status, store_input, start_date, end_date)\n \n if(new_status == 'in progress'):\n worker_IP = os.environ.get('WORKER_IP')\n print(worker_IP)\n rd_jobs.hset(_generate_job_key(jid), 'worker', worker_IP)\n\n if job:\n job['status'] = new_status\n _save_job(_generate_job_key(job['id']), job)\n else:\n raise Exception()", "def update_order_status(self, order_id, status):\n sql = (\n \"\"\"\n UPDATE orders SET status = '{}' WHERE order_id = '{}'\n \"\"\".format(status, order_id)\n )\n self.cur.execute(sql)\n self.conn.commit()", "def mongo_update_task_status(job_id, task_id, status):\n response = mongo.db.tasks.update_one(\n {'job_id': job_id, 'task_id': task_id},\n {'$set': {'task_status': status}})\n return response", "def update_batches(self):\n with self._commit_lock:\n self._update_batches_force()", "def test_route_change_status_by_id(self):\n print(\"In method\", self._testMethodName)\n description = 'TesteUpdateStatus'\n status = False\n self.app_test.post('/insert', data=dict(description=description,\n status=status))\n task = self.db.find_one({\"description\": description})\n self.app_test.put('/change-status-by-id/' + str(task.get('_id')))\n task = self.db.find_one({\"_id\": task.get('_id')})\n\n self.assertEqual(True, task.get('status'))", "def update_job_status(jid, newstatus): # update the status of the job by altering the dictionary\n# jid, status, start, end = rd.hmget(generate_job_key(jid), 'id', 'status', 'start', 'end')\n olddict = rd.hgetall(generate_job_key(jid))\n print(olddict) \n job = _instantiate_job(jid, olddict, 'status', newstatus) # returns a job dictionary\n if job:\n _save_job(generate_job_key(jid), job)\n else:\n raise Exception()", "def update_status(self, status, context=None):\n if status not in ACCEPTABLE_STATUS:\n raise ValueError('Invalid status value {}'.format(status))\n try:\n jsonapi.dumps(context)\n except TypeError:\n raise ValueError('Context must be JSON serializable.')\n\n status_changed = status != self._status\n self._status = status\n self._context = context\n self._last_updated = format_timestamp(get_aware_utc_now())\n\n if status_changed and self._status_changed_callback:\n print(self._status_changed_callback())", "def _set_timeline_status(timeline_id, status, error_msg=None):\n timeline = Timeline.query.get(timeline_id)\n if not timeline:\n logger.warning(\"Cannot set status: No such timeline\")\n return\n\n list_datasources_status = [\n datasource.get_status for datasource in timeline.datasources\n ]\n\n status = \"\"\n if len(set(list_datasources_status)) == 1 and \"fail\" in list_datasources_status:\n status = \"fail\"\n else:\n if \"processing\" in list_datasources_status:\n status = \"processing\"\n else:\n status = \"ready\"\n\n timeline.set_status(status)\n timeline.searchindex.set_status(status)\n # Commit changes to database\n db_session.add(timeline)\n db_session.commit()", "def put(cls, logged_activity_id):\n payload = request.get_json(silent=True)\n\n if 'status' not in payload:\n return response_builder(dict(message='status is required.'),\n 400)\n\n logged_activity = LoggedActivity.query.filter_by(\n uuid=logged_activity_id).first()\n if not logged_activity:\n return response_builder(dict(message='Logged activity not found'),\n 404)\n\n if not (payload.get('status') in ['pending', 'rejected']):\n return response_builder(dict(message='Invalid status value.'),\n 400)\n logged_activity.status = payload.get('status')\n logged_activity.save()\n\n return response_builder(\n dict(data=single_logged_activity_schema.dump(logged_activity).data,\n message=\"successfully changed status\"),\n 200)", "def export_setJobStatus( self, jobID, status, minorStatus, source = 'Unknown', datetime = None ):\n jobReport = RPCClient( 'WorkloadManagement/JobStateUpdate' )\n jobStatus = jobReport.setJobStatus( int( jobID ), status, minorStatus, source, datetime )\n return jobStatus" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Append new down_sample location to the existing batchId
def update_batch_down_sample_location( batch_id, down_sample_location, ): response = batch_execution_metadata_table.update_item( Key={ Attributes.BATCH_ID: batch_id, }, UpdateExpression="set #attr_down_sample_location=:down_sample_location", ExpressionAttributeValues={":down_sample_location": down_sample_location}, ExpressionAttributeNames={ "#attr_down_sample_location": Attributes.JOB_DOWN_SAMPLE_LOCATION }, ) return response
[ "def append(self, ch):\n self.batch.append(ch)\n if 'defrag_collection_est_size' not in ch:\n self.trust_batch_estimation = False\n self.batch_size_estimation += self.chunk_size_estimation\n else:\n self.batch_size_estimation += ch['defrag_collection_est_size']", "def _custom_create_or_extend_grad_sample(\n param: torch.Tensor, grad_sample: torch.Tensor, batch_dim: int\n) -> None:\n \n #print (\"now this happen\")\n \n if hasattr(param, \"grad_sample\"):\n param.grad_sample = param.grad_sample + grad_sample\n #param.grad_sample = torch.cat((param.grad_sample, grad_sample), batch_dim)\n else:\n param.grad_sample = grad_sample", "def collect_batch(self, *args, **kwargs):\n self.samples_np = self.double_buffer[self.sync.db_idx.value]\n return super().collect_batch(*args, **kwargs)", "def mergeWithGenerated(self, batch, generated):\n pass", "def _set_up_new_batch(self, *_):\n self.batch = []", "def add_batch(self, batch):\n batch_size = tf.cast(tf.shape(batch)[0], tf.int64)\n if batch_size >= self._capacity:\n self._current_size.assign(self._capacity)\n self._current_pos.assign(0)\n self._buffer.assign(batch[-self._capacity:, ...])\n elif batch_size + self._current_pos <= self._capacity:\n new_pos = self._current_pos + batch_size\n self._buffer.scatter_update(\n tf.IndexedSlices(batch, tf.range(self._current_pos, new_pos)))\n self._current_pos.assign(new_pos)\n self._current_size.assign(\n tf.minimum(self._current_size + batch_size, self._capacity))\n else:\n first = self._capacity - self._current_pos\n self._buffer.scatter_update(\n tf.IndexedSlices(batch[0:first, ...],\n tf.range(self._current_pos, self._capacity)))\n new_pos = batch_size - first\n self._buffer.scatter_update(\n tf.IndexedSlices(batch[first:, ...], tf.range(0, new_pos)))\n self._current_pos.assign(new_pos)\n self._current_size.assign(self._capacity)", "def _sample_batch(self):\n indices = np.random.choice(self.train_size, self.batch_size, replace=False)\n self._batch_train_x_value = self.train_x[indices, :]\n self._batch_train_y_value = self.train_y[indices, :]", "def batch_data(self, batch_data):\n\n self.container['batch_data'] = batch_data", "def generate_id(self, portal_type, batch_size=None):", "def appendBidsRun(self, run: BidsRun) -> None:\n if run.numIncrementals() == 0:\n return\n\n self._appendIncremental(run.asSingleIncremental())", "def downsample_rate(self) -> int:", "def _store_inserted_ids(self, mapping, job_id, local_ids_for_batch):\n id_table_name = self._reset_id_table(mapping)\n conn = self.session.connection()\n for batch_id, local_ids in local_ids_for_batch.items():\n try:\n results_url = \"{}/job/{}/batch/{}/result\".format(\n self.bulk.endpoint, job_id, batch_id\n )\n # Download entire result file to a temporary file first\n # to avoid the server dropping connections\n with download_file(results_url, self.bulk) as f:\n self.logger.info(\n \" Downloaded results for batch {}\".format(batch_id)\n )\n self._store_inserted_ids_for_batch(\n f, local_ids, id_table_name, conn\n )\n self.logger.info(\n \" Updated {} for batch {}\".format(id_table_name, batch_id)\n )\n except BulkDataException:\n raise\n except Exception as e:\n raise BulkDataException(\n \"Failed to download results for batch {} ({})\".format(\n batch_id, str(e)\n )\n )\n\n self.session.commit()", "def add_sample(self, sample):\n self.samples.append(sample)\n\n if len(self.samples) > self.max_memory:\n self.samples.pop(0)", "def generate_and_insert_data( inputs ):\n global gpudb_ingestor\n\n batch_size, num_batches = inputs\n\n my_id = int(random.random() * 100)\n\n null_percentage = 0.1\n alphanum = (string.ascii_letters + string.digits)\n\n # Nested loop\n # Outer loop controls how many batches of records are added to the ingestor\n for i in range(0, num_batches):\n print (\"thread {_id:>5} outer loop: {i:>5}\".format( _id = my_id, i = i ))\n records = []\n # Inner loop generated records for this batch\n for j in range(0, batch_size):\n _i_plus_j = (i + j)\n record = collections.OrderedDict()\n record[ \"i1\" ] = i * j\n record[ \"i2\" ] = random.randint( -_i_plus_j, _i_plus_j ) if (random.random() >= null_percentage) else None\n record[ \"i8\" ] = random.randint( -128, 127 ) if (random.random() >= null_percentage) else None\n record[ \"i16\" ] = random.randint( -32768, 32767 ) if (random.random() >= null_percentage) else None\n record[ \"d1\" ] = (random.random() * _i_plus_j ) if (random.random() >= null_percentage) else None\n record[ \"f1\" ] = (random.random() * _i_plus_j ) if (random.random() >= null_percentage) else None\n record[ \"l1\" ] = (random.randint( 0,_i_plus_j ) * _i_plus_j ) if (random.random() >= null_percentage) else None\n record[ \"timestamp\" ] = random.randint( -30610239758979, 29379542399999 ) if (random.random() >= null_percentage) else None\n record[ \"s1\" ] = None if (random.random() < null_percentage) \\\n else ''.join( [random.choice( alphanum ) for n in range( 0, random.randint( 2, 200 ) )] )\n record[ \"date\" ] = None if (random.random() < null_percentage) \\\n else strftime( datetime.date( random.randint( 1000, 2900 ), # year\n random.randint( 1, 12 ), # month\n random.randint( 1, 28 ) # day\n ), \"%Y-%m-%d\" )\n record[ \"datetime\" ] = None if (random.random() < null_percentage) \\\n else ( strftime( datetime.date( random.randint( 1000, 2900 ), # year\n random.randint( 1, 12 ), # month\n random.randint( 1, 28 ) # day\n ), \"%Y-%m-%d\" ) \\\n + \" \"\n + ( datetime.time( random.randint( 0, 23 ), # hour\n random.randint( 0, 59 ), # minute\n random.randint( 0, 59 ) # seconds\n ).strftime( \"%H:%M:%S\" ) )\n + (\".%d\" % random.randint( 0, 999 ) ) ) # milliseconds\n record[ \"decimal\" ] = None if (random.random() < null_percentage) \\\n else ( str( random.randint( -922337203685477, 922337203685477 ) )\n + \".\" + str( random.randint( 0, 9999 ) ) )\n record[ \"ipv4\" ] = None if (random.random() < null_percentage) \\\n else '.'.join( [ str( random.randint( 0, 255 ) ) for n in range(0, 4)] )\n record[ \"time\" ] = None if (random.random() < null_percentage) \\\n else ( datetime.time( random.randint( 0, 23 ), # hour\n random.randint( 0, 59 ), # minute\n random.randint( 0, 59 ) # seconds\n ).strftime( \"%H:%M:%S\" ) \\\n + (\".%d\" % random.randint( 0, 999 ) ) ) # milliseconds\n record[ \"c1\" ] = None if (random.random() < null_percentage) \\\n else random.choice( alphanum )\n record[ \"c2\" ] = None if (random.random() < null_percentage) \\\n else ''.join( [random.choice( alphanum ) for n in range( 0, random.randint( 0, 2 ) )] )\n record[ \"c4\" ] = None if (random.random() < null_percentage) \\\n else ''.join( [random.choice( alphanum ) for n in range( 0, random.randint( 0, 4 ) )] )\n record[ \"c8\" ] = None if (random.random() < null_percentage) \\\n else ''.join( [random.choice( alphanum ) for n in range( 0, random.randint( 0, 8 ) )] )\n record[ \"c16\" ] = None if (random.random() < null_percentage) \\\n else ''.join( [random.choice( alphanum ) for n in range( 0, random.randint( 0, 16 ) )] )\n record[ \"c32\" ] = None if (random.random() < null_percentage) \\\n else ''.join( [random.choice( alphanum ) for n in range( 0, random.randint( 0, 32 ) )] )\n record[ \"c64\" ] = None if (random.random() < null_percentage) \\\n else ''.join( [random.choice( alphanum ) for n in range( 0, random.randint( 0, 64 ) )] )\n record[ \"c128\"] = None if (random.random() < null_percentage) \\\n else ''.join( [random.choice( alphanum ) for n in range( 0, random.randint( 0, 128 ) )] )\n record[ \"c256\"] = None if (random.random() < null_percentage) \\\n else ''.join( [random.choice( alphanum ) for n in range( 0, random.randint( 0, 256 ) )] )\n\n # Add the record to the list of records\n records.append( record )\n # end for loop\n\n # Add the records to the ingestor\n gpudb_ingestor.insert_records( records )\n # end generating data\n\n\n # Need to flush here since the gpudb_ingestor of the parent\n # thread won't get this child thread's state\n gpudb_ingestor.flush()", "def batch_size(self, new_batch_size):\n\n self._batch_size = int(new_batch_size)", "def _append_device_id(self, path, device_id):\n if device_id:\n if \"?\" in path:\n path += \"&device_id=%s\" % device_id\n else:\n path += \"?device_id=%s\" % device_id\n return path", "def device_batch_job_id(self, device_batch_job_id):\n\n self._device_batch_job_id = device_batch_job_id", "def insert_batch_metadata_input(\n batch_id, parent_batch_id, down_sampling_rate, input_manifest, batch_status\n):\n\n dynamo_db_item = {\n Attributes.BATCH_ID: batch_id,\n Attributes.DOWN_SAMPLING_RATE: Decimal(str(down_sampling_rate)),\n Attributes.BATCH_METADATA_TYPE: BatchMetadataType.HUMAN_INPUT_METADATA,\n Attributes.JOB_OUTPUT_LOCATION: input_manifest,\n Attributes.PARENT_BATCH_ID: parent_batch_id,\n Attributes.BATCH_STATUS: batch_status,\n }\n\n return batch_execution_metadata_table.put_item(Item=dynamo_db_item)", "def fill_batch_training_information(self, training_logger,\n output_batch):\n training_logger[\"train\"][\"span_start_loss_batch\"].append(output_batch[\"span_start_loss\"].detach().cpu().numpy())\n training_logger[\"train\"][\"span_end_loss_batch\"].append(output_batch[\"span_end_loss\"].detach().cpu().numpy())\n training_logger[\"train\"][\"loss_batch\"].append(output_batch[\"loss\"].detach().cpu().numpy())\n # Training metrics:\n metrics = self.get_metrics()\n training_logger[\"train\"][\"start_acc_batch\"].append(metrics[\"start_acc\"])\n training_logger[\"train\"][\"end_acc_batch\"].append(metrics[\"end_acc\"])\n training_logger[\"train\"][\"span_acc_batch\"].append(metrics[\"span_acc\"])\n training_logger[\"train\"][\"em_batch\"].append(metrics[\"em\"])\n training_logger[\"train\"][\"f1_batch\"].append(metrics[\"f1\"])" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Marks a whole batch as failed, including all children batches.
def mark_batch_and_children_failed( batch_id, error_message="", ): update_batch_status(batch_id, BatchStatus.INTERNAL_ERROR, error_message=error_message) items = get_child_batch_metadata_all(batch_id) for item in items: mark_batch_and_children_failed(item["BatchId"], error_message)
[ "def _handle_unsuccessful_batch(self, batch_id: str, batch: Optional[Dict] = None):\n if not batch:\n # We have to fetch the batch again as the kafka event doesn't currently include the\n # resource details\n try:\n batch = data_loader_helper.batch_get_resource_batches([batch_id])[\n batch_id\n ]\n except HTTPError:\n # In is case we return now and the batch will be treated as missing later as it\n # is not in successful_batches or unsuccessful_batches\n log.warning(\n \"Failed to retrieve unsuccessful batch via REST API. This will be treated as\"\n \"a missing batch in subsequent processing.\"\n )\n return\n\n loaded_accounts = []\n\n # itertools requires us to sort the resources before grouping\n sorted_resources = sorted(\n batch[\"resources\"], key=lambda x: x[\"dependency_group_id\"]\n )\n for _, group in itertools.groupby(\n sorted_resources, key=lambda x: x[\"dependency_group_id\"]\n ):\n # group is an iterator that we process twice, so we store the contents in a list\n resources = [resource for resource in group]\n # We only want to treat a group as successful if all of its resources were loaded\n if any(\n resource\n for resource in resources\n if resource[\"resource_status\"] != \"RESOURCE_STATUS_LOADED\"\n ):\n continue\n\n for resource in resources:\n if \"account_resource\" in resource:\n self.loaded_accounts.append(resource[\"id\"])\n loaded_accounts.append(resource[\"id\"])\n elif \"customer_resource\" in resource:\n self.loaded_customers.append(resource[\"id\"])\n elif \"flag_resource\" in resource:\n self.loaded_flags.append(resource[\"id\"])\n\n if loaded_accounts:\n self.unsuccessful_batches[batch_id] = \"PARTIALLY_RECOVERED\"\n else:\n self.unsuccessful_batches[batch_id] = batch[\"status\"]", "def failJob(self, job):\n\n job.errors += 1\n\n if job.errors > 5:\n job.status = 'aborted'\n else:\n job.status = 'waiting'\n\n job.put()\n\n job_id = job.key().id()\n logging.warning(\"job %d now failed %d time(s)\" % (job_id, job.errors))", "def test_batch_state_stopping_after_error(self):\n\n minions_list = []\n retcode = None\n\n # Executing salt with batch: 1 and with failhard. It should stop after the first error.\n cmd = self.run_salt(\n '\"*minion\" state.single test.fail_without_changes name=test_me -b 1'\n \" --out=yaml --failhard\",\n timeout=self.run_timeout,\n )\n\n # Parsing the output. Idea is to fetch number on minions and retcode of the execution.\n # retcode var could be overwritten in case of broken failhard but number of minions check should still fail.\n for line in cmd:\n if line.startswith(\"Executing run on\"):\n minions_list.append(line)\n if line.startswith(\"retcode\"):\n retcode = line[-1]\n # We expect to have only one minion to be run\n self.assertEqual(1, len(minions_list))\n # We expect to find a retcode in the output\n self.assertIsNot(None, retcode)\n # We expect retcode to be non-zero\n self.assertNotEqual(0, retcode)", "def jobs_failed(self, jobs_failed):\n\n self._jobs_failed = jobs_failed", "def _on_permanent_failure_batch(self):\n logger.info(('Moving permamently %d failed tasks to the '\n 'dead-letter-queue %s.') % (\n len(self._permanent_failures), self._batch_queue.dlq_name))", "def xfail(self, strict):\n\n if self.failed:\n self.status_override = Status.XFAIL\n elif self.passed:\n if strict:\n self.status_override = Status.XPASS_STRICT\n else:\n self.status_override = Status.XPASS\n\n # do not override if derived status is UNKNOWN/UNSTABLE\n\n # propagate xfail down to testcase\n for child in self:\n child.xfail(strict)", "def __save_failed_matching(\n self,\n graph: nx.Graph,\n tree: nx.Graph,\n component: Optional[Set[Hashable]] = None,\n batch_id: Optional[int] = None,\n failure_type: int = 0,\n ):\n if self.failures is None:\n return\n if not self.failures.exists():\n self.failures.mkdir()\n if self.failures.is_dir():\n count = len(list(self.failures.iterdir()))\n if count >= 1000:\n return\n failure_dir = self.failures / f\"{count:03}\"\n failure_dir.mkdir(exist_ok=True)\n pickle.dump(graph, (failure_dir / \"graph.obj\").open(\"wb\"))\n pickle.dump(tree, (failure_dir / \"tree.obj\").open(\"wb\"))", "def fail(self, exception):\n self.state = State.FAILED\n self.failure_report = StepFailureReport(exception)", "def _retry_failed_submissions(self):\n\n still_failing = []\n for create_func, batch_data in self._submission_fails:\n try:\n self._submit_batches.submit_update(create_func, batch_data)\n except SubmitBatchesException:\n still_failing.append((create_func, batch_data))\n if self._print_verbose_activated:\n if len(self._submission_fails) > 0:\n print(\"Of\", len(self._submission_fails), \"/\", len(still_failing),\n \"are still failing.\")\n self._submission_fails = still_failing", "def test_problem_batch_submit_error(self):\n\n job = models.ProblemJob(\n data=self.problem_data,\n params=dict(non_existing_param=1),\n solver=self.solver_id,\n type=self.problem_type,\n )\n\n statuses = self.api.submit_problems([job])\n\n self.assertIsInstance(statuses, list)\n self.assertEqual(len(statuses), 1)\n\n for status in statuses:\n self.assertIsInstance(status, models.ProblemSubmitError)\n self.assertEqual(status.error_code, 400)", "def test_set_to_failed(self, course_run_program_type):\n course_run = self.course_runs[course_run_program_type]\n grade = Decimal('0.55')\n set_to_failed(user=self.user, course_run=course_run, grade=grade)\n mmtrack = get_mmtrack(self.user, course_run.course.program)\n assert not mmtrack.has_passed_course_run(course_run.edx_course_key)\n assert int(mmtrack.get_final_grade_percent(course_run.edx_course_key)) == (grade * 100)", "def fail_job(self, jobid, reason):", "def _set_failed(self, v, load=False):\n if hasattr(v, \"_utype\"):\n v = v._utype(v)\n try:\n t = YANGDynClass(v,base=YANGBool, is_leaf=True, yang_name=\"failed\", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/probes', defining_module='openconfig-probes', yang_type='boolean', is_config=False)\n except (TypeError, ValueError):\n raise ValueError({\n 'error-string': \"\"\"failed must be of a type compatible with boolean\"\"\",\n 'defined-type': \"boolean\",\n 'generated-type': \"\"\"YANGDynClass(base=YANGBool, is_leaf=True, yang_name=\"failed\", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/probes', defining_module='openconfig-probes', yang_type='boolean', is_config=False)\"\"\",\n })\n\n self.__failed = t\n if hasattr(self, '_set'):\n self._set()", "def test_nested_job_failed_too_many_times(self, api, mocker, time_mock, update_job_mock):\n\n def update_job_behaviour():\n jobs[1].failed = True\n sub_jobs[1].failed = True\n sub_jobs[1].attempt_number = InsightAsyncJobManager.MAX_NUMBER_OF_ATTEMPTS\n yield from range(10)\n\n update_job_mock.side_effect = update_job_behaviour()\n sub_jobs = [\n mocker.Mock(spec=InsightAsyncJob, attempt_number=1, failed=False, completed=True),\n mocker.Mock(spec=InsightAsyncJob, attempt_number=1, failed=False, completed=False),\n ]\n jobs = [\n mocker.Mock(spec=InsightAsyncJob, attempt_number=1, failed=False, completed=True),\n mocker.Mock(spec=ParentAsyncJob, _jobs=sub_jobs, attempt_number=1, failed=False, completed=False),\n ]\n manager = InsightAsyncJobManager(api=api, jobs=jobs)\n\n with pytest.raises(JobException):\n next(manager.completed_jobs(), None)", "def test_returned_with_error_disable_enqueue(self):\n job = Job.objects.get(pk=1)\n job.disable_enqueue_after_fails = 3\n job.save()\n\n for i in range(3):\n response = self.patch(\n '/api/v1/run/1/',\n {\n 'return_dts': timezone.now().isoformat(' '),\n 'return_success': False,\n }\n )\n\n self.assertEqual(202, response.status_code)\n job = Job.objects.get(pk=1)\n self.assertTrue(job.enqueue_is_enabled)\n self.assertEqual(i + 1, job.fail_times)\n\n response = self.patch(\n '/api/v1/run/1/',\n {\n 'return_dts': timezone.now().isoformat(' '),\n 'return_success': False,\n }\n )\n\n job = Job.objects.get(pk=1)\n self.assertFalse(job.enqueue_is_enabled)", "def test_batch_module_stopping_after_error(self):\n\n minions_list = []\n retcode = None\n\n # Executing salt with batch: 1 and with failhard. It should stop after the first error.\n cmd = self.run_salt(\n '\"*minion\" test.retcode 42 -b 1 --out=yaml --failhard',\n timeout=self.run_timeout,\n )\n\n # Parsing the output. Idea is to fetch number on minions and retcode of the execution.\n # retcode var could be overwritten in case of broken failhard but number of minions check should still fail.\n for line in cmd:\n if line.startswith(\"Executing run on\"):\n minions_list.append(line)\n if line.startswith(\"retcode\"):\n retcode = line[-1]\n # We expect to have only one minion to be run\n self.assertEqual(1, len(minions_list))\n # We expect to find a retcode in the output\n self.assertIsNot(None, retcode)\n # We expect retcode to be non-zero\n self.assertNotEqual(0, retcode)", "def _validate_batch(self, batch):\n if self._scheduler:\n try:\n self._scheduler.add_batch(batch)\n except SchedulerError as err:\n LOGGER.debug(\"Scheduler error processing batch: %s\", err)", "def failed_to_update(self, failed_to_update):\n\n self._failed_to_update = failed_to_update", "def fail_tasks(self):\n for fail in (self._directory / 'fail').iterdir():\n with fail.open('rb') as f:\n yield dill.load(f)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Collects all possible information about the database, its tables, their columns and indexes into a DatabaseSchema object.
def schematize (self): schema = DatabaseSchema (self.getDatabaseName ()) tableNames = self.getTableNames () for tableName in tableNames: schema.addTable (self.schematizeTable (tableName)) return schema
[ "def _backcompute_schema(self, cursor):\n raw_stats_types = self.connection.tables()\n if not raw_stats_types:\n raise weewx.UninitializedDatabase(\"Uninitialized stats database\")\n # Some stats database have schemas for heatdeg and cooldeg (even though\n # they are not used) due to an earlier bug. Filter them out. Also,\n # filter out the metadata table. In case the same database is being used\n # for the archive data, filter out the 'archive' database.\n stats_types = [s for s in raw_stats_types if s not in ['heatdeg','cooldeg','metadata', 'archive']]\n stats_schema = []\n for stat_type in stats_types:\n ncol = len(self.connection.columnsOf(stat_type))\n stats_schema.append((stat_type, 'REAL' if ncol==7 else 'VECTOR'))\n return stats_schema", "def load_all_schema(self):\n raise NotImplementedError", "def get_schema(\n self,\n table_name: str,\n database: str | None = None,\n ) -> sch.Schema:\n qualified_name = self._fully_qualified_name(table_name, database)\n (column_names, types, *_), *_ = self._client_execute(\n f\"DESCRIBE {qualified_name}\"\n )\n\n return sch.Schema.from_tuples(zip(column_names, map(parse, types)))", "def get_table_metadata(\n database: Database, table_name: str, schema_name: Optional[str]\n) -> Dict:\n keys: List = []\n columns = database.get_columns(table_name, schema_name)\n primary_key = database.get_pk_constraint(table_name, schema_name)\n if primary_key and primary_key.get(\"constrained_columns\"):\n primary_key[\"column_names\"] = primary_key.pop(\"constrained_columns\")\n primary_key[\"type\"] = \"pk\"\n keys += [primary_key]\n foreign_keys = get_foreign_keys_metadata(database, table_name, schema_name)\n indexes = get_indexes_metadata(database, table_name, schema_name)\n keys += foreign_keys + indexes\n payload_columns: List[Dict] = []\n for col in columns:\n dtype = get_col_type(col)\n payload_columns.append(\n {\n \"name\": col[\"name\"],\n \"type\": dtype.split(\"(\")[0] if \"(\" in dtype else dtype,\n \"longType\": dtype,\n \"keys\": [k for k in keys if col[\"name\"] in k.get(\"column_names\")],\n }\n )\n return {\n \"name\": table_name,\n \"columns\": payload_columns,\n \"selectStar\": database.select_star(\n table_name,\n schema=schema_name,\n show_cols=True,\n indent=True,\n cols=columns,\n latest_partition=True,\n ),\n \"primaryKey\": primary_key,\n \"foreignKeys\": foreign_keys,\n \"indexes\": keys,\n }", "def get_table_info(self):\n conn = self.get_connection()\n info = conn.cursor()\n info.execute(\"show table status\")\n for table in info:\n\n ## ignore foreign key table\n\n if table[0].startswith(\"f_\"):\n continue\n table_info = TableInfo(table[0], table[len(table) - 1])\n table_info.init_col(self.get_col_info(table[0]))\n self.table_info.append(table_info)", "def _getSchema(self):\n \n # Early versions of the stats database did not have an explicit\n # schema. In this case, an exception will be raised. Be prepared to\n # catch it, then back calculate the schema.\n _cursor = self.connection.cursor()\n try:\n _cursor.execute(\"SELECT obs_name, obs_type FROM _stats_schema\")\n _stats_schema_dict = dict((str(_row[0]), str(_row[1])) for _row in _cursor)\n syslog.syslog(syslog.LOG_DEBUG, \"stats: Schema exists with %d elements\" % (len(_stats_schema_dict),))\n except weedb.OperationalError:\n # The stats schema does not exist. Back calculate it.\n _stats_schema = self._backcompute_schema(_cursor)\n _stats_schema_dict = dict(_stats_schema)\n syslog.syslog(syslog.LOG_DEBUG, \"stats: Back calculated schema with %d elements.\" % (len(_stats_schema_dict),))\n finally:\n _cursor.close()\n\n return _stats_schema_dict", "def db_tables():\n\n from . import db\n print(' '.join(db.Base.metadata.tables))", "def _rebuild_internal_schema(self):\n\t\tself.columns = OrderedDict()\n\t\tself.primary_cgroup = None\n\n\t\tfor cgroup, schema in self._cgroups.iteritems():\n\t\t\tfor colname, dtype in schema['columns']:\n\t\t\t\tassert colname not in self.columns\n\t\t\t\tself.columns[colname] = ColumnType()\n\t\t\t\tself.columns[colname].name = colname\n\t\t\t\tself.columns[colname].dtype = np.dtype(dtype)\n\t\t\t\tself.columns[colname].cgroup = cgroup\n\n\t\t\tif self.primary_cgroup is None and not self._is_pseudotablet(cgroup):\n\t\t\t\tself.primary_cgroup = cgroup\n\t\t\t\tif 'primary_key' in schema:\n\t\t\t\t\tself.primary_key = self.columns[schema['primary_key']]\n\t\t\t\tif 'temporal_key' in schema:\n\t\t\t\t\tself.temporal_key = self.columns[schema['temporal_key']]\n\t\t\t\tif 'spatial_keys' in schema:\n\t\t\t\t\t(lon, lat) = schema['spatial_keys']\n\t\t\t\t\tself.spatial_keys = (self.columns[lon], self.columns[lat])\n\t\t\telse:\n\t\t\t\t# If any of these are defined, they must be defined in the\n\t\t\t\t# primary cgroup\n\t\t\t\tassert 'primary_key' not in schema\n\t\t\t\tassert 'spatial_keys' not in schema\n\t\t\t\tassert 'temporak_key' not in schema\n\n\t\t\tif 'blobs' in schema:\n\t\t\t\tfor colname in schema['blobs']:\n\t\t\t\t\tassert self.columns[colname].dtype.base == np.int64, \"Data structure error: blob reference columns must be of int64 type\"\n\t\t\t\t\tself.columns[colname].is_blob = True", "def get_info_schema(self):\n\n opsconfig = self.config_json\n info_schema = {}\n\n # info schema is json-formatted array\n # add ops_ to avoid namespace collision with database (i.e.,\n # user not allowed)\n for info_i in opsconfig[\"info\"]:\n info_schema[\"ops_\" + info_i[\"name\"]] = info_i[\"db_schema\"]\n\n return info_schema", "def extract_schema(self, connection: PostgresConnectionWrapper):\n if not connection:\n return\n\n res_schema = {\n \"type\": self.__class__.__name__,\n \"columns\": [],\n \"dtypes\": {},\n \"shape\": (),\n \"size.bytes\": 0, # TODO: calculate operation size in bytes\n }\n\n if self.dataframe is not None:\n res_schema.update(\n {\n \"columns\": list(self.dataframe.columns),\n \"shape\": self.dataframe.shape,\n \"dtypes\": {\n col: str(type_) for col, type_ in self.dataframe.dtypes.items()\n },\n }\n )\n else:\n if self.table_name is not None:\n redshift_query(\n connection.connection,\n f\"set search_path to '{self.schema_name}'\",\n fetch_all=False,\n )\n\n desc_results = redshift_query(\n connection.connection,\n f\"select * from pg_table_def where tablename='{self.table_name}'\",\n )\n\n if desc_results:\n for col_desc in desc_results:\n if len(col_desc) > 2:\n res_schema[\"columns\"].append(col_desc[2])\n res_schema[\"dtypes\"][col_desc[2]] = _type_conversion(\n col_desc[3]\n )\n\n res_schema[\"shape\"] = (self.records_count, len(res_schema[\"columns\"]))\n\n if desc_results is not None:\n self.schema_cache = res_schema", "def create_schema(ctx):\n SQLBase.metadata.create_all(ctx.obj['lister'].db_engine)", "def dump_db():\n\ttable_list = []\n\tfor table in db.metadata.tables.items():\n\t\ttable_list.append(table[0])\n\tdb_dict = dict.fromkeys(table_list)\n\tfor table in table_list:\n\t\tdb_dict[table] = []\n\t\tquery = db.engine.execute(\n\t\t\tf'SELECT * FROM {table}'\n\t\t)\n\t\tfor row in query:\n\t\t\tdb_dict[f\"{table}\"].append(list(row))\n\treturn jsonify(db_dict)", "def get_db_details(self):\n props = {}\n props['path'] = self.path\n props['size'] = self.__get_size()\n props['indexes'] = self.indexes_names.keys()\n props['cdb_environment'] = cdb_environment\n return props", "def _get_all_schemas(self, database: str, exclude_defaults: Optional[bool] = False) -> List[str]:\n raise NotImplementedError()", "def info_database(self):\n for x in self.list_databases:\n print(\"%50s: %s\" %( x['definition'], x['entry_id']))", "def construct_schema(collection):\n columns_dict = {}\n columns = []\n for row in collection.find():\n for field in row.keys():\n field_type = get_type(field, row[field])\n if field not in columns_dict.keys():\n columns_dict[field] = field_type\n else:\n union_type = unify_types(columns_dict[field], field_type)\n columns_dict[field] = union_type\n for field in sorted(columns_dict.keys()):\n # We sort the keys to make the constructed schema look nice\n # Possible failure modes up until this point:\n # Field is entirely empty arrays, type is undefined\n # Field is entirely empty objects\n # Field is invalid\n columns_dict[field] = remove_invalid_fields(columns_dict[field])\n if (columns_dict[field].get('type', 'INVALID') != 'INVALID' and\n not (columns_dict[field]['type'] == 'RECORD' and columns_dict[field]['fields'] == [])):\n columns.append(columns_dict[field])\n return columns", "def createDatabaseTables(self):\n\t\tself.createBlockTable()\n\t\tself.createTransactionTable()\n\t\tself.createInputTable()\n\t\tself.createOutputTable()\n\t\tself.createClusterTable()\n\t\tself.createAddressTable()\n\t\tself.createLedgerTable()", "def schema(self):\n return self.get(\"/schema\").json()", "def get_table_mapping(self) -> dict:\n table_mapping = {}\n for table in self.database.list_tables():\n with self.database.snapshot() as snapshot:\n result = snapshot.execute_sql(\n f\"select column_name, spanner_type \"\n \"from information_schema.columns \"\n f\"where table_name = '{table.table_id}'\"\n )\n table_mapping[table.table_id] = dict(result)\n return table_mapping" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compiles the information provided into a ColumnSchema object.
def schematizeColumn (self, columnName, dataType, isNullable, extra): column = ColumnSchema (columnName, dataType, isNullable, extra) return column
[ "def _rebuild_internal_schema(self):\n\t\tself.columns = OrderedDict()\n\t\tself.primary_cgroup = None\n\n\t\tfor cgroup, schema in self._cgroups.iteritems():\n\t\t\tfor colname, dtype in schema['columns']:\n\t\t\t\tassert colname not in self.columns\n\t\t\t\tself.columns[colname] = ColumnType()\n\t\t\t\tself.columns[colname].name = colname\n\t\t\t\tself.columns[colname].dtype = np.dtype(dtype)\n\t\t\t\tself.columns[colname].cgroup = cgroup\n\n\t\t\tif self.primary_cgroup is None and not self._is_pseudotablet(cgroup):\n\t\t\t\tself.primary_cgroup = cgroup\n\t\t\t\tif 'primary_key' in schema:\n\t\t\t\t\tself.primary_key = self.columns[schema['primary_key']]\n\t\t\t\tif 'temporal_key' in schema:\n\t\t\t\t\tself.temporal_key = self.columns[schema['temporal_key']]\n\t\t\t\tif 'spatial_keys' in schema:\n\t\t\t\t\t(lon, lat) = schema['spatial_keys']\n\t\t\t\t\tself.spatial_keys = (self.columns[lon], self.columns[lat])\n\t\t\telse:\n\t\t\t\t# If any of these are defined, they must be defined in the\n\t\t\t\t# primary cgroup\n\t\t\t\tassert 'primary_key' not in schema\n\t\t\t\tassert 'spatial_keys' not in schema\n\t\t\t\tassert 'temporak_key' not in schema\n\n\t\t\tif 'blobs' in schema:\n\t\t\t\tfor colname in schema['blobs']:\n\t\t\t\t\tassert self.columns[colname].dtype.base == np.int64, \"Data structure error: blob reference columns must be of int64 type\"\n\t\t\t\t\tself.columns[colname].is_blob = True", "def construct_schema(collection):\n columns_dict = {}\n columns = []\n for row in collection.find():\n for field in row.keys():\n field_type = get_type(field, row[field])\n if field not in columns_dict.keys():\n columns_dict[field] = field_type\n else:\n union_type = unify_types(columns_dict[field], field_type)\n columns_dict[field] = union_type\n for field in sorted(columns_dict.keys()):\n # We sort the keys to make the constructed schema look nice\n # Possible failure modes up until this point:\n # Field is entirely empty arrays, type is undefined\n # Field is entirely empty objects\n # Field is invalid\n columns_dict[field] = remove_invalid_fields(columns_dict[field])\n if (columns_dict[field].get('type', 'INVALID') != 'INVALID' and\n not (columns_dict[field]['type'] == 'RECORD' and columns_dict[field]['fields'] == [])):\n columns.append(columns_dict[field])\n return columns", "def make_cols(self):\n column_types = self.config.column_types\n table = self.make_new_table()\n #update current table\n self.curr_table = table\n\n cols_to_add = []\n count = 0\n for column_type in column_types:\n num = int(self.MAX_COLS_TABLE * .8)\n cols_to_add += [(table.name+\"__\"+str(c), column_type) for c in range(count, count+num)]\n count += num\n\n values=[]\n for (name, col_type) in cols_to_add:\n values.append(\"ADD COLUMN `%s` %s\" % (name, col_type))\n\n values = \", \".join(values)\n qry = \"\"\"\n ALTER TABLE `{table}`\n {cols_to_add}\n \"\"\".format(table=table.name, cols_to_add=values)\n self.engine.execute(qry)\n\n \n #reflect table again to have update columns\n table = Table(table.name, MetaData(bind=self.engine), autoload=True, autoload_with=self.engine)\n self.tables[table.name] = table\n self.free_cols[table.name] = {}\n #for new column in the database, add it to free columns\n for (name, col_type) in cols_to_add:\n if col_type not in self.free_cols[table.name]:\n self.free_cols[table.name][col_type] = set([])\n\n col = DSMColumn(getattr(table.c, name), dsm_table=self)\n self.free_cols[table.name][col_type].add(col)", "def create_columns(self):\n for value in self.raw_data[0]:\n self.columns.append(Column(header=value))\n self.headers.append(value)\n self.valid_rows.pop(0)\n\n for row in self.valid_rows:\n for index, value in enumerate(row):\n self.columns[index].values.append(value)", "def evaluate(self):\n log.info(\" ---> Start evaluating column '{0}'\".format(self.id))\n\n #\n # Stage 1: Ensure that the data field (with table data) is ready for applying column operations\n #\n table = self.table.data # Table the columns will be added to\n\n #\n # Stage 2: Generate a list of concrete definitions by imposing extensions on the base definition\n # \"extensions\" field determine family or not.\n #\n concrete_definitions = self.get_definitions()\n num_extensions = len(concrete_definitions)\n\n # Essentially, we evaluate several columns independently\n for i, definition in enumerate(concrete_definitions):\n\n #\n # Stage 3. Resolve the function\n #\n func_name = definition.get('function')\n if not func_name:\n log.warning(\"Column function is not specified. Skip column definition.\".format(func_name))\n break\n\n func = resolve_full_name(func_name)\n if not func:\n log.warning(\"Cannot resolve user-defined function '{0}'. Skip column definition.\".format(func_name))\n break\n\n window = definition.get('window')\n\n #\n # Stage 4. Prepare input data argument to pass to the function (as the first argument)\n #\n data = table\n\n inputs = definition.get('inputs', [])\n inputs = get_columns(inputs, data)\n if inputs is None:\n log.warning(\"Error reading column list. Skip column definition.\")\n break\n\n # Validation: check if all explicitly specified columns available\n if not all_columns_exist(inputs, data):\n log.warning(\"Not all columns available. Skip column definition.\".format())\n break\n\n # Select only the specified input columns\n data = data[inputs]\n\n data_type = definition.get('data_type')\n\n #\n # Stage 5. Prepare model object to pass to the function (as the second argument)\n #\n model_type = definition.get('model_type')\n model = self.prepare_model(definition, inputs)\n if model is None:\n break\n\n #\n # Stage 6. Apply function.\n # Depending on the \"window\" the system will organize a loop over records, windows or make single call\n # It also depends on the call options (how and what to pass in data and model arguments, flatten json, ndarry or Series etc.)\n #\n out = transform(func, window, data, data_type, model, model_type)\n\n #\n # Stage 7. Post-process the result by renaming the output columns accordingly (some convention is needed to know what output to expect)\n #\n outputs = definition.get('outputs', [])\n if isinstance(outputs, str): # If a single name is provided (not a list), then we wrap into a list\n outputs = [outputs]\n if not outputs:\n id = definition.get('id')\n # TODO: We could use a smarter logic here by finding a parameter of the extension which really changes (is overwritten): inputs, function, outputs, window, model etc.\n if num_extensions > 1:\n id = id + '_' + str(i)\n outputs.append(id)\n\n # TODO: There result could be a complex object, while some option (like 'result_path') could provide a path to access it, so we need to be able to retrieve the result (either here or in transform function)\n # TODO: The result can be Series/listndarray(1d or 2d) and we need to convert it to DataFrame by using the original index.\n out = pd.DataFrame(out) # Result can be ndarray\n for i, c in enumerate(out.columns):\n if outputs and i < len(outputs): # Explicitly specified output column name\n n = outputs[i]\n else: # Same name - overwrite input column\n n = inputs[i]\n table[n] = out[c] # A column is attached by matching indexes so indexes have to be consistent (the same)\n\n #\n # Stage 8. Post-process the whole family\n #\n\n log.info(\" <--- Finish evaluating column '{0}'\".format(self.id))", "def columnsFromSchema(self, tableName, soClass):\n\n fieldqry = \"\"\"\\\n SELECT rf.RDB$FIELD_NAME as field,\n t.RDB$TYPE_NAME as t,\n f.RDB$FIELD_LENGTH as flength,\n f.RDB$FIELD_SCALE as fscale,\n rf.RDB$NULL_FLAG as nullAllowed,\n coalesce(rf.RDB$DEFAULT_SOURCE, f.rdb$default_source) as thedefault,\n f.RDB$FIELD_SUB_TYPE as blobtype\n FROM RDB$RELATION_FIELDS rf\n INNER JOIN RDB$FIELDS f ON rf.RDB$FIELD_SOURCE = f.RDB$FIELD_NAME\n INNER JOIN RDB$TYPES t ON f.RDB$FIELD_TYPE = t.RDB$TYPE\n WHERE rf.RDB$RELATION_NAME = '%s'\n AND t.RDB$FIELD_NAME = 'RDB$FIELD_TYPE'\"\"\"\n\n colData = self.queryAll(fieldqry % tableName.upper())\n results = []\n for field, t, flength, fscale, nullAllowed, thedefault, blobType in colData:\n field = field.strip().lower()\n if thedefault:\n thedefault = thedefault.split(' ')[1]\n if thedefault.startswith(\"'\") and thedefault.endswith(\"'\"):\n thedefault = thedefault[1:-1]\n idName = str(soClass.sqlmeta.idName or 'id').upper()\n if field.upper() == idName:\n continue\n colClass, kw = self.guessClass(t, flength, fscale)\n kw['name'] = soClass.sqlmeta.style.dbColumnToPythonAttr(field).strip()\n kw['dbName'] = field\n kw['notNone'] = not nullAllowed\n kw['default'] = thedefault\n results.append(colClass(**kw))\n return results", "def _parse_column(self, line, state):\n\n spec = None\n m = self._re_column.match(line)\n if m:\n spec = m.groupdict()\n spec[\"full\"] = True\n else:\n m = self._re_column_loose.match(line)\n if m:\n spec = m.groupdict()\n spec[\"full\"] = False\n if not spec:\n util.warn(\"Unknown column definition %r\" % line)\n return\n if not spec[\"full\"]:\n util.warn(\"Incomplete reflection of column definition %r\" % line)\n\n name, type_, args = spec[\"name\"], spec[\"coltype\"], spec[\"arg\"]\n\n try:\n col_type = self.dialect.ischema_names[type_]\n except KeyError:\n util.warn(\n \"Did not recognize type '%s' of column '%s'\" % (type_, name)\n )\n col_type = sqltypes.NullType\n\n # Column type positional arguments eg. varchar(32)\n if args is None or args == \"\":\n type_args = []\n elif args[0] == \"'\" and args[-1] == \"'\":\n type_args = self._re_csv_str.findall(args)\n else:\n type_args = [int(v) for v in self._re_csv_int.findall(args)]\n\n # Column type keyword options\n type_kw = {}\n\n if issubclass(col_type, (DATETIME, TIME, TIMESTAMP)):\n if type_args:\n type_kw[\"fsp\"] = type_args.pop(0)\n\n for kw in (\"unsigned\", \"zerofill\"):\n if spec.get(kw, False):\n type_kw[kw] = True\n for kw in (\"charset\", \"collate\"):\n if spec.get(kw, False):\n type_kw[kw] = spec[kw]\n if issubclass(col_type, (ENUM, SET)):\n type_args = _strip_values(type_args)\n\n if issubclass(col_type, SET) and \"\" in type_args:\n type_kw[\"retrieve_as_bitwise\"] = True\n\n type_instance = col_type(*type_args, **type_kw)\n\n col_kw = {}\n\n # NOT NULL\n col_kw[\"nullable\"] = True\n # this can be \"NULL\" in the case of TIMESTAMP\n if spec.get(\"notnull\", False) == \"NOT NULL\":\n col_kw[\"nullable\"] = False\n\n # AUTO_INCREMENT\n if spec.get(\"autoincr\", False):\n col_kw[\"autoincrement\"] = True\n elif issubclass(col_type, sqltypes.Integer):\n col_kw[\"autoincrement\"] = False\n\n # DEFAULT\n default = spec.get(\"default\", None)\n\n if default == \"NULL\":\n # eliminates the need to deal with this later.\n default = None\n\n comment = spec.get(\"comment\", None)\n\n if comment is not None:\n comment = cleanup_text(comment)\n\n sqltext = spec.get(\"generated\")\n if sqltext is not None:\n computed = dict(sqltext=sqltext)\n persisted = spec.get(\"persistence\")\n if persisted is not None:\n computed[\"persisted\"] = persisted == \"STORED\"\n col_kw[\"computed\"] = computed\n\n col_d = dict(\n name=name, type=type_instance, default=default, comment=comment\n )\n col_d.update(col_kw)\n state.columns.append(col_d)", "def test_construct_column(type_, expected_type):\n artifacts = types.ColumnArtifacts(type_)\n\n returned_column = column.construct_column(artifacts=artifacts)\n\n assert isinstance(returned_column, sqlalchemy.Column)\n assert isinstance(returned_column.type, expected_type)\n assert len(returned_column.foreign_keys) == 0\n assert returned_column.nullable is True", "def check_schema(\n *, schema: types.Schema, required: typing.Optional[bool] = None\n) -> typing.Tuple[types.ColumnSchema, types.ColumnArtifacts]:\n # Retrieve artifacts\n type_ = helpers.peek.type_(schema=schema, schemas={})\n format_ = helpers.peek.format_(schema=schema, schemas={})\n max_length = helpers.peek.max_length(schema=schema, schemas={})\n nullable = helpers.peek.nullable(schema=schema, schemas={})\n primary_key = helpers.get_ext_prop(source=schema, name=\"x-primary-key\")\n autoincrement = helpers.get_ext_prop(source=schema, name=\"x-autoincrement\")\n index = helpers.get_ext_prop(source=schema, name=\"x-index\")\n unique = helpers.get_ext_prop(source=schema, name=\"x-unique\")\n foreign_key = helpers.get_ext_prop(source=schema, name=\"x-foreign-key\")\n dict_ignore = helpers.get_ext_prop(source=schema, name=\"x-dict-ignore\")\n\n # Construct schema to return\n return_schema: types.ColumnSchema = {\"type\": type_}\n if format_ is not None:\n return_schema[\"format\"] = format_\n if max_length is not None:\n return_schema[\"maxLength\"] = max_length\n if nullable is not None:\n return_schema[\"nullable\"] = nullable\n if dict_ignore is not None:\n return_schema[\"x-dict-ignore\"] = dict_ignore\n\n # Construct return artifacts\n nullable_artefact = _calculate_nullable(nullable=nullable, required=required)\n return_artifacts = types.ColumnArtifacts(\n type_,\n format=format_,\n max_length=max_length,\n nullable=nullable_artefact,\n primary_key=primary_key,\n autoincrement=autoincrement,\n index=index,\n unique=unique,\n foreign_key=foreign_key,\n )\n\n return return_schema, return_artifacts", "def _create_columns(self,\n column_names,\n logical_types,\n semantic_tags,\n use_standard_tags,\n column_descriptions,\n column_metadata):\n datacolumns = {}\n for name in column_names:\n if logical_types and name in logical_types:\n logical_type = logical_types[name]\n else:\n logical_type = None\n if semantic_tags and name in semantic_tags:\n semantic_tag = semantic_tags[name]\n else:\n semantic_tag = None\n if column_descriptions:\n description = column_descriptions.get(name)\n else:\n description = None\n if column_metadata:\n metadata = column_metadata.get(name)\n else:\n metadata = None\n dc = DataColumn(self._dataframe[name], logical_type, semantic_tag, use_standard_tags, name, description, metadata)\n datacolumns[dc.name] = dc\n return datacolumns", "def _construct_schema(uuid):\n catalog_url = '{0}/api/catalog/v1?ids={1}'.format(URI, uuid)\n response = urllib.request.urlopen(catalog_url, context=context)\n catalog_data = json.load(response)[\"results\"][0][\"resource\"]\n\n schema = []\n for i in range(0, len(catalog_data[\"columns_field_name\"])):\n name = catalog_data[\"columns_field_name\"][i]\n field_type = _encode_datatype(catalog_data[\"columns_datatype\"][i])\n description = catalog_data[\"columns_description\"][i]\n schema.append(bigquery.SchemaField(name, field_type, mode='NULLABLE', description=description))\n\n return schema", "def rebuild_schema(doc, r, df):\n import numpy as np\n\n # Re-get the resource in the doc, since it may be different.\n try:\n r = doc.resource(r.name)\n except AttributeError:\n # Maybe r is actually a resource name\n r = doc.resource(r)\n\n def alt_col_name(name, i):\n import re\n\n if not name:\n return 'col{}'.format(i)\n\n return re.sub('_+', '_', re.sub('[^\\w_]', '_', str(name)).lower()).rstrip('_')\n\n df_types = {\n np.dtype('O'): 'text',\n np.dtype('int64'): 'integer',\n np.dtype('float64'): 'number'\n }\n\n try:\n df_index_frame = df.index.to_frame()\n except AttributeError:\n df_index_frame = None\n\n def get_col_dtype(c):\n\n c = str(c)\n\n try:\n return df_types[df[c].dtype]\n except KeyError:\n # Maybe it is in the index?\n pass\n\n try:\n return df_types[df_index_frame[c].dtype]\n except TypeError:\n # Maybe not a multi-index\n pass\n\n if c == 'id' or c == df.index.name:\n return df_types[df.index.dtype]\n\n return 'unknown'\n\n columns = []\n schema_term = r.schema_term[0]\n\n if schema_term:\n\n old_cols = { c['name'].value: c.properties for c in schema_term.children }\n for c in schema_term.children:\n schema_term.remove_child(c)\n\n schema_term.children = []\n\n else:\n old_cols = {}\n schema_term = doc['Schema'].new_term('Table', r.schema_name)\n\n index_names = [n if n else \"id\" for n in df.index.names]\n\n for i, col in enumerate(index_names + list(df.columns)):\n acn = alt_col_name(col, i) if alt_col_name(col, i) != str(col) else ''\n\n d = {'name': col, 'datatype': get_col_dtype(col), 'altname': acn}\n\n if col in old_cols.keys():\n lookup_name = col\n elif acn in old_cols.keys():\n lookup_name = acn\n else:\n lookup_name = None\n\n if lookup_name and lookup_name in old_cols:\n\n for k,v in schema_term.properties.items():\n\n old_col = old_cols.get(lookup_name)\n\n for k,v in old_col.items():\n if k != 'name' and v :\n d[k] = v\n\n columns.append(d)\n\n for c in columns:\n\n name = c['name']\n del c['name']\n datatype = c['datatype']\n del c['datatype']\n altname = c['altname']\n del c['altname']\n\n schema_term.new_child('Column', name, datatype=datatype, altname=altname, **c)", "def column_to_bq_schema(self) -> SchemaField:\n kwargs = {}\n if len(self.fields) > 0:\n fields = [field.column_to_bq_schema() for field in self.fields]\n kwargs = {\"fields\": fields}\n\n return SchemaField(self.name, self.dtype, self.mode, **kwargs)", "def evaluate(self):\n definition = self.column_json\n operation = self.get_operation()\n\n log.info(\"---> Start evaluating column '{0}'. Operation '{1}'.\".format(self.id, operation))\n\n # Link columns use their own definition schema different from computaional (functional) definitions\n if self.is_op_link():\n out = self._evaluate_link()\n self._append_output_columns(out)\n self.data.append(out)\n return\n\n # Compose columns use their own definition schema different from computaional (functional) definitions\n if self.is_op_compose():\n out = self._evaluate_compose()\n self._append_output_columns(out)\n self.data.append(out)\n return\n\n #\n # Resolve the function\n #\n func_name = definition.get('function')\n if not func_name:\n log.warning(\"Column function is not specified. Skip column definition.\".format(func_name))\n return\n\n func = resolve_full_name(func_name)\n if not func:\n log.warning(\"Cannot resolve user-defined function '{0}'. Skip column definition.\".format(func_name))\n return\n\n #\n # Prepare model object to pass to the function (as the second argument)\n #\n\n # Model is an arbitrary object.\n # It can be specified by-value as dict.\n # It can be a new instance of the specified class created using the specified constructor parameters.\n # Or it can be returned y the provided (training) procedure which\n # We pass inputs because 1) they are already prepared 2) we might need them for training\n model = self.prepare_model(definition)\n if model is None:\n return\n\n if self.is_op_aggregate(): # Aggregate functions consume facts from another table\n\n out = self._evaluate_aggregate(func, model)\n\n elif self.is_op_calc(): # Computational functions consume this table records\n #\n # Prepare input data argument to pass to the function (as the first argument)\n #\n data = self.table.data\n\n inputs = definition.get('inputs', [])\n inputs = get_columns(inputs, data)\n if inputs is None:\n log.warning(\"Error reading column list. Skip column definition.\")\n return\n\n # Validation: check if all explicitly specified columns available\n if not all_columns_exist(inputs, data):\n log.warning(\"Not all columns available. Skip column definition.\".format())\n return\n\n data = data[inputs] # Select only the specified input columns\n\n data_type = definition.get('data_type')\n\n #\n # Evaluate column depending on the operation type\n #\n if self.is_op_one():\n out = self._evaluate_calculate(func, data, data_type, model)\n elif self.is_op_roll():\n out = self._evaluate_roll(func, data, data_type, model)\n elif self.is_op_all():\n out = self._evaluate_all(func, data, data_type, model)\n else:\n log.warning(\"Unknown operation '{0}'. Skip column definition.\".format(operation))\n return\n else:\n log.warning(\"Unknown operation '{0}'. Skip column definition.\".format(operation))\n return\n\n #\n # Append the newly generated column(s) to this table\n #\n self._append_output_columns(out)\n\n log.info(\"<--- Finish evaluating column '{0}'\".format(self.id))", "def _create_schema(schema_nodes):\n schema = col.SchemaNode(col.Mapping())\n for name, node_def in schema_nodes.items():\n data_type = node_def[0]\n arg_funcs = node_def[1:]\n\n kw = {'name': name}\n for func in arg_funcs:\n kw = func(kw)\n\n node = col.SchemaNode(data_type(), **kw)\n schema.add(node)\n return schema", "def columnize(col_meta, name = None):\n c_name = name if name else col_meta['name']\n ct = col_meta['type']\n if ct in ['BigInteger', 'Boolean', 'Date', 'DateTime',\n 'String', 'Float', 'Integer', ]:\n c_type = ct\n # elif ct == 'Enumerable':\n # c_type = \"Enum\"\n else:\n raise Exception(\"Unrecognized column type:\", ct)\n # now add optional params to the type\n if col_meta.get('length'):\n # arraify it\n lt = col_meta['length']\n lt = lt if isinstance(lt, list) else [lt]\n # convert to strings\n lt = [str(_x) for _x in lt]\n c_type = c_type + (\"(%s)\" % ','.join(lt))\n else:\n c_type = c_type + '()'\n # eval it\n try:\n c_type = eval(c_type)\n except:\n raise Exception(\"Failed to resolve column type: %s\" % c_type)\n else:\n # set optional attributes\n atts = {}\n # column is nullable by default\n atts['nullable'] = False if col_meta.get('nullable') is False else True\n # add format as necessary\n if col_meta.get('format'):\n fmt = col_meta['format']\n atts['info'] = {'format': fmt}\n # make Column object\n return Column(c_name, c_type, **atts)", "def _check_schema(self, column_vals):\n \n model = self.medium\n # This will be only localy defined fields (excluding many_to_many)\n own_field_names = set([f.name for f in model._meta.fields])\n # All locally defined fields which are required and not auto fields (id)\n required_field_names = set([f.name for f in model._meta.fields\n if field_is_required(f)])\n m2m_field_names = set([f.name for f in model._meta.many_to_many])\n \n \n processed_column_values = []\n for key, val in column_vals:\n # Valid field?\n if not key in own_field_names.union(m2m_field_names):\n msg = \"Model %r doesn't have field named %s.\" % \\\n (pretty_model_name(model), key)\n \n raise ValueError(msg + \\\n self._annotate_invalid_schema_exception(model, key))\n \n # Keep a track of required fields\n try:\n required_field_names.remove(key)\n except KeyError:\n pass\n \n # If the field is a relation check the related type\n field = model._meta.get_field(key)\n from django.db.models.fields.related import ManyToManyField\n if isinstance(field, ManyToManyField):\n try:\n len(val)\n except TypeError:\n val = [val]\n rel_types = [isinstance(v, field.rel.to) for v in val]\n if not field.null and False in rel_types:\n raise ValueError(\"Values for field %s must be of type %s, \"\n \"got %s\" % \\\n (key,\n pretty_model_name(field.rel.to),\n val))\n processed_column_values.append((key, val))\n if len(required_field_names):\n raise ValueError(\"Requred fields %s not found\" % required_field_names)\n return m2m_field_names, processed_column_values", "def prepare_output_schema(self, output_schema: OutputSchema) -> OutputSchema:\n columns: List[dict] = output_schema.attributes[\"output_columns\"]\n for column in columns:\n # Extract both field name and transform expression version of field name\n column_name: str = column[\"field_name\"]\n transform_expr: str = column[\"transform\"][\"transform_expr\"]\n column_name_match: re.Match = re.search(r\"`[^`]+`\", transform_expr)\n transform_column_name: str = column_name_match.group(0)\n transform = f\"to_text({transform_column_name})\"\n output_schema = output_schema.change_column_transform(column_name).to(transform)\n changed_output_schema: OutputSchema = output_schema.run()\n return changed_output_schema", "def build_schema_field(column):\n mode = column.get('mode', 'NULLABLE')\n if column['type'] != \"RECORD\":\n return bigquery.schema.SchemaField(column['name'], column['type'], mode)\n fields = set([build_schema_field(field) for field in column['fields']])\n return bigquery.schema.SchemaField(column['name'], column['type'], mode, fields=fields)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fetches the MySQL database connection assigned to this schematizer. Override this method to define a different way to provide a connection for the schematizer.
def getConnection (self): return self._mysqlConnection
[ "def get_connection(self):\n return MySQLHelper.create_db_connection()", "def get_database_connection():\n return connection", "def get_mysql_con():\n\tfrom PySQLPool import getNewPool, getNewConnection, getNewQuery\n\tfrom settings import MYSQL_USER, MYSQL_PASSWORD, MYSQL_HOST, MYSQL_DB\n\tgetNewPool().maxActiveConnections = 1\n\tmysql_db = getNewConnection(username=MYSQL_USER, password=MYSQL_PASSWORD, host=MYSQL_HOST, db=MYSQL_DB)\n\tquery = getNewQuery(mysql_db, commitOnEnd=True)\n\tquery.Query('SET NAMES utf8mb4;')\n\tquery.Query('SET CHARACTER SET utf8mb4;')\n\tquery.Query('SET character_set_connection=utf8mb4;')\n\treturn mysql_db", "def create_default_connection_mysql():\n conf = cfg.getInstance()\n mydb = mysql.connector.connect(\n host=conf.host,\n user=conf.user,\n password=conf.password\n )\n return mydb", "def getDBconnection():\n\t\tdb_connection=None\n\t\tuser_name=USER\n\t\tpassword=PASSWORD\n\t\tdb_name=DATABASE\n\t\tdb_connection = mdb.connect('localhost', user_name, password, db_name);\n\t\treturn db_connection", "def acquire_database_connection():\n g._database_connection = db.pool.getconn()\n return None", "def get_database_connection(self):\n return self.__db_engine", "def connect_to_db(self):\n raise NotImplementedError", "def get_connection(remote=False):\n if remote:\n return mysql.connector.connect(**REMOTE)\n else:\n return mysql.connector.connect(**LOCAL)", "def getDb():\n return psycopg2.connect(\"dbname='snippets'\")", "def get_hub_db_conn():\n raise NotImplementedError()", "def connect(self):\n return self.connectionFactory()", "def database_connection(self, database_name):\n return psycopg2.connect(dbname=database_name, user='andela', host='localhost', password='bootcamp')", "def connect(dbname='twitter'):\n from pymongo import MongoClient\n client = MongoClient()\n db = client.__getattr__(self, dbname)\n\n return db", "def get_mysql_jdbc_url(self):\n return self.__get_value('ambariLevelParams/mysql_jdbc_url')", "def get_connection(self):\n return self.get_pool().get_connection()", "def get_pcf_mysql_connection_string():\n dburl = os.environ.get('DATABASE_URL')\n if not dburl:\n raise EnvironmentError('No database URL found - have you bound a service to the app?')\n if dburl.startswith('mysql2'):\n dburl = dburl.replace('mysql2', 'mysql+mysqldb')\n dburl = dburl.replace('?reconnect=true', '')\n return dburl", "def _getBouncerConnection(self):\n params = self._getParams()._replace(user='pgbouncer',\n database='pgbouncer')\n # NB: don't use the pgpool driver or it will try to interrogate\n # the admindb for schema information, which doesn't work.\n return dbstore.connect(params.asDBStore(), 'postgresql')", "def connect(self):\n self.db = MySQLdb.connect(self.hostname, self.username, self.password, self.dbname)\n self.db.autocommit(on=True)\n self.cursor = self.db.cursor()" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fetch the constraint associated with the given index, if there is one.
def getIndexConstraint (self, tableName, indexName): constraint = None cursor = self.getConnection ().cursor () cursor.execute (""" select constraint_type from information_schema.table_constraints where table_schema = %s and table_name = %s and constraint_name = %s """, (self.getDatabaseName (), tableName)) result = cursor.fetchone () if result is not None: constraintType = result [0] else: # There is no constraint associated with this index. return None
[ "def __getitem__(self, key):\n for constraint in self.constraints:\n name = getattr(constraint, 'name', None)\n if name is not None and name == key:\n return constraint\n try:\n found = constraint[key]\n except (KeyError, TypeError):\n pass\n else:\n return found\n raise KeyError('Constraint {} not found'.format(key))", "def get_parameter(self, index):\n result = None\n if index < len(self.paramorder):\n key = self.paramorder[index]\n if key in self._parameters:\n result = self._parameters[key]\n\n return result", "def __getitem__(self, index: int) -> Cell:\n\n if index[0] <= self.N and index[1] <= self.N:\n return self._safe_get(index)\n return None", "def constraint(self, x):\n return x[0]", "def __getitem__(self, index: Union[SchemaKey, int]) -> dict:\n\n logger = logging.getLogger(__name__)\n logger.debug('SchemaStore.__getitem__: >>> index: {}'.format(index))\n\n rv = None\n if isinstance(index, SchemaKey):\n rv = self._schema_key2schema[index]\n elif isinstance(index, int):\n try:\n rv = self._schema_key2schema[self._seq_no2schema_key[index]]\n except KeyError:\n logger.debug('SchemaStore.__getitem__: <!< index {} not present'.format(index))\n raise SchemaStoreIndex('{}'.format(index))\n else:\n logger.debug('SchemaStore.__getitem__: <!< index {} must be int or SchemaKey'.format(index))\n raise SchemaStoreIndex('{} must be int or SchemaKey'.format(index))\n\n logger.debug('SchemaStore.__getitem__: <<< {}'.format(rv))\n return rv", "def calc_constraint_at(self, i: int, x: np.ndarray) -> float:\n return self.constraints[i](x)", "def remove_denial_constraint(self, index):\n if len(self.Denial_constraints) == 0:\n raise IndexError(\"No Denial Constraints Have Been Defined\")\n\n if index < 0 or index >= len(self.Denial_constraints):\n raise IndexError(\"Given Index Out Of Bounds\")\n\n return self.Denial_constraints.pop(index)", "def get(self, index: int) -> int: \n i = 0\n cur = self.head\n while cur is not None:\n if i==index:\n return cur.val\n i+=1\n cur = cur.nextNode\n return -1", "def get_byindex(self, index):\n return self.dict_pref[self.polygon_objs[index]]", "def get_index(matrix, constraints, row, col):\r\n key = (ku.index_to_slice(row),\r\n ku.index_to_slice(col))\r\n idx, idx_constr = index.graph_implementation([matrix],\r\n (1, 1),\r\n key)\r\n constraints += idx_constr\r\n return idx", "def get_version(self, index):\r\n for verneed, vernaux_iter in self.iter_versions():\r\n for vernaux in vernaux_iter:\r\n if vernaux['vna_other'] == index:\r\n return verneed, vernaux\r\n\r\n return None", "def get(self, index: int) -> int:\n if index >= self.length:\n return -1\n else:\n i = 0\n tmp_node: Node = self.first\n while i < index:\n tmp_node = tmp_node.next\n i += 1\n return tmp_node.val if tmp_node else -1", "def getConstraint (self):\n\n return self.constraint", "def locate_scc(self, vertex_index):\n for scc in self.sccs:\n if vertex_index in scc.internals:\n return scc.index\n return -1", "def constraint(self, name, target, index):\n # sol.aux['constraints'][self.name]['limit'][1]\n self.set((name,index), target, param_type='constraint')", "def lookup(indexable, idx):\n return indexable[idx]", "def getMomentConstraint(self, idx):\n assert idx < len(self.MomConst), \"Index out of range.\"\n return self.MomConst[idx][0].subs(self.RevSymDict) >= sympify(self.MomConst[idx][1]).subs(self.RevSymDict)", "def _get(elements: Sequence[T], index: Optional[int]) -> Optional[T]:\n return None if index is None else elements[index]", "def get(self, key):\n return next(\n requirement for requirement in self if requirement.key == key\n )" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function determines the direction that a line was crossed. This procedure is based on a cross product. No concern has been made for squared terms or magnitudes, only the sign of the cross product.
def line_cross_direction(self, p0, p1, p2) : # print( 'line_cross_direction' ) u = np.array(p0) - np.array(p1) v = np.array(p1) - np.array(p2) v = v[::-1] v[0] *= -1 uv_mag_sqr = np.sum(u*v) return np.sign( uv_mag_sqr )
[ "def ifLineCross(line2p, Line2p):\r\n downCrs = (line2p[0] > Line2p[0]) and (line2p[1] < Line2p[1])\r\n upCrs = (line2p[0] < Line2p[0]) and (line2p[1] > Line2p[1])\r\n if downCrs:\r\n return -1 # line2p down cross Line2p\r\n elif upCrs:\r\n return 1 # line2p up cross Line2p\r\n else:\r\n return 0", "def getCrossings(streamline, point = [0., 0., 0.], normal=[1.,0.,0.]):\n sides = np.dot( (streamline.tracers-point), normal)>0 #calculate the side of the plane each point falls on by projecting on the normal vector\n return (sides[:-1]^sides[1:]).nonzero()[0] #calculate the xor of the shifted sidetables (which is only true if one is shifted) and return the sum", "def getCrossingNr(streamline, point, normal):\n sides = np.dot( (streamline.tracers-point), normal)>0 #calculate the side of the plane each point falls on by projecting on the normal vector\n return np.sum((sides[:-1]^sides[1:])) #calculate the xor of the shifted sidetables (which is only true if one is shifted) and return the sum ", "def crosses(line1, line2):\n (x1,y1), (x2,y2) = line1\n (u1,v1), (u2,v2) = line2\n (a,b), (c,d) = (x2-x1, u1-u2), (y2-y1, v1-v2)\n e, f = u1-x1, v1-y1\n denom = float(a*d - b*c)\n if MathHelper.near(denom, 0):\n # parallel\n return False\n else:\n t = (e*d - b*f)/denom\n s = (a*f - e*c)/denom\n # When 0<=t<=1 and 0<=s<=1 the point of intersection occurs within the\n # line segments\n return 0<=t<=1 and 0<=s<=1", "def crosses(line1, line2):\n (x1,y1), (x2,y2) = line1\n (u1,v1), (u2,v2) = line2\n (a,b), (c,d) = (x2-x1, u1-u2), (y2-y1, v1-v2)\n e, f = u1-x1, v1-y1\n denom = float(a*d - b*c)\n if near(denom, 0):\n # parallel\n return False\n else:\n t = (e*d - b*f)/denom\n s = (a*f - e*c)/denom\n # When 0<=t<=1 and 0<=s<=1 the point of intersection occurs within the\n # line segments\n return 0<=t<=1 and 0<=s<=1", "def side(self, pt):\n t = self.a*pt.x + self.b*pt.y - self.c\n if t < 0:\n return -1\n elif t > 0:\n return 1\n else:\n return 0", "def without_cross(field):\n if row_without_cross(field): #row\n return row_without_cross(field)\n elif col_without_cross(field): #column\n return col_without_cross(field)\n elif diagonal_without_cross(field): #diagonal\n return diagonal_without_cross(field)\n else: #no lines\n return False", "def crosses(D, ep):\n\n # map the vertices of the edge-pair to their location in the drawing D\n a, b, c, d = [D.index(v) for v in (ep[0][0], ep[0][1], ep[1][0], ep[1][1])]\n\n # check vertex locations for crossing\n return (a < c < b < d) or (b < c < a < d) or (a < d < b < c) or \\\n (b < d < a < c) or (c < a < d < b) or (d < a < c < b) or \\\n (c < b < d < a) or (d < b < c < a)", "def side(lat,lon,fault_lat,fault_lon,strike):\n # Scalar option.\n if np.isscalar(strike):\n if 0 <= (strike+45)%360 < 90:\n return np.sign((lon-fault_lon+180)%360-180)\n elif 90 <= (strike+45)%360 < 180:\n return -np.sign(lat-fault_lat)\n elif 180 <= (strike+45)%360 < 270:\n return -np.sign((lon-fault_lon+180)%360-180)\n else:\n return np.sign(lat-fault_lat)\n\n # Vectorized option.\n fault_lat = fault_lat.reshape(lat.shape)\n fault_lon = fault_lon.reshape(lon.shape)\n strike = strike.reshape(lat.shape)\n sides = np.empty(lat.shape)\n\n mask1 = (0 <= (strike+45)%360) & ((strike+45)%360 < 90)\n sides[mask1] = np.sign((lon[mask1]-fault_lon[mask1]+180)%360-180)\n\n mask2 = (90 <= (strike+45)%360) & ((strike+45)%360 < 180)\n sides[mask2] = -np.sign(lat[mask2]-fault_lat[mask2])\n\n mask3 = (180 <= (strike+45)%360) & ((strike+45)%360 < 270)\n sides[mask3] = -np.sign((lon[mask3]-fault_lon[mask3]+180)%360-180)\n\n mask4 = ~(mask1 | mask2 | mask3)\n sides[mask4] = np.sign(lat[mask4]-fault_lat[mask4])\n\n return sides", "def detect_cross(A,B,C,D):\n\n Ax, Ay = A[0], A[1]\n Bx, By = B[0], B[1]\n Cx, Cy = C[0], C[1]\n Dx, Dy = D[0], D[1]\n\n # We assume A,B,C,D are all different nodes.\n # i.e. have NOT been sent edges (A,B) and (A,C)\n # So we can check for coincidence.\n\n if Ax == Bx and Ay == By: print \"Coincidence\"; return True\n if Ax == Cx and Ay == Cy: print \"Coincidence\"; return True\n if Ax == Dx and Ay == Dy: print \"Coincidence\"; return True\n if Bx == Cx and By == Cy: print \"Coincidence\"; return True\n if Bx == Dx and By == Dy: print \"Coincidence\"; return True\n if Cx == Dx and Cy == Dy: print \"Coincidence\"; return True\n\n AB = (Bx - Ax, By - Ay)\n AC = (Cx - Ax, Cy - Ay)\n AD = (Dx - Ax, Dy - Ay)\n\n CA = (Ax - Cx, Ay - Cy)\n CB = (Bx - Cx, By - Cy)\n CD = (Dx - Cx, Dy - Cy)\n\n BD = (Dx - Bx, Dy - By)\n DB = (Bx - Dx, By - Dy)\n\n # Generic cases where no three points are colinear.\n\n if crossproduct(AC,AD) > 0:\n if crossproduct(AC,AB) > 0:\n if crossproduct(AB,AD) > 0:\n # AB is heading towards crossing CD.\n if crossproduct(CB,CA) > 0:\n if crossproduct(CB,CD) > 0:\n if crossproduct(CD,CA) > 0:\n# print \"1 Edges cross! Dude!\"\n return True\n elif crossproduct(CB,CA) < 0:\n if crossproduct(CB,CD) < 0:\n if crossproduct(CD,CA) < 0:\n# print \"2 Edges cross! Dude!\"\n return True\n\n if crossproduct(AC,AD) < 0:\n if crossproduct(AC,AB) < 0:\n if crossproduct(AB,AD) < 0:\n # AB is heading towards crossing CD.\n if crossproduct(CB,CA) > 0:\n if crossproduct(CB,CD) > 0:\n if crossproduct(CD,CA) > 0:\n# print \"3 Edges cross! Dude!\"\n return True\n elif crossproduct(CB,CA) < 0:\n if crossproduct(CB,CD) < 0:\n if crossproduct(CD,CA) < 0:\n# print \"4 Edges cross! Dude!\"\n return True\n\n # Corner cases where a point is colinear with two others.\n # Cross detected if a point is ON the line segment.\n\n if crossproduct(AB,AC) == 0:\n# print \"C is colinear with A and B.\"\n if dotproduct(AB,AC) > 0 and dotproduct(AC,CB) > 0:\n print \"C is on line AB.\"\n return True\n\n if crossproduct(AB,AD) == 0:\n# print \"D is colinear with A and B\"\n if dotproduct(AB,AD) > 0 and dotproduct(AD,DB) > 0:\n print \"D is on line AB.\"\n return True\n\n if crossproduct(CD,CA) == 0:\n# print \"A is colinear with C and D.\"\n if dotproduct(CD,CA) > 0 and dotproduct(CA,AD) > 0:\n print \"A is on line CD.\"\n return True\n\n if crossproduct(CD,CB) == 0:\n# print \"B is colinear with C and D\"\n if dotproduct(CD,CB) > 0 and dotproduct(CB,BD) > 0:\n print \"B is on line CD.\"\n return True\n\n\n return False", "def cross(o, a, b):\r\n return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])", "def _compute_direction(self):\n # Get the first helix axis and a point on that axis from the staple bases. \n # If there is no staple then use the scaffold.\n helix1 = self.from_helix\n if len(helix1.staple_bases) != 0:\n helix1_base = helix1.staple_bases[0]\n elif len(helix1.scaffold_bases) != 0:\n helix1_base = helix1.scaffold_bases[0]\n pt1 = helix1_base.coordinates\n axis1 = [helix1.end_frames[0,2,0], helix1.end_frames[1,2,0], helix1.end_frames[2,2,0]]\n\n # Get the second (adjacent) helix axis and a point on that axis.\n helix2 = self.to_helix\n if len(helix2.staple_bases) != 0:\n helix2_base = helix2.staple_bases[0]\n elif len(helix2.scaffold_bases) != 0:\n helix2_base = helix2.scaffold_bases[0]\n pt2 = helix2_base.coordinates\n axis2 = [helix2.end_frames[0,2,0], helix2.end_frames[1,2,0], helix2.end_frames[2,2,0]]\n axis2_length = np.linalg.norm(axis2)\n\n # Compute the unit vector in the direction of the adjacent helix.\n vec = pt1 - pt2\n d = np.dot(axis2,vec) / axis2_length\n a2pt = pt2 + np.dot(axis2,d)\n self.direction = a2pt - pt1\n self.direction = self.direction / np.linalg.norm(self.direction)", "def curr_curve_direction(self):\n return self._curr_curve_direction", "def _cross(v, w):\n return v[0]*w[1] - v[1]*w[0]", "def vectorCross(v1, v2):\r\n return (v1[0] * v2[1] - v1[1] * v2[0])", "def distPointToLine( x1, x2, x3 ):\n return np.linalg.norm( np.cross(x3-x1,x3-x2) ) / np.linalg.norm(x2-x1)", "def getDirection(self) -> \"SbVec3d const &\":\n return _coin.SbDPLine_getDirection(self)", "def getDirection(self) -> \"SbVec3f const &\":\n return _coin.SbLine_getDirection(self)", "def orientation(a, b, c) -> int:\n slope_diff = (b.y - a.y) * (c.x - b.x) / (b.x - a.x) * (c.y - b.y)\n if slope_diff > 0:\n return 1\n elif slope_diff < 0:\n return -1\n else:\n return 0" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function tests to see if the car has crossed any of the check points based on the car travelling from it's old position, pos_old, to it's new position, pos_new.
def crossed_check_point_test(self, pos_old, pos_new) : for line in self.check_point_lines : value = self.crossed_line_test(pos_old, pos_new, line) if value != 0 : return value return 0
[ "def obs_check(self, q_tree, x_new, label_new, obs_check):\n\n if q_tree[0][0] != x_new[0] and q_tree[0][1] != x_new[1]:\n return False\n\n if (q_tree[0], x_new) in obs_check.keys():\n return obs_check[(q_tree[0], x_new)]\n\n if (x_new, q_tree[0]) in obs_check.keys():\n return obs_check[(x_new, q_tree[0])]\n\n # the line connecting two points crosses an obstacle\n for (obs, boundary) in iter(self.ts['obs'].items()):\n if LineString([Point(q_tree[0]), Point(x_new)]).intersects(boundary):\n obs_check[(q_tree[0], x_new)] = False\n obs_check[(x_new, q_tree[0])] = False\n return False\n\n for (region, boundary) in iter(self.ts['region'].items()):\n if LineString([Point(q_tree[0]), Point(x_new)]).intersects(boundary) \\\n and region + '_' + str(1) != label_new \\\n and region + '_' + str(1) != self.tree.nodes[q_tree]['label']:\n obs_check[(q_tree[0], x_new)] = False\n obs_check[(x_new, q_tree[0])] = False\n return False\n\n obs_check[(q_tree[0], x_new)] = True\n obs_check[(x_new, q_tree[0])] = True\n return True", "def twoPointCrossover(self,cl):\r\n\r\n \tchanged = False;\r\n \tif random() < cons.pX:\r\n \t length = len(self.condition)\r\n \t sep1 = int(random()*(length))\r\n \t sep2 = int(random()*(length)) + 1\r\n \t if sep1>sep2:\r\n \t\thelp1 = sep1\r\n \t\tsep1 = sep2\r\n \t\tsep2 = help1\r\n\r\n \t elif sep1==sep2:\r\n \t\t sep2= sep2+1\r\n\r\n \t cond1 = self.condition[:]\r\n \t cond2 = cl.condition\r\n for i in range(sep1,sep2):\r\n \t\tif cond1[i] != cond2[i]:\r\n \t\t changed = True\r\n \t\t help2 = cond1[i]\r\n \t\t cond1[i]= cond2[i]\r\n \t\t cond2[i]= help2\r\n\r\n \t if changed:\r\n \t\tself.condition = cond1\r\n \t\tcl.condition = cond2\r\n\r\n \treturn changed", "def is_crossing(self) -> bool:\n return self.num_river >= 3 or (self.num_coast == 1 and self.num_river == 2)", "def detect_cross(A,B,C,D):\n\n Ax, Ay = A[0], A[1]\n Bx, By = B[0], B[1]\n Cx, Cy = C[0], C[1]\n Dx, Dy = D[0], D[1]\n\n # We assume A,B,C,D are all different nodes.\n # i.e. have NOT been sent edges (A,B) and (A,C)\n # So we can check for coincidence.\n\n if Ax == Bx and Ay == By: print \"Coincidence\"; return True\n if Ax == Cx and Ay == Cy: print \"Coincidence\"; return True\n if Ax == Dx and Ay == Dy: print \"Coincidence\"; return True\n if Bx == Cx and By == Cy: print \"Coincidence\"; return True\n if Bx == Dx and By == Dy: print \"Coincidence\"; return True\n if Cx == Dx and Cy == Dy: print \"Coincidence\"; return True\n\n AB = (Bx - Ax, By - Ay)\n AC = (Cx - Ax, Cy - Ay)\n AD = (Dx - Ax, Dy - Ay)\n\n CA = (Ax - Cx, Ay - Cy)\n CB = (Bx - Cx, By - Cy)\n CD = (Dx - Cx, Dy - Cy)\n\n BD = (Dx - Bx, Dy - By)\n DB = (Bx - Dx, By - Dy)\n\n # Generic cases where no three points are colinear.\n\n if crossproduct(AC,AD) > 0:\n if crossproduct(AC,AB) > 0:\n if crossproduct(AB,AD) > 0:\n # AB is heading towards crossing CD.\n if crossproduct(CB,CA) > 0:\n if crossproduct(CB,CD) > 0:\n if crossproduct(CD,CA) > 0:\n# print \"1 Edges cross! Dude!\"\n return True\n elif crossproduct(CB,CA) < 0:\n if crossproduct(CB,CD) < 0:\n if crossproduct(CD,CA) < 0:\n# print \"2 Edges cross! Dude!\"\n return True\n\n if crossproduct(AC,AD) < 0:\n if crossproduct(AC,AB) < 0:\n if crossproduct(AB,AD) < 0:\n # AB is heading towards crossing CD.\n if crossproduct(CB,CA) > 0:\n if crossproduct(CB,CD) > 0:\n if crossproduct(CD,CA) > 0:\n# print \"3 Edges cross! Dude!\"\n return True\n elif crossproduct(CB,CA) < 0:\n if crossproduct(CB,CD) < 0:\n if crossproduct(CD,CA) < 0:\n# print \"4 Edges cross! Dude!\"\n return True\n\n # Corner cases where a point is colinear with two others.\n # Cross detected if a point is ON the line segment.\n\n if crossproduct(AB,AC) == 0:\n# print \"C is colinear with A and B.\"\n if dotproduct(AB,AC) > 0 and dotproduct(AC,CB) > 0:\n print \"C is on line AB.\"\n return True\n\n if crossproduct(AB,AD) == 0:\n# print \"D is colinear with A and B\"\n if dotproduct(AB,AD) > 0 and dotproduct(AD,DB) > 0:\n print \"D is on line AB.\"\n return True\n\n if crossproduct(CD,CA) == 0:\n# print \"A is colinear with C and D.\"\n if dotproduct(CD,CA) > 0 and dotproduct(CA,AD) > 0:\n print \"A is on line CD.\"\n return True\n\n if crossproduct(CD,CB) == 0:\n# print \"B is colinear with C and D\"\n if dotproduct(CD,CB) > 0 and dotproduct(CB,BD) > 0:\n print \"B is on line CD.\"\n return True\n\n\n return False", "def crosses(line1, line2):\n (x1,y1), (x2,y2) = line1\n (u1,v1), (u2,v2) = line2\n (a,b), (c,d) = (x2-x1, u1-u2), (y2-y1, v1-v2)\n e, f = u1-x1, v1-y1\n denom = float(a*d - b*c)\n if MathHelper.near(denom, 0):\n # parallel\n return False\n else:\n t = (e*d - b*f)/denom\n s = (a*f - e*c)/denom\n # When 0<=t<=1 and 0<=s<=1 the point of intersection occurs within the\n # line segments\n return 0<=t<=1 and 0<=s<=1", "def position_check(pos_object):\n def check_coord(exp_x, exp_y, pos):\n return (exp_x == pos.get_x() and exp_y == pos.get_y())\n\n cur_x = pos_object.get_x()\n cur_y = pos_object.get_y()\n\n pos_object.move(checkersgame.NW)\n print check_coord(cur_x + 1, cur_y + 1, pos_object) #false\n pos_object.move(checkersgame.SE)\n print check_coord(cur_x, cur_y, pos_object) #true\n pos_object.move(checkersgame.NE)\n print check_coord(cur_x - 1, cur_y + 1, pos_object) #false\n pos_object.move(checkersgame.SW)\n print check_coord(cur_x, cur_y, pos_object) #true", "def is_in_desired_position(self,current_position, epsilon=0.05):\n\n is_in_desired_pos = False\n\n\n x_pos_plus = self.desired_point.x + epsilon\n x_pos_minus = self.desired_point.x - epsilon\n y_pos_plus = self.desired_point.y + epsilon\n y_pos_minus = self.desired_point.y - epsilon\n\n x_current = current_position.x\n y_current = current_position.y\n\n x_pos_are_close = (x_current <= x_pos_plus) and (x_current > x_pos_minus)\n y_pos_are_close = (y_current <= y_pos_plus) and (y_current > y_pos_minus)\n\n is_in_desired_pos = x_pos_are_close and y_pos_are_close\n\n rospy.logdebug(\"###### IS DESIRED POS ? ######\")\n rospy.logdebug(\"current_position\"+str(current_position))\n rospy.logdebug(\"x_pos_plus\"+str(x_pos_plus)+\",x_pos_minus=\"+str(x_pos_minus))\n rospy.logdebug(\"y_pos_plus\"+str(y_pos_plus)+\",y_pos_minus=\"+str(y_pos_minus))\n rospy.logdebug(\"x_pos_are_close\"+str(x_pos_are_close))\n rospy.logdebug(\"y_pos_are_close\"+str(y_pos_are_close))\n rospy.logdebug(\"is_in_desired_pos\"+str(is_in_desired_pos))\n rospy.logdebug(\"############\")\n\n return is_in_desired_pos", "def crosses(line1, line2):\n (x1,y1), (x2,y2) = line1\n (u1,v1), (u2,v2) = line2\n (a,b), (c,d) = (x2-x1, u1-u2), (y2-y1, v1-v2)\n e, f = u1-x1, v1-y1\n denom = float(a*d - b*c)\n if near(denom, 0):\n # parallel\n return False\n else:\n t = (e*d - b*f)/denom\n s = (a*f - e*c)/denom\n # When 0<=t<=1 and 0<=s<=1 the point of intersection occurs within the\n # line segments\n return 0<=t<=1 and 0<=s<=1", "def _crossed(self, other):\n\n\t\tif not other.disruptive and not self.disruptive and not (self.attributes.count(\"touch_player\")!=0\n\t\t\t\t and other is t12.player) and not (self.attributes.count(\"touch_enemies\")!=0 and other.attributes.count(\"actors\")!=0\n\t\t\t\t and other is not t12.player):\n\t\t\treturn False\n\n\t\t# let other=O, last=L, current=C\n\t\t# O L-----------C\n\t\t# see, if O is way over there on the left, who cares about it?\n\t\tif not self._inpath(other):\n\t\t\treturn False\n\n\t\t# wow, how awesome! The line widths match up! Who knew that \"top bottom\" has the same number of characters as \"left right\"?!\n\t\tif self.last.top >= other.last.bottom and self.geom.top >= other.geom.bottom: return False\n\t\tif self.last.bottom <= other.last.top and self.geom.bottom <= other.geom.top: return False\n\t\tif self.last.right <= other.last.left and self.geom.right <= other.geom.left: return False\n\t\tif self.last.left >= other.last.right and self.geom.left >= other.geom.right: return False\n\n\t\tmlines = ( (self.last.centerx, self.last.centery, self.geom.centerx, self.geom.centery), # 0 - path line\n\t\t\t(self.geom.left+1, self.geom.top+1, self.geom.left+1, self.geom.bottom-1), # 1 - left line\n\t\t\t(self.geom.right-1, self.geom.top+1, self.geom.right-1, self.geom.bottom-1), # 2 - right line\n\t\t\t(self.geom.left+1, self.geom.top+1, self.geom.right-1, self.geom.top+1), # 3 - top line\n\t\t\t(self.geom.left+1, self.geom.bottom-1, self.geom.right-1, self.geom.bottom-1), # 4 - bottom line\n\t\t\t(self.last.left+1, self.last.top+1, self.geom.left+1, self.geom.top+1),\n\t\t\t(self.last.right-1, self.last.top+1, self.geom.right-1, self.geom.top+1),\n\t\t\t(self.last.left+1, self.last.bottom-1, self.geom.left+1, self.geom.bottom-1),\n\t\t\t(self.last.right-1, self.last.bottom-1, self.geom.right-1, self.geom.bottom-1)\n\t\t\t)\n\n\t\tolines = ( (other.last.centerx, other.last.centery, other.geom.centerx, other.geom.centery), # 0 - path line\n\t\t\t(other.geom.left+1, other.geom.top+1, other.geom.left+1, other.geom.bottom-1), # 1 - left line\n\t\t\t(other.geom.right-1, other.geom.top+1, other.geom.right-1, other.geom.bottom-1), # 2 - right line\n\t\t\t(other.geom.left+1, other.geom.top+1, other.geom.right-1, other.geom.top+1), # 3 - top line\n\t\t\t(other.geom.left+1, other.geom.bottom-1, other.geom.right-1, other.geom.bottom-1), # 4 - bottom line\n\t\t\t(other.last.left+1, other.last.top+1, other.geom.left+1, other.geom.top+1),\n\t\t\t(other.last.right-1, other.last.top+1, other.geom.right-1, other.geom.top+1),\n\t\t\t(other.last.left+1, other.last.bottom-1, other.geom.left+1, other.geom.bottom-1),\n\t\t\t(other.last.right-1, other.last.bottom-1, other.geom.right-1, other.geom.bottom-1)\n\t\t\t)\n\n\t\tfor m in mlines:\n\t\t\tfor o in olines:\n\t\t\t\tif self._lint(m, o):\n\t\t\t\t\treturn True\n\t\treturn False", "def verify(self):\n for i in self.coords:\n if np.abs(6*i-int(6*i))>0.1: return False\n if np.abs(self.coords[2]+self.coords[0]+self.coords[1]) > 0.1: return False\n return True", "def check_move(self):\n\n if self.DEBUG_PRINT_FUNCTIONS:\n pass;\n print \"check_move\"\n\n if len(self.square) != 1 or self.piece == None:\n if self.DEBUG:\n print \"missing piece or square!\"\n return 5\n sqr_cords = self.c.coords(self.square) # square coords\n sqr_cntr = apply(self.find_center, sqr_cords) # square center\n pce_cntr = apply(self.find_center, self.c.coords(self.piece)) # piece center\n vtr = (sqr_cntr[0] - pce_cntr[0], sqr_cntr[1] - pce_cntr[1]) # piece vector(distence and direction)\n if self.DEBUG:\n pass; # print sqr_cords, sqr_cntr, pce_cntr, vtr\n\n if self.jumps[0]: # jump checker\n # if move has not been found by check_for_jumps then fail\n # else, ingore all the other checks, and succeed\n if self.jumps[0].count((self.piece, vtr)) != 1:\n self.show_message(\"You have a jump!\", .8)\n return 5\n else:\n self.jump_made = self.jumps[0].index((self.piece, vtr))\n if self.DEBUG:\n print \"jump_made: \", self.jump_made\n return 0\n\n # movement direction checker\n if self.c.itemcget(self.piece, \"outline\") != \"gold2\":\n if self.moving == \"black\":\n if vtr[1] > 0:\n if self.DEBUG:\n print \"wrong way, black!\"\n return 3\n else:\n if vtr[1] < 0:\n if self.DEBUG:\n print \"wrong way, red!\"\n return 3\n\n # distence checker\n if abs(vtr[0]) != self.SQUARESIZE or abs(vtr[1]) != self.SQUARESIZE:\n if self.DEBUG:\n print \"Too far!\"\n return 4\n\n # square emptiness checker\n if self.c.type(self.c.find_overlapping(sqr_cords[0] + (self.SQUARESIZE / 2), \\\n sqr_cords[1] + (self.SQUARESIZE / 2), \\\n sqr_cords[2] - (self.SQUARESIZE / 2), \\\n sqr_cords[3] - (self.SQUARESIZE / 2))) != \"rectangle\":\n if self.DEBUG:\n print \"not empty: \", self.c.find_overlapping(sqr_cords[0] + (self.SQUARESIZE / 2), \\\n sqr_cords[1] + (self.SQUARESIZE / 2), \\\n sqr_cords[2] - (self.SQUARESIZE / 2), \\\n sqr_cords[3] - (self.SQUARESIZE / 2))\n return 2\n\n return 0", "def report_cow_status(cow_position1, cow_position2, delta_t, boundary_points):\r\n #case 1\r\n cow_position1_x=cow_position1[0]\r\n cow_position1_y=cow_position1[1]\r\n cow_position2_x=cow_position2[0]\r\n cow_position2_y=cow_position2[1]\r\n x1=boundary_points[0][0]\r\n y1=boundary_points[0][1]\r\n x2=boundary_points[2][0]\r\n y2=boundary_points[2][1]\r\n\r\n if (cow_position1_x>x1 and cow_position1_y>y2 and cow_position1_x<x2 and cow_position1_y<y1) and (cow_position2_x>x1 and cow_position2_y>y2 and cow_position2_x<x2 and cow_position2_y<y1):\r\n left=abs(cow_position2_x-x1)\r\n right=abs(cow_position2_x-x2)\r\n up=abs(cow_position2_y-y1)\r\n down=abs(cow_position2_y-y2)\r\n ways=[left,right,up,down]\r\n closest=min(ways)\r\n travel=math.sqrt((cow_position1_x-cow_position2_x)**2+(cow_position1_y-cow_position2_y)**2)\r\n velocity=travel/delta_t\r\n time=closest/velocity\r\n time=round(time,2)\r\n print (time)\r\n\r\n #case 2\r\n elif not(cow_position1_x>x1 and cow_position1_y>y2 and cow_position1_x<x2 and cow_position1_y<y1) and not (cow_position2_x>x1 and cow_position2_y>y2 and cow_position2_x<x2 and cow_position2_y<y1):\r\n travel=math.sqrt((cow_position1_x-cow_position2_x)**2+(cow_position1_y-cow_position2_y)**2)\r\n distance=math.sqrt((x1-cow_position2_x)**2+(y1-cow_position2_y)**2)\r\n velocity=travel/delta_t\r\n time=distance/velocity\r\n time=round(time,2)\r\n print (time)\r\n\r\n\r\n #case 3\r\n elif (not(cow_position1_x>x1 and cow_position1_y>y2 and cow_position1_x<x2 and cow_position1_y<y1)) and (cow_position2_x>x1 and cow_position2_y>y2 and cow_position2_x<x2 and cow_position2_y<y1):\r\n print (\"-1\")\r\n\r\n #case 4\r\n elif (cow_position1_x>x1 and cow_position1_y>y2 and cow_position1_x<x2 and cow_position1_y<y1) and (not(cow_position2_x>x1 and cow_position2_y>y2 and cow_position2_x<x2 and cow_position2_y<y1)):\r\n print (\"0\")", "def check_collision(self, interval):\n next_displacement = self.displacement.add_make(self.velocity) # add radius/side length here?\n for p in self.physics_canvas.physics_objects:\n if p != self:\n other_next_displacement = p.displacement.add_make(p.velocity)\n y_cross = False\n if self.displacement.y <= p.displacement.y:\n if next_displacement.y + self.y_side >= other_next_displacement.y - p.y_side:\n y_cross = True\n elif self.displacement.y >= p.displacement.y:\n if next_displacement.y - self.y_side <= other_next_displacement.y + p.y_side:\n y_cross = True\n x_cross = False\n if self.displacement.x <= p.displacement.x:\n if next_displacement.x + self.x_side >= other_next_displacement.x - p.x_side:\n x_cross = True\n elif self.displacement.x >= p.displacement.x:\n if next_displacement.x - self.x_side <= other_next_displacement.x + p.x_side:\n x_cross = True\n\n if x_cross and y_cross:\n self.collide(p, next_displacement, other_next_displacement, interval)\n return True\n return False", "def on_corner(self):\n for c in self.corners:\n if abs(c[0]-self.position[0]) <= EPSILON and abs(c[1]-self.position[1]) <= EPSILON:\n return True\n return False", "def check_for_jumps(self):\n pass\n if self.DEBUG_PRINT_FUNCTIONS:\n print \"check_for_jumps\"\n if self.moving == \"red\":\n baz_normal = [(2 * self.SQUARESIZE, 2 * self.SQUARESIZE), (-2 * self.SQUARESIZE, 2 * self.SQUARESIZE)]\n if self.moving == \"black\":\n baz_normal = [(2 * self.SQUARESIZE, -2 * self.SQUARESIZE), (-2 * self.SQUARESIZE, -2 * self.SQUARESIZE)]\n baz = baz_normal\n for piece in self.pieces[self.moving]:\n if self.c.itemcget(piece, \"outline\") == \"gold2\":\n baz = [(2 * self.SQUARESIZE, 2 * self.SQUARESIZE), \\\n (-2 * self.SQUARESIZE, 2 * self.SQUARESIZE),\n (2 * self.SQUARESIZE, -2 * self.SQUARESIZE), \\\n (-2 * self.SQUARESIZE, -2 * self.SQUARESIZE)]\n else:\n baz = baz_normal\n for vtr in baz:\n bar = self.c.coords(piece)\n sqr_cords = (bar[0] - self.piece_offset + vtr[0], \\\n bar[1] - self.piece_offset + vtr[1], \\\n bar[2] + self.piece_offset + vtr[0], \\\n bar[3] + self.piece_offset + vtr[1])\n if self.jumpable(vtr, sqr_cords):\n if len(self.c.find_overlapping(sqr_cords[0] + 5, sqr_cords[1] + 5, \\\n sqr_cords[2] - 5, sqr_cords[3] - 5)) == 1:\n self.jumps[0].append((piece, vtr))\n self.jumps[1].append(self.quux)\n self.quux = None\n if self.DEBUG_BIG_THINGS:\n print \"self.jumps: \", self.jumps", "def is_ahead(self, current_car_pose, next_wp_pose):\n current_x = current_car_pose.position.x\n current_y = current_car_pose.position.y\n\n next_x = next_wp_pose.pose.position.x\n next_y = next_wp_pose.pose.position.y\n\n _, _, current_car_yaw = tf.transformations.euler_from_quaternion([current_car_pose.orientation.x, current_car_pose.orientation.y, current_car_pose.orientation.z, current_car_pose.orientation.w])\n\n isAhead = (next_x - current_x) * math.cos(current_car_yaw) + (next_y - current_y) * math.sin(current_car_yaw)\n\n return isAhead > 0", "def crosses(D, ep):\n\n # map the vertices of the edge-pair to their location in the drawing D\n a, b, c, d = [D.index(v) for v in (ep[0][0], ep[0][1], ep[1][0], ep[1][1])]\n\n # check vertex locations for crossing\n return (a < c < b < d) or (b < c < a < d) or (a < d < b < c) or \\\n (b < d < a < c) or (c < a < d < b) or (d < a < c < b) or \\\n (c < b < d < a) or (d < b < c < a)", "def test_move_available(self):\n plateau = Plateau(5, 7)\n self.assertTrue(plateau.is_position_within_plateau_area(RoverPosition(2, 3)))\n self.assertFalse(plateau.is_position_within_plateau_area(RoverPosition(6, 2)))\n self.assertFalse(plateau.is_position_within_plateau_area(RoverPosition(3, 8)))\n self.assertFalse(plateau.is_position_within_plateau_area(RoverPosition(-1, 2)))\n self.assertFalse(plateau.is_position_within_plateau_area(RoverPosition(-1, -1)))", "def test_cross_won(self):\n t = TicTacToe()\n\n self.assertEqual(t.place_marker('x',0,0),t.STATES.NAUGHT_TURN)\n self.assertEqual(t.place_marker('o',2,2),t.STATES.CROSS_TURN)\n self.assertEqual(t.place_marker('x',2,0),t.STATES.NAUGHT_TURN)\n self.assertEqual(t.place_marker('o',1,2),t.STATES.CROSS_TURN)\n self.assertEqual(t.place_marker('x',0,2),t.STATES.NAUGHT_TURN)\n self.assertEqual(t.place_marker('o',2,2),t.STATES.CROSS_TURN)\n self.assertEqual(t.place_marker('x',1,1),t.STATES.CROSS_WON)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transfer CA certificate for an upgrade to a subcloud Returns the next state in the state machine on success. Any exceptions raised by this method set the strategy to FAILED.
def perform_state_action(self, strategy_step): if self.subcloud_type == consts.SYSTEM_MODE_SIMPLEX: return self.next_state self.info_log(strategy_step, "Start transferring CA certificate...") retry_counter = 0 while True: try: sysinv_client = self.get_sysinv_client(strategy_step.subcloud.name) data = {'mode': 'openldap_ca'} ldap_ca_cert, ldap_ca_key = utils.get_certificate_from_secret( consts.OPENLDAP_CA_CERT_SECRET_NAME, consts.CERT_NAMESPACE_PLATFORM_CA_CERTS) sysinv_client.update_certificate('', ldap_ca_cert + ldap_ca_key, data) break except Exception as e: self.warn_log(strategy_step, "Encountered exception: %s" % str(e)) retry_counter += 1 if retry_counter > self.max_retries: raise Exception( "Failed to transfer CA certificate for subcloud %s." % strategy_step.subcloud.name) self.warn_log(strategy_step, "Retry (%i/%i) in %i secs." % (retry_counter, self.max_retries, self.sleep_duration)) time.sleep(self.sleep_duration) self.info_log(strategy_step, "CA certificate transfer completed.") return self.next_state
[ "def perform_state_action(self, strategy_step):\n\n self.info_log(strategy_step, \"Performing simplex upgrade for subcloud\")\n\n subcloud_sysinv_client = None\n subcloud_barbican_client = None\n try:\n subcloud_sysinv_client = self.get_sysinv_client(\n strategy_step.subcloud.name)\n subcloud_barbican_client = self.get_barbican_client(\n strategy_step.subcloud.name)\n except Exception:\n # if getting the token times out, the orchestrator may have\n # restarted and subcloud may be offline; so will attempt\n # to use the persisted values\n message = (\"Simplex upgrade perform_subcloud_install \"\n \"subcloud %s failed to get subcloud client\" %\n strategy_step.subcloud.name)\n self.error_log(strategy_step, message)\n pass\n\n # Check whether subcloud is already re-installed with N+1 load\n target_version = SW_VERSION\n if self._check_load_already_active(\n target_version, subcloud_sysinv_client):\n self.info_log(strategy_step,\n \"Load:%s already active\" % target_version)\n return self.next_state\n\n # Check whether subcloud supports redfish, and if not, fail.\n # This needs to be inferred from absence of install_values as\n # there is currrently no external api to query.\n install_values = self.get_subcloud_upgrade_install_values(\n strategy_step, subcloud_sysinv_client, subcloud_barbican_client)\n\n local_ks_client = self.get_keystone_client()\n\n # Upgrade the subcloud to the install_values image\n self.perform_subcloud_install(\n strategy_step, local_ks_client.session, install_values)\n return self.next_state", "def _add_kube_rootca_update_cert_stage(self):\n from nfv_vim import strategy\n stage = strategy.StrategyStage(\n strategy.STRATEGY_STAGE_NAME.KUBE_ROOTCA_UPDATE_CERT)\n # if there is an existing cert file, upload it\n if self._cert_file:\n stage.add_step(\n strategy.KubeRootcaUpdateUploadCertStep(self._cert_file))\n else:\n stage.add_step(\n strategy.KubeRootcaUpdateGenerateCertStep(self._expiry_date,\n self._subject))\n self.apply_phase.add_stage(stage)\n # Proceed to the next stage\n self._add_kube_rootca_hosts_trustbothcas_stage()", "def update_intermediate_ca_certificate(self, context,\n root_ca_crt, sc_ca_cert, sc_ca_key):\n sc_endpoint_cert_secret_ns = 'sc-cert'\n sc_intermediate_ca_secret_name = 'sc-adminep-ca-certificate'\n sc_admin_endpoint_secret_name = constants.SC_ADMIN_ENDPOINT_SECRET_NAME\n if root_ca_crt is None:\n LOG.error('Root CA cert is not provided')\n raise exception.SysinvException(_(\n \"Root CA certificate is not provided\"))\n\n kube_operator = kubernetes.KubeOperator()\n secret = kube_operator.kube_get_secret(sc_intermediate_ca_secret_name,\n sc_endpoint_cert_secret_ns)\n if not hasattr(secret, 'data'):\n raise Exception('Invalid secret %s\\\\%s' % (\n sc_endpoint_cert_secret_ns, sc_intermediate_ca_secret_name\n ))\n\n tls_key = base64.encode_as_text(sc_ca_key)\n tls_crt = base64.encode_as_text(sc_ca_cert)\n if tls_key == secret.data['tls.key'] and tls_crt == secret.data['tls.crt']:\n LOG.info('Intermediate CA cert is not changed')\n return\n\n secret.data['tls.key'] = tls_key\n secret.data['tls.crt'] = tls_crt\n\n new = kube_operator.kube_patch_secret(sc_intermediate_ca_secret_name,\n sc_endpoint_cert_secret_ns,\n secret)\n if new.data['tls.key'] == tls_key and new.data['tls.crt'] == tls_crt:\n with open(constants.DC_ROOT_CA_CONFIG_PATH, 'w') as f:\n f.write(root_ca_crt)\n res = kube_operator.kube_delete_secret(sc_admin_endpoint_secret_name,\n sc_endpoint_cert_secret_ns)\n\n LOG.info('Deleting %s:%s, result %s, msg %s' %\n (sc_endpoint_cert_secret_ns,\n sc_admin_endpoint_secret_name,\n res.status, res.message))\n else:\n raise Exception(\"Unexpected result updating %s\\\\%s. tls.crt \"\n \"and/or tls.key don't match\"\n % (sc_endpoint_cert_secret_ns, sc_endpoint_cert_secret_ns))", "def test_update_cloud_certificate(self):\n pass", "def report_kube_rootca_update_failure(self, host_uuid, reported_cfg,\n error):\n LOG.info(\"Kube root CA update phase '%s' failed on host: %s, error: %s\"\n % (reported_cfg, host_uuid, error))\n\n # If the update is aborted, don't update anything\n c_update = self.dbapi.kube_rootca_update_get_one()\n if c_update.state == kubernetes.KUBE_ROOTCA_UPDATE_ABORTED:\n LOG.info(\"Current update has been aborted at host: %s, config: %s\"\n % (host_uuid, reported_cfg))\n return\n\n if reported_cfg == puppet_common.REPORT_KUBE_CERT_UPDATE_TRUSTBOTHCAS:\n state = kubernetes.KUBE_ROOTCA_UPDATING_HOST_TRUSTBOTHCAS_FAILED\n elif reported_cfg == puppet_common.REPORT_KUBE_CERT_UPDATE_UPDATECERTS:\n state = kubernetes.KUBE_ROOTCA_UPDATING_HOST_UPDATECERTS_FAILED\n elif reported_cfg == puppet_common.REPORT_KUBE_CERT_UPDATE_TRUSTNEWCA:\n state = kubernetes.KUBE_ROOTCA_UPDATING_HOST_TRUSTNEWCA_FAILED\n else:\n LOG.info(\"Not supported reported_cfg: %s\" % reported_cfg)\n raise exception.SysinvException(_(\n \"Not supported reported_cfg: %s\" % reported_cfg))\n\n # Update host 'update state'\n h_update = self.dbapi.kube_rootca_host_update_get_by_host(host_uuid)\n self.dbapi.kube_rootca_host_update_update(h_update.id,\n {'state': state})\n\n # Update cluster 'update state'\n self.dbapi.kube_rootca_update_update(c_update.id, {'state': state})", "def _precheck_save_kubernetes_rootca_cert(self, update, temp_pem_contents):\n\n if update.state != kubernetes.KUBE_ROOTCA_UPDATE_STARTED:\n msg = \"A new root CA certificate already exists\"\n return dict(success=\"\", error=msg)\n\n if update.to_rootca_cert:\n LOG.info(\"root CA target with serial number %s will be overwritten\"\n % update.to_rootca_cert)\n\n # extract the certificate contained in PEM file\n try:\n cert = cutils.extract_certs_from_pem(temp_pem_contents)[0]\n except Exception as e:\n msg = \"Failed to extract certificate from file: %s\" % str(e)\n return dict(success=\"\", error=msg)\n\n if not cert:\n msg = \"No certificate have been added, \" \\\n \"no valid certificate found in file.\"\n LOG.info(msg)\n return dict(success=\"\", error=msg)\n\n # extract current k8s rootca\n current_cert = \\\n cutils.get_certificate_from_file(kubernetes.KUBERNETES_ROOTCA_CERT)\n if not current_cert:\n msg = \"Not able to get the current kube rootca\"\n return dict(success=\"\", error=msg)\n\n # validate certificate\n msg = cutils.check_cert_validity(cert)\n\n if msg is not None:\n return dict(success=\"\", error=msg)\n\n is_ca = cutils.is_ca_cert(cert)\n if not is_ca:\n msg = \"The certificate in the file is not a CA certificate\"\n LOG.error(msg)\n return dict(success=\"\", error=msg)\n\n # extract information regarding the new rootca\n try:\n new_cert_id = cutils.build_cert_identifier(cert)\n except Exception:\n msg = \"Failed to extract subject and serial number \" \\\n \"from new root CA\"\n LOG.error(msg)\n return dict(success=\"\", error=msg)\n\n return dict(success=new_cert_id, error=\"\")", "def update_installation(self, attempts=3):\n if self.no_ejbca_update:\n logger.debug('EJBCA update is disabled')\n return\n\n try:\n logger.debug('Going to download specs from the provisioning servers')\n for provserver in PROVISIONING_SERVERS:\n url = 'https://%s/ejbca/index.json' % provserver\n tmpdir = util.safe_new_dir('/tmp/ejbca-update')\n\n for attempt in range(attempts):\n try:\n self.audit.audit_evt('prov-ejbca', url=url)\n res = requests.get(url=url, timeout=15)\n res.raise_for_status()\n js = res.json()\n\n self.audit.audit_evt('prov-ejbca', url=url, response=js)\n revs = js['versions']['6.3.1.1']['revisions']\n\n top_rev = None\n for rev in revs:\n if top_rev is None or top_rev['rev'] < rev['rev']:\n top_rev = rev\n\n archive_url = top_rev['url']\n logger.debug('Revision: %s, url: %s' % (top_rev['rev'], archive_url))\n\n # Download archive.\n archive_path = os.path.join(tmpdir, 'ejbca_6_3_1_1.tgz')\n self.download_file(archive_url, archive_path)\n logger.debug('File downloaded, updating...')\n\n # Update\n self.update_ejbca_from_file(archive_path, tmpdir)\n return 0\n\n except errors.SetupError as e:\n logger.debug('SetupException in updating EJBCA from the provisioning server: %s' % e)\n self.audit.audit_exception(e, process='prov-ejbca')\n\n except Exception as e:\n logger.debug('Exception in updating EJBCA from the provisioning server: %s' % e)\n self.audit.audit_exception(e, process='prov-ejbca')\n\n finally:\n if os.path.exists(tmpdir):\n shutil.rmtree(tmpdir)\n\n return 0\n\n except Exception as e:\n logger.debug('Exception when updating EJBCA')\n self.audit.audit_exception(e)", "def refresh_cert_and_key(self):\n d = None\n\n if \"post_body\" in self.config[\"cfssl\"]:\n d = self.config[\"cfssl\"][\"post_body\"]\n else:\n d = {\n \"request\": self.config[\"cfssl\"][\"request\"]\n }\n\n url = \"{}/api/v1/cfssl/newcert\".format(self.config[\"cfssl\"][\"url\"])\n\n kwargs = {}\n\n if \"auth\" in self.config[\"cfssl\"]:\n kwargs[\"auth\"] = (self.config[\"cfssl\"][\"auth\"][\"user\"],\n self.config[\"cfssl\"][\"auth\"][\"password\"])\n\n if \"ca_bundle\" in self.config[\"cfssl\"]:\n kwargs[\"verify\"] = self.config[\"cfssl\"][\"ca_bundle\"]\n\n try:\n resp = requests.post(url, json=d, **kwargs)\n resp.raise_for_status()\n except requests.exceptions.RequestException as e:\n print(\"cfssl refresh failed! {}\".format(e))\n\n if \"onfailure\" in self.config:\n if \"post_to_slack\" in self.config[\"onfailure\"]:\n\n msg_lines = [\n \"exception: `{}`\".format(e),\n \"request:\",\n \"```\",\n \"{}\".format(\n json.dumps(self.config[\"cfssl\"][\"request\"],\n indent=2)),\n \"```\"\n ]\n\n self._post_to_slack(\"cfssl refresh failed!\", msg_lines)\n\n return False\n\n r = resp.json()\n\n self._write_out_cert_files(r[\"result\"])\n\n if \"onsuccess\" in self.config:\n if \"execute_command\" in self.config[\"onsuccess\"]:\n args = shlex.split(\n self.config[\"onsuccess\"][\"execute_command\"]\n )\n\n child = subprocess.Popen(args, stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n stdout, stderr = child.communicate()\n\n if child.returncode != 0:\n if \"onfailure\" in self.config:\n if \"post_to_slack\" in self.config[\"onfailure\"]:\n msg_lines = [\n \"args: `{}`\".format(args),\n \"rc: {}\".format(child.returncode),\n \"stdout: `{}`\".format(stdout.strip()),\n \"stderr: `{}`\".format(stderr.strip()),\n ]\n\n self._post_to_slack(\n \"post cfssl refresh execute command failed!\",\n msg_lines)\n\n return False\n\n return True", "def _get_subcloud_upgrade_data_install(self, strategy_step):\n\n upgrade_data_install = {}\n\n subcloud = db_api.subcloud_get(self.context, strategy_step.subcloud_id)\n if not subcloud.data_install:\n # Set the deploy status to pre-install-failed so it can be\n # handled accordingly in pre check step.\n message = (\"Failed to get upgrade data from install\")\n db_api.subcloud_update(\n self.context, strategy_step.subcloud_id,\n deploy_status=consts.DEPLOY_STATE_PRE_INSTALL_FAILED,\n error_description=message)\n\n self.warn_log(strategy_step, message)\n raise Exception(message)\n\n data_install = json.loads(subcloud.data_install)\n\n # base64 encoded sysadmin_password is default\n upgrade_data_install.update({\n 'ansible_become_pass': consts.TEMP_SYSADMIN_PASSWORD,\n 'ansible_ssh_pass': consts.TEMP_SYSADMIN_PASSWORD,\n })\n # Get mandatory bootstrap info from data_install\n # bootstrap_address is referenced in SubcloudInstall\n # bootstrap-address is referenced in create_subcloud_inventory and\n # subcloud manager.\n # todo(jkung): refactor to just use one bootstrap address index\n upgrade_data_install.update({\n 'bootstrap_interface': data_install.get('bootstrap_interface'),\n 'bootstrap-address': data_install.get('bootstrap_address'),\n 'bootstrap_address': data_install.get('bootstrap_address'),\n 'bootstrap_address_prefix': data_install.get('bootstrap_address_prefix'),\n 'bmc_username': data_install.get('bmc_username'),\n 'bmc_address': data_install.get('bmc_address'),\n 'bmc_password': data_install.get('bmc_password'),\n })\n\n persistent_size = data_install.get('persistent_size')\n if persistent_size is not None:\n upgrade_data_install.update({'persistent_size': persistent_size})\n\n for p in dccommon_consts.OPTIONAL_INSTALL_VALUES:\n if p in data_install:\n upgrade_data_install.update({p: data_install.get(p)})\n\n return upgrade_data_install", "def update_certs():\n\n stack_name = get_stack_name()\n cfn_config = get_config()\n # Upload any SSL certificates to our EC2 instances\n updated_count = False\n if 'ssl' in cfn_config.data:\n logging.info(\"Reloading SSL certificates...\")\n iam = get_connection(IAM)\n updated_count = iam.update_ssl_certificates(cfn_config.ssl(),\n stack_name)\n else:\n logging.error(\"No ssl section found in cloud config file, aborting...\")\n sys.exit(1)\n\n # Arbitrary wait to allow SSL upload to register with AWS\n # Otherwise, we can get an ARN for the load balancer certificates\n # without it being ready to assign\n time.sleep(3)\n\n # Set the certificates on ELB's if we have any\n if updated_count > 0:\n if 'elb' in cfn_config.data:\n logging.info(\"Setting load balancer certificates...\")\n elb = get_connection(ELB)\n elb.set_ssl_certificates(cfn_config.ssl(), stack_name)\n else:\n logging.error(\"No certificates updated so skipping \"\n \"ELB certificate update...\")", "def test_02_upgrade_kubernetes_cluster(self):\n if self.setup_failed == True:\n self.fail(\"Setup incomplete\")\n global k8s_cluster\n k8s_cluster = self.getValidKubernetesCluster(version=self.kubernetes_version_v1)\n\n time.sleep(self.services[\"sleep\"])\n self.debug(\"Upgrading Kubernetes cluster with ID: %s\" % k8s_cluster.id)\n try:\n k8s_cluster = self.upgradeKubernetesCluster(k8s_cluster.id, self.kubernetes_version_v2.id)\n except Exception as e:\n self.deleteKubernetesClusterAndVerify(k8s_cluster.id, False, True)\n self.fail(\"Failed to upgrade Kubernetes cluster due to: %s\" % e)\n\n self.verifyKubernetesClusterUpgrade(k8s_cluster, self.kubernetes_version_v2.id)\n return", "def migrate(self):\n migrate_certificate(self)", "def update_intermediate_ca_certificate(self, context,\n root_ca_crt, sc_ca_cert, sc_ca_key):\n return self.call(context,\n self.make_msg('update_intermediate_ca_certificate',\n root_ca_crt=root_ca_crt,\n sc_ca_cert=sc_ca_cert,\n sc_ca_key=sc_ca_key))", "def kube_upgrade_control_plane(self, context, host_uuid):\n\n def manifest_apply_failed_state(context, fail_state, host_obj):\n kube_upgrade_obj = objects.kube_upgrade.get_one(context)\n kube_upgrade_obj.state = fail_state\n kube_upgrade_obj.save()\n kube_host_upgrade_obj = objects.kube_host_upgrade.get_by_host_id(\n context, host_obj.id)\n kube_host_upgrade_obj.status = \\\n kubernetes.KUBE_HOST_UPGRADING_CONTROL_PLANE_FAILED\n kube_host_upgrade_obj.save()\n return\n\n host_obj = objects.host.get_by_uuid(context, host_uuid)\n host_name = host_obj.hostname\n kube_host_upgrade_obj = objects.kube_host_upgrade.get_by_host_id(\n context, host_obj.id)\n target_version = kube_host_upgrade_obj.target_version\n kube_upgrade_obj = objects.kube_upgrade.get_one(context)\n kube_operator = kubernetes.KubeOperator()\n current_versions = kube_operator.kube_get_kubelet_versions()\n system = self.dbapi.isystem_get_one()\n\n if kube_upgrade_obj.state == kubernetes.KUBE_UPGRADING_FIRST_MASTER:\n if system.system_mode == constants.SYSTEM_MODE_SIMPLEX:\n next_versions = kube_operator.kube_get_higher_patch_version(current_versions.get(host_name, None),\n kube_upgrade_obj.to_version)\n target_version = next_versions[0]\n kube_cmd_versions = objects.kube_cmd_version.get(context)\n kube_cmd_versions.kubeadm_version = target_version.lstrip('v')\n kube_cmd_versions.kubelet_version = current_versions.get(host_name, None).lstrip('v')\n kube_cmd_versions.save()\n kube_host_upgrade_obj.target_version = target_version\n kube_host_upgrade_obj.save()\n\n puppet_class = 'platform::kubernetes::upgrade_first_control_plane'\n new_state = kubernetes.KUBE_UPGRADED_FIRST_MASTER\n fail_state = kubernetes.KUBE_UPGRADING_FIRST_MASTER_FAILED\n\n # Drop any removed/unsupported feature gates before we upgrade to a\n # newer Kubernetes. If we leave them in we can prevent K8s services\n # from starting up. If we hit any problems we'll still try and\n # convert what we can.\n rc = 0\n\n # The bootstrap config file is used by backup/restore.\n if self.sanitize_feature_gates_bootstrap_config_file(target_version) == 1:\n LOG.error(\"Problem sanitizing bootstrap config file.\")\n rc = 1\n\n # The service parameters are used by backup/restore and the custom\n # K8s configuration functionality.\n if self.sanitize_feature_gates_service_parameters(target_version) == 1:\n LOG.error(\"Problem sanitizing feature gates service parameter.\")\n rc = 1\n\n if self.sanitize_feature_gates_kubeadm_configmap(target_version) == 1:\n LOG.error(\"Problem sanitizing kubeadm configmap feature gates.\")\n rc = 1\n\n if self.sanitize_image_repository_kubeadm_configmap(target_version) == 1:\n LOG.error(\"Problem updating kubeadm configmap image repository.\")\n rc = 1\n\n # The kubelet configmap is used by the K8s upgrade itself.\n if self.sanitize_feature_gates_kubelet_configmap(target_version) == 1:\n LOG.error(\"Problem sanitizing kubelet configmap feature gates.\")\n rc = 1\n\n # Work around upstream kubeadm configmap parsing issue.\n if self._kube.kubeadm_configmap_reformat(target_version) == 1:\n LOG.error(\"Problem reformatting kubelet configmap.\")\n rc = 1\n\n if rc == 1:\n kube_upgrade_obj.state = fail_state\n kube_upgrade_obj.save()\n return\n\n elif kube_upgrade_obj.state == kubernetes.KUBE_UPGRADING_SECOND_MASTER:\n puppet_class = 'platform::kubernetes::upgrade_control_plane'\n new_state = kubernetes.KUBE_UPGRADED_SECOND_MASTER\n fail_state = kubernetes.KUBE_UPGRADING_SECOND_MASTER_FAILED\n else:\n raise exception.SysinvException(_(\n \"Invalid state %s to upgrade control plane.\" %\n kube_upgrade_obj.state))\n\n # Update the config for this host\n personalities = [host_obj.personality]\n config_uuid = self._config_update_hosts(context, personalities,\n [host_uuid])\n\n # Apply the runtime manifest to upgrade the control plane\n config_dict = {\n \"personalities\": personalities,\n \"host_uuids\": [host_uuid],\n \"classes\": [puppet_class]\n }\n try:\n self._config_apply_runtime_manifest(context, config_uuid, config_dict)\n except Exception:\n LOG.error(\"Manifest apply failed for host %s with config_uuid %s\" %\n (host_name, config_uuid))\n manifest_apply_failed_state(context, fail_state, host_obj)\n\n # Wait for the manifest to be applied\n elapsed = 0\n while elapsed < kubernetes.MANIFEST_APPLY_TIMEOUT:\n elapsed += kubernetes.MANIFEST_APPLY_INTERVAL\n greenthread.sleep(kubernetes.MANIFEST_APPLY_INTERVAL)\n host_obj = objects.host.get_by_uuid(context, host_uuid)\n if host_obj.config_target == host_obj.config_applied:\n LOG.info(\"Config was applied for host %s\" % host_name)\n break\n LOG.debug(\"Waiting for config apply on host %s\" % host_name)\n else:\n LOG.warning(\"Manifest apply failed for host %s\" % host_name)\n manifest_apply_failed_state(context, fail_state, host_obj)\n\n # Wait for the control plane pods to start with the new version\n elapsed = 0\n while elapsed < kubernetes.POD_START_TIMEOUT:\n elapsed += kubernetes.POD_START_INTERVAL\n greenthread.sleep(kubernetes.POD_START_INTERVAL)\n cp_versions = kube_operator.kube_get_control_plane_versions()\n if cp_versions.get(host_name, None) == target_version:\n LOG.info(\"Control plane was updated for host %s\" % host_name)\n break\n LOG.debug(\"Waiting for control plane update on host %s\" % host_name)\n else:\n LOG.warning(\"Control plane upgrade failed for host %s\" %\n host_name)\n kube_host_upgrade_obj = objects.kube_host_upgrade.get_by_host_id(\n context, host_obj.id)\n kube_host_upgrade_obj.status = \\\n kubernetes.KUBE_HOST_UPGRADING_CONTROL_PLANE_FAILED\n kube_host_upgrade_obj.save()\n kube_upgrade_obj = objects.kube_upgrade.get_one(context)\n kube_upgrade_obj.state = fail_state\n kube_upgrade_obj.save()\n return\n\n # The control plane update was successful\n kube_host_upgrade_obj = objects.kube_host_upgrade.get_by_host_id(\n context, host_obj.id)\n kube_host_upgrade_obj.status = None\n kube_host_upgrade_obj.save()\n kube_upgrade_obj = objects.kube_upgrade.get_one(context)\n kube_upgrade_obj.state = new_state\n kube_upgrade_obj.save()", "def report_kube_rootca_pods_update_failure(self, reported_cfg, error):\n LOG.info(\"Kube root CA update phase '%s' failed for pods, error: %s\"\n % (reported_cfg, error))\n\n # If the update is aborted, don't update anything\n c_update = self.dbapi.kube_rootca_update_get_one()\n if c_update.state == kubernetes.KUBE_ROOTCA_UPDATE_ABORTED:\n LOG.info(\"Current update has been aborted at config: %s\"\n % (reported_cfg))\n return\n\n if reported_cfg == \\\n puppet_common.REPORT_KUBE_CERT_UPDATE_PODS_TRUSTBOTHCAS:\n state = kubernetes.KUBE_ROOTCA_UPDATING_PODS_TRUSTBOTHCAS_FAILED\n elif reported_cfg == \\\n puppet_common.REPORT_KUBE_CERT_UPDATE_PODS_TRUSTNEWCA:\n state = kubernetes.KUBE_ROOTCA_UPDATING_PODS_TRUSTNEWCA_FAILED\n else:\n LOG.info(\"Not supported reported_cfg: %s\" % reported_cfg)\n raise exception.SysinvException(_(\n \"Not supported reported_cfg: %s\" % reported_cfg))\n\n # Update cluster 'update state'\n self.dbapi.kube_rootca_update_update(c_update.id, {'state': state})", "def _setup_ca_cert(self):\r\n if not self.verify:\r\n return\r\n\r\n ca_certs_available = [cert\r\n for cert in libcloud.security.CA_CERTS_PATH\r\n if os.path.exists(cert) and os.path.isfile(cert)]\r\n if ca_certs_available:\r\n # use first available certificate\r\n self.ca_cert = ca_certs_available[0]\r\n else:\r\n raise RuntimeError(\r\n libcloud.security.CA_CERTS_UNAVAILABLE_ERROR_MSG)", "def test_01_invalid_upgrade_kubernetes_cluster(self):\n if self.setup_failed == True:\n self.fail(\"Setup incomplete\")\n global k8s_cluster\n k8s_cluster = self.getValidKubernetesCluster(version=self.kubernetes_version_v2)\n\n self.debug(\"Downgrading Kubernetes cluster with ID: %s to a lower version. This should fail!\" % k8s_cluster.id)\n\n try:\n k8s_cluster = self.upgradeKubernetesCluster(k8s_cluster.id, self.kubernetes_version_v1.id)\n self.debug(\"Invalid CKS Kubernetes HA cluster deployed with ID: %s. Deleting it and failing test.\" % self.kubernetes_version_v1.id)\n self.deleteKubernetesClusterAndVerify(k8s_cluster.id, False, True)\n self.fail(\"Kubernetes cluster downgrade to a lower Kubernetes supported version. Must be an error.\")\n except Exception as e:\n self.debug(\"Upgrading Kubernetes cluster with invalid Kubernetes supported version check successful, API failure: %s\" % e)\n self.deleteKubernetesClusterAndVerify(k8s_cluster.id, False, True)\n\n self.verifyKubernetesClusterUpgrade(k8s_cluster, self.kubernetes_version_v2.id)\n return", "def _get_subcloud_upgrade_data(\n self, strategy_step, subcloud_sysinv_client, subcloud_barbican_client):\n\n volatile_data_install = {}\n\n if subcloud_sysinv_client is None:\n # subcloud is not reachable, use previously saved values\n subcloud = db_api.subcloud_get(\n self.context, strategy_step.subcloud_id)\n if subcloud.data_upgrade:\n return json.loads(subcloud.data_upgrade)\n else:\n message = ('Cannot retrieve upgrade data install '\n 'for subcloud: %s' %\n strategy_step.subcloud.name)\n raise Exception(message)\n\n subcloud_system = subcloud_sysinv_client.get_system()\n\n if subcloud_system.system_type != 'All-in-one':\n message = ('subcloud %s install unsupported for system type: %s' %\n (strategy_step.subcloud.name,\n subcloud_system.system_type))\n raise Exception(message)\n\n host = subcloud_sysinv_client.get_host('controller-0')\n\n install_type = self._get_install_type(host)\n\n bmc_password = None\n if subcloud_barbican_client:\n bmc_password = subcloud_barbican_client.get_host_bmc_password(host.uuid)\n if bmc_password:\n # If the host is configured to store bmc in its barbican database,\n # encode the password. Otherwise leave it as None and it will be\n # replaced with the value retrieved from the dcmanager database.\n bmc_password = base64.encode_as_text(bmc_password)\n\n volatile_data_install.update({\n 'bmc_address': host.bm_ip,\n 'bmc_username': host.bm_username,\n 'bmc_password': bmc_password,\n 'install_type': install_type,\n 'boot_device': host.boot_device,\n 'rootfs_device': host.rootfs_device,\n })\n\n # Persist the volatile data\n db_api.subcloud_update(\n self.context, strategy_step.subcloud_id,\n data_upgrade=json.dumps(volatile_data_install))\n\n admin_password = str(keyring.get_password('CGCS', 'admin'))\n volatile_data_install.update({'admin_password': admin_password})\n\n return volatile_data_install", "def _add_kube_rootca_update_pods_trustnewca_stage(self):\n from nfv_vim import strategy\n stage = strategy.StrategyStage(\n strategy.STRATEGY_STAGE_NAME.KUBE_ROOTCA_UPDATE_PODS_TRUSTNEWCA)\n stage.add_step(strategy.KubeRootcaUpdatePodsTrustNewcaStep())\n self.apply_phase.add_stage(stage)\n # Proceed to the next stage\n self._add_kube_rootca_update_complete_stage()" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if an array contains an element as 0
def arr_has_0_check(int_arr) -> bool: return 0 in int_arr
[ "def iszero(self):\n return all((v == 0 for v in self.b))", "def is_all_negative(arr):\n for e in arr:\n if e >= 0:\n return False\n return True", "def is_zero_vector(nablaG):\n\n result = True\n for i in range(len(nablaG)):\n if not((isinstance(nablaG[i], numbers.Number)) and (nablaG[i] == 0)):\n result = False\n return result\n return result", "def is_there_zero(map:list) -> bool:\n for row in map:\n if 0 in row:\n return True\n return False", "def zero(self):\n for row in range(self._height): \n for col in range(self._width):\n if (self._val[row][col] == 0):\n return True\n return False", "def is_zero(self):\n return self.one() == self.zero()", "def nonz(self, arr: list):\n for i in range(len(arr)):\n if arr[i] == 0:\n continue\n else:\n return arr[i]", "def isZero(X:cpuByte)->bool:\r\n for position in range (cpuByte._size-1):\r\n if X._state[position]:\r\n return False # we've found a single bit where X deviates from 0\r\n return True", "def _check_shape_contain_zero(shp):\n if isinstance(shp, int):\n return shp == 0\n return F.shape_mul(shp) == 0", "def is_zero(self):\n return self == self.number_field().ideal(0)", "def isZeroPoly(p):\n\tif len(p) > 1:\n\t\treturn False\n\telse:\n\t\treturn p[0] == 0", "def _ensure_non_zero(values: np.ndarray) -> np.ndarray:\n if (values == 0).any():\n values = np.nextafter(values, np.inf)\n return values", "def nonzero_values(x):\n return x[x != 0]", "def err_vals_all_zero(output_hdul):\n\n result = np.all(output_hdul[\"ERR\"].data == 0)\n return result", "def is_zero(self):\n if not self.monomials and not self.coeffs:\n return True\n else:\n return False", "def test_zero_lists():\n arr = [0, 0, 0]\n check_sum_of_four(arr, arr, arr, arr) == len(arr) ** 4", "def isSkipZeroValues(self) -> bool:\n ...", "def _is_scalar_or_zero_d_array(val):\n return (\n isinstance(val, (np.ndarray, cp.ndarray)) and val.ndim == 0\n ) or is_scalar(val)", "def float_not_in_array(x, array):\r\n return np.logical_not(np.any(abs(array - x) < 1e-10))" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Instructions displayed to the user per the recipients file.
def recitals_recipients(self): print("Loading recipient data") print("Important, you must have the following header convention (names can be anything) " "with the corresponding data to use this program:") print('Email To | CC (Can be blank) | Subject | Body | Attachment path with Extension') print('Use a comma "," to separate more than one To, CC, or Attachments') print("Alternatively, copy and paste the direct file path with file name. " "\nExample: C:Users\\Dummy sheet.xlsx\nThen paste it here.")
[ "def recitals_sender(self):\n print(\"Loading the sender data.\")\n print(\"Please provide the file path for the following on the 2nd row: \")\n print(\"SMTP server | SMTP Port | Your_Email | Your_Password \"\n \"(Leave blank if not needed) | optional: Signature path in .html format.\")\n print('Please ask your IT department if needed.')", "def emailcmd(self, connection, data):\r\n if data[2] not in self.usernames:\r\n connection.send(b\"Recipient Name Not Recognized: \" + str(data[2]))\r\n else:\r\n #append email contnets to accounts dictionary value with key being the recipient\r\n #email values logged in form of [sender, subject, message, date/time]\r\n self.accounts[data[2]].append([self.un, data[3], data[4], time.strftime(\"%c\")])\r\n self.update_accounts()\r\n connection.send(b\"OK: Email Sent\")", "def show_subject_email(self):\n showme(\"%s %s : %s\" % \\\n (SUBJECT, self.subject_info.reference[REF_EMAIL_ADDRESS][REF_NAME]\\\n .lower(), self.get_subject_email()))", "def comment_notifier(sender, **kwargs):\n body = kwargs['instance'].name + \", comento\" + \": \" + kwargs['instance'].comment\n send_mail(\"Nuevo Comentario en Sitio ADDAC\", body, 'no-reply@addac.org.ni', ['byroncorrales@gmail.com','antorcha@addac.org.ni'])", "def email_registration_info(player_id):\r\n\temail_dir = 'bracket/emails/' # directory where all txt & html email templates are located\r\n\r\n\tplayer = User.objects.get(id=player_id)\r\n\r\n\t# context elements for email\r\n\tc = {\r\n\t\t'first_name': player.first_name,\r\n\t\t'full_name': player.full_name,\r\n\t\t'num_entries': player.num_entries,\r\n\t\t'mult_entry_type': player.mult_entry_type,\r\n\t\t'target_email': player.email,\r\n\t}\r\n\r\n\tsubject = 'NCAA Spreadpool registration for {} successfully processed!'.format(player.full_name)\r\n\tmsg_plain = render_to_string(email_dir + 'register_info.txt', c)\r\n\tmsg_html = render_to_string(email_dir + 'register_info.html', c)\r\n\r\n\t# print (c)\r\n\tsend_mail(subject, msg_plain, settings.DEFAULT_FROM_EMAIL, [player.email], html_message=msg_html)\r\n\tstoreMessage(player, subject, msg_plain)\r\n\treturn", "def MailPlot(self,recipient_list): \n \n with open(recipient_list) as f:\n Lines = f.readlines()\n b=''\n for line in Lines: \n a=line.strip()\n if(b != ''):\n b = b +','+a\n else:\n b = a\n\n subject = ' LCWA speedtest for '+ datetime.datetime.today().strftime('%Y-%m-%d')\n\n \n \n message = ' this is the daily Raspberry PI report, \\n blue is download green upload, \\n \\\n \\n \\n'\n\n file = self.PA.pdf \n \n sa = SFM.MyMail(file,b,subject, message)\n from pathlib import Path\n home = str(Path.home()) \n \n sa.send_email_pdf_figs(home+'/private/LCWA/andifile')", "async def to_do(self):\n\t\tto_do = \"```Here is your current to do list:\\n\\n\"\n\n\t\tfile = open(\"to_do.txt\", \"r\")\n\t\tlines = file.readlines()\n\n\t\tcounter = 0\n\t\tfor _ in range(len(lines)):\n\t\t\tto_do+=\"%s\\n\" % (lines[counter])\n\t\t\tcounter += 1\n\t\tto_do+=\"```\"\n\t\tawait self.bot.say(to_do)", "def contactus(self):\r\n\r\n\t\ttkMessageBox.showinfo(\"Contact Us\", \"Mohd Ejaz Siddiqui - mejaz_siddiqui@optum.com\\n Vaibhav Rawat - vaibhav_rawat@optum.com\")", "def sendMailToProprio():", "def email(donor_name, amount):\n header = \"\\nDear {:} {:}\".format(*donor_name)\n body = \"\\nThank you so much for your generous donation of $ {:.2f}.\"\n print(header, body.format(amount))", "def adminEmails():", "def addContactInfo(self, *args):\n print(self, args)", "def new_suggestion_mail(sender, **kwargs):\n instance = kwargs.pop(\"instance\")\n plaintext = get_template('suggestions/email.txt')\n html = get_template('suggestions/email.html')\n\n subject = \"Suggestion from %s\" % instance.name\n d = Context(dict(object=instance, subject=subject))\n text_content = plaintext.render(d)\n html_content = html.render(d)\n mail_admins(\"Suggestion from: %s\" % instance.name, text_content,\n html_message = html_content)", "async def address(self, ctx):\n await ctx.send('{} Send Coins to: `{}`'.format(ctx.author.mention, self.grlc.get_user_address(ctx.author.id)))", "def format_email(self,giver_receiver):\n host = \"localhost\"\n subject = \"Gift Selection\"\n from_address = EMAIL_USERNAME + \"@gmail.com\"\n to_address = giver_receiver.giver_email\n text = (\"Name selections for your gift shuffle. You (%s) are giving presents to %s.\") % \\\n (giver_receiver.giver,\n ','.join(str(r) for r in giver_receiver.receiver))\n if DEBUG: print to_address\n mail.send_mail(sender=from_address,\n to=to_address,\n subject=subject,\n body=text)", "def form_text(self):\n return [_( 'As well as software, we also provide real people '\n 'on hand to offer all the advice and support you '\n 'need. No automated telephone lines - just a '\n 'dedicated team of people who know the products inside out.'),\n _('Please complete the form below. We\\'ll be in touch shortly.')\n ]", "def Email(i: dict) -> str:\n if 'email' in i.keys():\n out = 'Email: <a href=\"mailto:%s\">%s</a>' % (i['email'], i['email'])\n else:\n out = \"Email: Not Available\\n\\n\"\n return \"<p>\" + out + \"</p>\"", "def print_thank_you(self, donor, write_to_file=0):\n notes_text = \"Dear {},\\nThank you very much for your recent donation\" \\\n \" to XYZ Charity for an amount of {}. \\n\" \\\n \"The funds raised will go towards X, Y and Z. Thank You\" \\\n \"again for your kindness.\\nSincerely,\\nThe Team\\n\". \\\n format(donor, self.donor_dict[donor].total_donation_amt())\n if not write_to_file:\n print(notes_text)\n return notes_text", "def printInfo(self):\r\n\r\n about = \"Student name is {0}, {1}, and {2} is taking {3}.\".format(\r\n self.lastName, self.firstName, self.pronoun, len(self._courseList))\r\n\r\n print(about)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Instructions displayed to the user per the sender file.
def recitals_sender(self): print("Loading the sender data.") print("Please provide the file path for the following on the 2nd row: ") print("SMTP server | SMTP Port | Your_Email | Your_Password " "(Leave blank if not needed) | optional: Signature path in .html format.") print('Please ask your IT department if needed.')
[ "def inform(msg: str):\n # Dynamic user update messages\n print(\" %-80s\" % msg, end=\"\\r\", flush=True)", "def display_text(self):\n\n print(\"\\n\" * 100)\n print(\"Help MacGyver (M) to escape !\\n\")\n print(\"Controls:\\n\")\n print(\" Z\")\n print(\"Q S D\\n\")\n print(\"Pick up all the items (I) and reach the Guardian (G).\")\n print(\"If you try to escape without all the items, you will lose!\\n\")\n print(f\"Inventory: {str(self.game.player.inventory)}/3 items\\n\")", "def send_welcome_messages(self):\n\n msg = f\"Welcome to the Internet Relay Network {self.nickname}!{self.nickname}@{self.address}\"\n self.send_code(\"001\", self.nickname, msg)\n\n msg = f\"Your host is {self.server_mem.ipv6_address}, running version {self.server_mem.server_name}\"\n self.send_code(\"002\", self.nickname, msg)\n\n msg = f\"This server was created in 2000 - no wait, that's the protocol. The server was made 20 years after everyone stopped using IRC.\"\n self.send_code(\"003\", self.nickname, msg)\n\n msg = f\"{self.server_mem.server_name} v{self.server_mem.server_version}\"\n self.send_code(\"004\", self.nickname, msg)", "def infoheader():\n clear()\n print(\"=^.^= WEBCAT =^.^=\")\n print(\"-\"*50)\n print(\"->> Target: %s\" %(options.target))\n print(\"-\"*50)", "def info(msg):\n message(msg, flag='i')", "def welcome_user():\r\n print(welcome_msg)\r\n print()\r\n print(info_msg)\r\n print()\r\n print(instructions)", "def show_msg_on_startup(self):\n print(\" \")\n print(\" ██████╗ ███████╗████████╗████████╗███████╗██████╗ ███████╗██╗███████╗ \") \n print(\" ██╔══██╗██╔════╝╚══██╔══╝╚══██╔══╝██╔════╝██╔══██╗██╔════╝██║██╔════╝ \")\n print(\" ██████╔╝█████╗ ██║ ██║ █████╗ ██████╔╝███████╗██║███████╗ \")\n print(\" ██╔══██╗██╔══╝ ██║ ██║ ██╔══╝ ██╔══██╗╚════██║██║╚════██║ \")\n print(\" ██████╔╝███████╗ ██║ ██║ ███████╗██║ ██║███████║██║███████║ \")\n print(\" ╚═════╝ ╚══════╝ ╚═╝ ╚═╝ ╚══════╝╚═╝ ╚═╝╚══════╝╚═╝╚══════╝ \")\n print(\" \")\n print(\" ===================================================================== \")\n print(\" \")\n print(\" DISCLAIMER: \")\n print(\" BetterSIS, this software, controls SIS in the background and tries to \")\n print(\" provide modern features \")\n print(\" (such as command history, suggestions and autocompletion) \")\n print(\" and small improvements to SIS itself. (like the simulate improvement) \")\n print(\" > SIS is a tool for synthesis and optimization of sequential circuits \")\n print(\" \")\n print(\" I'm not affiliated with the SIS developers in any way. \")\n print(\" You can read more about SIS here: \")\n print(\" https://jackhack96.github.io/logic-synthesis/sis.html \")\n print(\" \")\n print(\" ===================================================================== \")\n print(\" \")\n print(\" BetterSIS version: {}\".format(__version__) )\n print(\" BetterSIS repository: https://github.com/mario33881/bettersis \")\n print(\" Siswrapper version: {}\".format(siswrapper.__version__) )\n print(\" Running in the background: \", self.sis.res[\"stdout\"] )", "def print_greeting():\n print(\n \"\\nHi there! \\nI can help you figure out the notes of a scale or mode of your choice!\"\n )", "def show_instructions(self, event):\n self.controller.show_frame(TkInstructions)", "async def info(self, ctx):\r\n await ctx.send(f'A simple python Discord bot scripted by Midge.\\n'\r\n f'<https://github.com/MidgeOnGithub/discord-bot>')", "def help_chuck(self):\n print_say(\"Tell a joke about Chuck Norris\", self)", "def arrivalMessage(self):\n #self.__printDescription()\n s = \"Arriving in the port of \" + self.getName() + \"....\"\n printNow('='*len(s) + '\\n' + s + '\\n' + '='*len(s))\n printNow(self.getPortDescription() + '\\n')\n self.printNeighboringPorts()\n printNow(\"\")", "def _format_tell(self, packet):\r\n return _(\"{c%(sender)s@%(origin)s{n {wpages (over IMC):{n %(msg)s\") % {\"sender\": packet.sender,\r\n \"origin\": packet.origin,\r\n \"msg\": packet.optional_data.get('text', 'ERROR: No text provided.')}", "def greet_user(self):\n print(\"Greetings \" + self.f_name.title() + \" \" + self.l_name.title() + \" we hope you enjoy your stay with us!\")", "def help_show_inbox():\n get_show_inbox_parser().print_help()", "def display_help_about():\n showinfo(\"Help about.\", \"Password checker version 1.1\")", "def notify(self, title, message, icon_data=None):\n \n print \"[\" + title + \"]\"\n print message\n print", "def show_text(self):\n\t\topen_file = open(self.file_name, 'r')\n\t\tprint()\n\t\tprint('================================')\n\t\tprint(self.file_name)\n\t\tprint('================================')\n\t\tprint()\n\t\tprint(open_file.read())", "def alert():\n showinfo(\"A propos\", \"Jeu crée par Sanjeevan et Enrick\\n\\nProjet M1106 - Année 2019/2020\")" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If the sizes of disk offerings are not configurable and there are no disk offerings with the requested size, an exception should be thrown.
def test_create_volume_no_noncustomized_offering_with_size(self): location = self.driver.list_locations()[0] self.assertRaises( LibcloudError, self.driver.create_volume, 'vol-0', location, 11)
[ "def showErrorDiskSize(self):\n ButtonChoiceWindow(self.__screen, ERROR_DISK_SIZE.localize(),\n ERROR_DISK_SIZE_MSG.localize(),\n buttons=[(OK.localize(), 'ok')],\n width=50)", "def __check_size__(self, size):\n # size must be an integer, otherwise raise a TypeError exception\n if type(size) != int:\n raise TypeError(\"size must be an integer\")\n # if size is less than 0, raise a ValueError\n if size < 0:\n raise ValueError(\"size must be >= 0\")", "def test_isc_utils_size_spec_failing(self):\n test_data = [\n '-1',\n '2 giga',\n '3Kb',\n '4kb',\n '1min',\n 'limitless',\n 'unlimit',\n 'defaulted',\n 'defaults',\n ]\n result = size_spec.runTests(test_data, failureTests=True)\n self.assertTrue(result[0])", "def __checkForDiskSpace( dpath, size ):\n dsize = (getDiskSpace(dpath)-1)*1024*1024\n maxStorageSizeBytes = 1024*1024*1024\n return ( min(dsize, maxStorageSizeBytes) > size )", "def validate_volume_size(size):\n if size is None:\n raise exception.VolumeSizeNotSpecified()\n max_size = CONF.max_accepted_volume_size\n if int(size) > max_size:\n msg = (\"Volume 'size' cannot exceed maximum \"\n \"of %d Gb, %s cannot be accepted.\"\n % (max_size, size))\n raise exception.VolumeQuotaExceeded(msg)", "def check_storage_config(self):\n\n if get_root_disk_size() < constants.MINIMUM_ROOT_DISK_SIZE:\n print(textwrap.fill(\n \"Warning: Root Disk %s size is less than %d GiB. \"\n \"Please consult the Software Installation Guide \"\n \"for details.\" %\n (self.rootfs_node, constants.MINIMUM_ROOT_DISK_SIZE), 80))\n print('')", "def list_sizes(location=None):", "def set_ephemeral_storage_request(self, size) -> 'Container':\n self._validate_size_string(size)\n return self.add_resource_request('ephemeral-storage', size)", "def _validate_size(self, object_size):\n def make_error(name, value):\n ver = (\"?versionId=\"+self._version_id) if self._version_id else \"\"\n return ValueError(\n f\"Source {self._bucket_name}/{self._object_name}{ver}: \"\n f\"{name} {value} is beyond object size {object_size}\"\n )\n\n if self._offset is not None and self._offset >= object_size:\n raise make_error(\"offset\", self._offset)\n if self._length is not None:\n if self._length > object_size:\n raise make_error(\"length\", self._length)\n offset = self._offset or 0\n if offset+self.length > object_size:\n raise make_error(\"compose size\", offset+self._length)", "def test_created_server_disk_size(self):\n remote_client = self.server_behaviors.get_remote_instance_client(\n self.server, config=self.servers_config, key=self.key.private_key)\n disk_size = remote_client.get_disk_size(\n self.servers_config.instance_disk_path)\n self.assertEqual(disk_size, self.resized_flavor.disk,\n msg=\"Expected disk to be {0} GB, was {1} GB\".format(\n self.resized_flavor.disk, disk_size))", "def test_isc_utils_size_spec_passing(self):\n test_data = [\n 'unlimited',\n 'default',\n '1',\n '0',\n '100',\n '1K',\n '2k',\n '3M',\n '4m',\n '5G',\n '6g',\n ]\n result = size_spec.runTests(test_data, failureTests=False)\n self.assertTrue(result[0])", "def disk_check():\n disk_usage = psutil.disk_usage(\"/\").percent # \n if disk_usage > 80:\n subject = \"Error - Available disk space is less than 20%\"\n message = email.generate_error_report(subject)\n emails.send(message)", "def _get_sizes(self) -> int:\n pass", "def test_get_size_opt(self):\n section = util.my_name()\n fpath = __file__\n obj = CrawlConfig.CrawlConfig()\n obj.add_section(section)\n obj.filename = fpath\n self.assertRaisesMsg(CrawlConfig.NoOptionError,\n \"No option 'foobar' in section: '%s' in %s\" %\n (section, fpath),\n obj.get_size,\n section,\n \"foobar\")", "def list_sizes(self, location=None):\r\n raise NotImplementedError(\r\n 'list_sizes not implemented for this driver')", "def test_get_disk_capacity(self):\n self.assertEqual(\"536870912\",\n self.helper.get_disk_capacity(self.blank_vmdk))\n\n self.assertEqual(\"1073741824\",\n self.helper.get_disk_capacity(self.input_vmdk))", "def test_partition_sizes(self):\n assert self.state.partition_sizes == (3, 4, 5, 6, 7, 8, 9)", "def test_quotaUnlimited(self):\n home = yield self.homeUnderTest()\n allowed = home.quotaAllowedBytes()\n self.assertIdentical(allowed, None)\n yield self.test_createAttachment()", "def test_get_disk_capacity_not_available(self):\n # Haven't found a way yet to make qemu-img actually fail here\n # without returning a non-zero RC and triggering a HelperError,\n # so we'll have to fake it\n self.fake_output = \"qemu-img info: unsupported command\"\n self.assertRaises(RuntimeError, self.helper.get_disk_capacity,\n \"/foo/bar\")" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
S1, S2, Target are the windowed dataframe Counts the number of samples for each class label and generates the data distribution plot and saves to the provided directory
def plot_training_data_distribution_multi_source(s1, s2, target, activity_list, save_dir): unique, counts = np.unique(target, return_counts=True) target_dict = dict(zip(unique, counts)) target_samples = np.fromiter(target_dict.values(), dtype=float).astype(int) unique, counts = np.unique(s1, return_counts=True) s1_dict = dict(zip(unique, counts)) s1_samples = np.fromiter(s1_dict.values(), dtype=float).astype(int) unique, counts = np.unique(s2, return_counts=True) s2_dict = dict(zip(unique, counts)) s2_samples = np.fromiter(s2_dict.values(), dtype=float).astype(int) n_groups = len(activity_list) plt.figure(figsize=(12,8)) index = np.arange(n_groups) bar_width = 0.25 opacity = 0.8 rects1 = plt.bar(index, s1_samples, bar_width, alpha=opacity, color='b', label='Source1') rects2 = plt.bar(index + bar_width, s2_samples, bar_width, alpha=opacity, color='g', label='Source2') rects3 = plt.bar(index + 2*bar_width, target_samples, bar_width, alpha=opacity, color='m',label='Target') plt.xlabel('Activity', fontsize=14) plt.ylabel('Window Number', fontsize=14) plt.title('Window Distribution', fontsize=10) plt.xticks(index + bar_width, activity_list, rotation = 45) plt.legend() plt.legend(fontsize=10) plt.tight_layout() plt.savefig(save_dir+"Activity Distribution.png") plt.show()
[ "def display_class_distributions(labels_path='labels', class_map):\n labels_path = labels_path if labels_path.endswith('/') else labels_path + '/'\n \n txt_labels = sorted(glob(f'{labels_path}*.txt'))\n labels_df = pd.concat((pd.read_csv(file, sep=\" \", header=None) for file in txt_labels if os.path.getsize(file) > 0), ignore_index=True)\n\n plotdata = labels_df.loc[:,0].value_counts().sort_index()\n\n plotdata.index = class_map\n print(plotdata)\n plotdata.plot(kind=\"barh\" )", "def create_distribution_plots(self):\n for checkpoint, epoch in tqdm(zip(self.checkpoint, self.epoch), total=len(self.epoch),\n desc=\"Creating Weight and Bias Distribution Plots\"):\n num_plots = len(checkpoint.keys())\n num_rows = int(np.ceil(num_plots / 2.0))\n\n sns.set_style('darkgrid')\n fig, axs = plt.subplots(num_rows, 2, figsize=(8, num_rows * 3))\n\n for key, ax in zip(checkpoint.keys(), axs.reshape(-1)):\n sns.distplot(checkpoint[key], ax=ax)\n ax.set_xlabel('Weight Value' if 'weight' in key else 'Bias Value')\n ax.set_ylabel('Frequency')\n ax.set_title(' '.join(key.split('.')).title())\n plt.suptitle(f'Weight and Bias Distribution - Epoch {epoch}', fontsize=16)\n plt.tight_layout()\n plt.subplots_adjust(top=0.88)\n plt.savefig(f'{WeightDistribution.TEMP_PLOTS_FOLDER}/epoch_{epoch}.png')\n plt.close()", "def plot_all(self):\n files = [f for f in listdir(self.count_path) if isfile(join(self.count_path, f))]\n try:\n mkdir(self.plots_path)\n except:\n print('plots directory already exists')\n for file_name in files:\n with open(join(self.count_path, file_name), 'rb') as f:\n counts = pickle.load(f)\n file_name = file_name[:-4]\n try:\n mkdir(join(self.plots_path, file_name))\n except:\n print('plots ' + file_name + ' directory already exists')\n counts['w_b/w'] = np.nan_to_num((self.get_marginal_counts(counts['f(w_b)']) / self.get_marginal_counts(counts['f(w)'])))\n counts['b_b/b'] = np.nan_to_num((self.get_marginal_counts(counts['f(b_b)']) / self.get_marginal_counts(counts['f(b)'])))\n self.plot_nodes_over_time(counts, file_name)\n self.plot_edges_over_time(counts, file_name)\n self.plot_f_w_over_time(counts, file_name)\n self.plot_bichromatic_fraction_diff_over_time(counts, file_name)\n self.plot_f_b_over_time(counts, file_name)\n self.plot_f_w_f_b_ratios_over_time(counts, file_name)\n self.plot_f_w_f_b_separately_over_time(counts, file_name)\n self.plot_marginal_w_b_over_time(counts, file_name)\n self.plot_marginal_bichromatic_fraction_diff_over_time(counts, file_name)", "def _print_per_target_comparison(self, results_filename, label):\n sns.set_context('talk')\n sns.set_style(\"white\")\n plt.figure(figsize=(15, 11))\n examples = ['1.4', '2.4', '3.8', '4.1', '5.2']\n for key in examples:\n plt.plot(list(range(1, 101)), (np.asarray(self._matches_by_sent[key]) * 100)[:100], label=key)\n plt.legend(title='SDG Target', bbox_to_anchor=(1.1, 1.2), loc=1, borderaxespad=10)\n plt.title('Percent Matches Vs. Number of Sentences by Target - ' + label)\n plt.xlabel('Number of Sentences')\n plt.ylabel('Percent Matches with Policy Experts')\n plt.yticks(np.arange(0, 105, 10))\n plt.savefig(results_filename + ' - target comparison.jpg')\n plt.close()", "def chart(self):\n\n import matplotlib.pyplot as plt\n import seaborn as sns\n\n empty_cols = [col for col in self.df.columns if self.df[col].isnull().all()]\n self.df.drop(empty_cols, axis=1, inplace=True)\n plt.rcParams.update({'figure.max_open_warning': 0})\n\n # Distribution Chart for each dataframe column\n for col in self.df.columns:\n print('Variable: \\033[34m{}\\033[m'.format(col))\n if self.df.dtypes[col] == \"O\" or self.df.dtypes[col] == \"bool\":\n if len(self.df[col].unique()) > 50:\n print(\n 'Since the variable \\033[32m{}\\033[m has several distinct values, the visualization process through the chart is not a good option.'.format(\n col))\n print()\n print()\n\n else:\n plt.figure(figsize=(9, 4))\n chart = sns.countplot(x=col, data=self.df, order=self.df[col].value_counts().index)\n chart.set(title=\"Frequency Chart - {}\".format(col))\n plt.xticks(rotation=45, horizontalalignment='right')\n plt.grid(color='gray', ls='-.', lw=0.08)\n plt.show()\n print()\n print()\n\n else:\n fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 5))\n\n ax1.hist(self.df[col], label=col, bins='sqrt')\n ax1.set(title=\"Frequency Chart - {}\".format(col), xlabel=col, ylabel=\"count\")\n ax1.grid(color='gray', ls='-.', lw=0.08)\n plt.setp(ax1.get_xticklabels(), rotation=15)\n\n red_diamond = dict(markerfacecolor='r', marker='D')\n ax2.boxplot(self.df[col], flierprops=red_diamond)\n ax2.set(title=\"Box-plot - {}\".format(col), xlabel=col, ylabel=\"values\")\n ax2.grid(color='gray', ls='-.', lw=0.08)\n\n plt.show()\n print()\n print()\n\n # Correlation Plot\n if self.df.shape[1] <= 10:\n plt.figure(figsize=(5, 5))\n elif self.df.shape[1] <= 20:\n plt.figure(figsize=(8, 8))\n else:\n plt.figure(figsize=(20, 20))\n sns.heatmap(self.df.corr(), annot=True, cmap='RdBu')\n plt.title('Correlation Plot - Heatmap', fontsize=14)\n plt.xticks(rotation=15)\n plt.yticks(rotation=15)", "def plot_distribution(self, features_to_plot: list=[], binary_classes_to_plot: list=[]):\n\n if len(self._outcome) > 0:\n if len(binary_classes_to_plot) == 2:\n if (binary_classes_to_plot[0] in self._class_label) & (binary_classes_to_plot[1] in self._class_label):\n if not features_to_plot:\n features_to_plot = self._feature_column\n num_features = []\n for feature in features_to_plot:\n if self._feature_dataframe[feature].dtype != 'object':\n num_features.append(feature)\n cols = 4\n rows = len(num_features) // 4 + 1\n num_features_tuple = tuple(num_features)\n fig = plotly.subplots.make_subplots(rows=rows, cols=cols, subplot_titles=num_features_tuple)\n counter = 0\n for feature in num_features:\n c = counter % 4 + 1\n r = counter // 4 + 1\n fig.append_trace(go.Histogram(\n x=self._feature_outcome_dataframe.loc[self._feature_outcome_dataframe[self._outcome_column] ==\n binary_classes_to_plot[0]][feature],\n opacity=0.75,\n name=str(binary_classes_to_plot[0]),\n marker={'color': 'magenta'},\n showlegend=(counter == 0)),\n r, c)\n fig.append_trace(go.Histogram(\n x=self._feature_outcome_dataframe.loc[self._feature_outcome_dataframe[self._outcome_column] ==\n binary_classes_to_plot[1]][feature],\n opacity=0.75,\n name=str(binary_classes_to_plot[1]),\n marker={'color': 'orange'},\n showlegend=(counter == 0)),\n r, c)\n fig.update_xaxes(title_text='values', title_font={\"size\": 10}, title_standoff=5, row=r, col=c,\n showgrid=False, zeroline=False)\n fig.update_yaxes(title_text='count', title_font={\"size\": 10}, title_standoff=0, row=r, col=c,\n showgrid=False, zeroline=False)\n fig.layout.update(go.Layout(barmode='overlay'))\n counter += 1\n for i in fig['layout']['annotations']:\n i['font'] = dict(size=10)\n fig.update_layout(title_text='Features binary distribution in classes',\n height=rows * 250, width=1250)\n plotly.offline.plot(fig,\n filename=os.path.splitext(self._feature_path)[0] + '_distr.html',\n config={'scrollZoom': True})\n else:\n print('Wrong class label(s).')\n else:\n\n color_scheme = ['magenta', 'orange', 'cyan', 'yellow', 'lime',\n 'blue', 'red', 'green', 'darkviolet', 'saddlebrown']\n if not features_to_plot:\n features_to_plot = self._feature_column\n num_features = []\n for feature in features_to_plot:\n if self._feature_dataframe[feature].dtype != 'object':\n num_features.append(feature)\n cols = 4\n rows = len(num_features) // 4 + 1\n num_features_tuple = tuple(num_features)\n fig = plotly.subplots.make_subplots(rows=rows, cols=cols, subplot_titles=num_features_tuple)\n counter = 0\n for feature in num_features:\n c = counter % 4 + 1\n r = counter // 4 + 1\n counter_colors = 0\n for cl in self._class_label:\n fig.append_trace(go.Histogram(\n x=self._feature_outcome_dataframe.loc[self._feature_outcome_dataframe[self._outcome_column] ==\n cl][feature],\n opacity=0.5,\n name=str(cl),\n marker={'color': color_scheme[counter_colors]},\n showlegend=(counter == 0)),\n r, c)\n counter_colors += 1\n\n fig.update_xaxes(title_text='values', title_font={\"size\": 10}, title_standoff=5, row=r, col=c,\n showgrid=False, zeroline=False)\n fig.update_yaxes(title_text='count', title_font={\"size\": 10}, title_standoff=0, row=r, col=c,\n showgrid=False, zeroline=False)\n fig.layout.update(go.Layout(barmode='overlay'))\n counter += 1\n for i in fig['layout']['annotations']:\n i['font'] = dict(size=10)\n fig.update_layout(title_text='Features binary distribution in classes',\n height=rows * 250, width=1250)\n plotly.offline.plot(fig,\n filename=os.path.splitext(self._feature_path)[0] + '_distr.html',\n config={'scrollZoom': True})\n\n else:\n print('Outcome column should be presented')\n\n return None", "def save_to_pdf(data1, sources1, data2, sources2, dirname=None):\n\n ncolors = np.max(data2) + 1\n prng = np.random.RandomState(1234)\n h = prng.uniform(low=0.0, high=1.0, size=ncolors)\n s = prng.uniform(low=0.2, high=0.7, size=ncolors)\n v = prng.uniform(low=0.5, high=1.0, size=ncolors)\n hsv = np.dstack((h, s, v))\n\n rgb = np.squeeze(colors.hsv_to_rgb(hsv))\n rgb[0] = (0, 0, 0)\n cmap = colors.ListedColormap(rgb)\n\n mk_patch = lambda xy, r, c, lw, fill: patch.Circle(xy=xy,\n radius=r,\n color=c,\n fill=fill,\n lw=lw)\n norm = ImageNormalize(data1,\n stretch=LogStretch(),\n vmin=0,\n vmax=1000)\n # interval=ZScaleInterval())\n\n outname = 'centroid_comparison.pdf'\n print('Total number of sources {}'.format(len(sources1)))\n with PdfPages(outname) as pdf:\n num_pages = int(np.ceil(len(sources1) / 16))\n # num_pages = 20\n start_idx = 0\n for i in range(num_pages):\n start_idx += 8\n sources1_to_plot = sources1[start_idx: start_idx + 8]\n sources2_to_plot = sources2[start_idx: start_idx + 8]\n # Initalize the plot, each axes list will contain 8 plots\n # The plots should be organize by columns, i.e. two plots in\n # the same column correspond to the same image\n fig, axes00, axes10 = mk_grid()\n\n\n\n # i will run from 0 to 15 (i.e. 16 elements)\n for j in range(len(sources1_to_plot)):\n cr1 = sources1_to_plot[j]\n cr2 = sources2_to_plot[j]\n # limits for the first star\n # print(j)\n if j < 4:\n # print(j%4)\n ax1 = axes00[j]\n else:\n # print(j%4)\n ax1 = axes10[j % 4]\n\n cutout_size = 40\n # Limits for the first plot\n xlimits1 = cr1['xcenter'] - cutout_size / 2, \\\n cr1['xcenter'] + cutout_size / 2\n ylimits1 = cr1['ycenter'] - cutout_size / 2, \\\n cr1['ycenter'] + cutout_size / 2\n\n if j < 4:\n # print(j%4 + 4)\n ax2 = axes00[j % 4 + 4]\n else:\n # print(j%4 + 4)\n ax2 = axes10[j % 4 + 4]\n\n # Limits for the second plot\n xlimits2 = cr2['xcenter'] - cutout_size/2, \\\n cr2['xcenter'] + cutout_size/2\n ylimits2 = cr2['ycenter'] - cutout_size/2, \\\n cr2['ycenter'] + cutout_size/2\n\n\n\n im1 = ax1.imshow(data1, norm=norm, cmap='gray', origin='lower')\n im2 = ax2.imshow(data2, cmap=cmap, origin='lower')\n\n # Add axes for color bar to show scale\n divider = make_axes_locatable(ax1)\n cax1 = divider.append_axes(\"right\", size=\"8%\", pad=0.05)\n\n\n cbar = fig.colorbar(im1, cax=cax1)\n n = len(cbar.ax.get_yticklabels())\n\n labels_to_hide = [n-3, n - 2]\n loop = zip(cbar.ax.get_yticklabels(),\n cbar.ax.yaxis.get_major_ticks())\n for i, (label, tick) in enumerate(loop):\n if i in labels_to_hide:\n label.set_visible(False)\n tick.set_visible(False)\n\n cbar.ax.set_yticklabels(cbar.ax.get_yticklabels(),\n rotation=10,\n horizontalalignment='left',\n verticalalignment='center',\n fontsize=5\n )\n cbar.update_ticks()\n\n\n\n flux_max_patch = mk_patch((cr1['xmax'], cr1['ymax']),\n r=0.5,\n c='magenta',\n lw=1,\n fill=True)\n ax1.add_patch(flux_max_patch)\n\n flux_center_patch = mk_patch((cr1['xcenter'], cr1['ycenter']),\n r=0.5,\n c='red',\n lw=1.,\n fill=True)\n ax1.add_patch(flux_center_patch)\n geo_center_patch = mk_patch((cr2['xcenter'], cr2['ycenter']),\n r=0.5,\n c='blue',\n lw=1.,\n fill=True)\n\n ax1.add_patch(geo_center_patch)\n\n current_label_patch = mk_patch((cr2['xcenter'], cr2['ycenter']),\n r=4,\n c='white',\n lw=1.5,\n fill=False)\n\n\n ax2.add_patch(current_label_patch)\n\n ax1.set_title('Red: flux-weight\\n '\n 'Blue: uniform-weight \\n'\n 'Magneta: max value',\n fontsize='medium')\n ax2.set_title('Label', fontsize='medium')\n\n # Set the plot limits for star 1\n ax1.set_xlim(xlimits1[0], xlimits1[1])\n ax1.set_ylim(ylimits1[0], ylimits1[1])\n\n # Set the plot limits for star 2\n ax2.set_xlim(xlimits2[0], xlimits2[1])\n ax2.set_ylim(ylimits2[0], ylimits2[1])\n\n ax1.grid(False)\n ax2.grid(False)\n # add colorbar to outer grid\n\n pdf.savefig(fig)\n plt.close()", "def plot_dist_features(df, features, save=False, path=str):\n\n import matplotlib as mpl\n import matplotlib.cm as cm\n import matplotlib.pyplot as plt\n import seaborn as sns\n\n for i in features:\n fig, axs = plt.subplots(1, figsize=(9,6))\n sns.set(style='white', palette='deep')\n\n x = df[i]\n if i == 'duration_ms':\n x = x/1000\n sns.kdeplot(x, label = 'duration in seconds', shade=True).set_title(\"Distribution of Feature Duration\")\n else:\n sns.kdeplot(x, label = i, shade=True).set_title(\"Distribution of Feature \"+i)\n\n if save:\n filename='distribution_plot_'+i\n fig.savefig(path+filename)\n\n return", "def plot_distributions(data,directory):\n \n # Create dictionary to translate from mag class to wavelength\n mag_to_wv = {'mag_u' : 355.1,'mag_g' : 468.6,'mag_r' : 616.5,'mag_i' : 748.1,\n 'mag_z' : 893.1, 'w1' : 3400,'w2' : 4600,'w3' : 12000,'w4' : 22000}\n wavelength = np.zeros(len(mag_to_wv))\n i = 0\n for element in data.columns:\n if(element == 'class' or element == 'subclass'):\n continue\n wavelength[i] = np.log10(mag_to_wv[element])\n i += 1\n # In this function we only look at galaxies (including quasars)\n data = data.drop(data[data['class']=='STAR'].index)\n \n \n data_G = data[data['class'] == 'GALAXY']\n data_Q = data[data['class'] == 'QSO']\n \n \n colors = ['darkred','r','orange','y','g','b','navy','violet','m']\n colors = colors[0:len(list(data['subclass'].unique()))]\n \n subclasses = list(data['subclass'].unique())\n \n # Start with quasars\n y = np.zeros(len(data_G.columns) - 2) # substract 'class' and 'subclass'\n for subclass in subclasses:\n i = 0\n for element in data_Q.columns:\n if(element == 'class' or element == 'subclass'):\n continue\n y[i] = np.mean(data_Q[data_Q['subclass']==subclass][element])\n i += 1\n \n plt.plot(wavelength,y,label = subclass,markersize=10)\n plt.scatter(wavelength,y,marker='o',s=10)\n plt.xlabel('Logarithmic Wavelength [log(nm)]')\n plt.ylabel('Mean Magnitude')\n plt.title('Photometric Spectra of Quasars')\n plt.legend(loc='lower left')\n plt.grid(True)\n plt.savefig(directory+'spectraQuasarsLog.png',format='png')\n plt.gcf().clear()\n \n # Now galaxies\n for subclass in subclasses:\n i = 0\n for element in data_G.columns:\n if(element == 'class' or element == 'subclass'):\n continue\n y[i] = np.mean(data_G[data_G['subclass']==subclass][element])\n i += 1\n \n plt.plot(wavelength,y,label = subclass,markersize=10)\n plt.scatter(wavelength,y,marker='o',s=10)\n plt.xlabel('Logarithmic Wavelength [log(nm)]')\n plt.ylabel('Mean Magnitude')\n plt.title('Photometric Spectra of Galaxies')\n plt.legend(loc='lower left')\n plt.grid(True)\n plt.savefig(directory+'spectraGalaxiesLog.png',format='png')\n plt.gcf().clear()", "def visualise(folder_path=FOLDER_PATH, origin_class=ORIGIN_CLASS, target_class=TARGET_CLASS):\n\n jsma_path = folder_path + \"jsma_train/jsma_image_\" + str(IMAGE_NUMBER) + \".csv\"\n wjsma_path = folder_path + \"wjsma_train/wjsma_image_\" + str(IMAGE_NUMBER) + \".csv\"\n jsma_probs = probabilities_array(jsma_path, 6)\n wjsma_probs = probabilities_array(wjsma_path, 6)\n\n jsma_target_probs = jsma_probs[target_class::10]\n wjsma_target_probs = wjsma_probs[target_class::10]\n jsma_origin_probs = jsma_probs[origin_class::10]\n wjsma_origin_probs = wjsma_probs[origin_class::10]\n\n plt.plot(jsma_target_probs, label=\"JSMA target\")\n plt.plot(jsma_origin_probs, label=\"JSMA origin\")\n plt.plot(wjsma_target_probs, label=\"WJSMA target\")\n plt.plot(wjsma_origin_probs, label=\"WJSMA origin\")\n\n plt.xlabel('Iterations')\n plt.ylabel('Probabilities')\n\n plt.legend()\n plt.show()", "def _print_per_sdg_comparison(self, results_filename, label):\n sns.set_context('talk')\n sns.set_style(\"white\")\n plt.figure(figsize=(15, 11))\n for key in range(1, 6):\n plt.plot(list(range(1, 101)), (np.asarray(self._avg_sdg_matches_by_sent[key]) * 100)[:100],\n label='SDG ' + str(key))\n plt.plot(list(range(1, 101)), (np.asarray(self._avg_matches_by_sent) * 100)[:100], label='SDG Avg')\n plt.legend(title='SDG', bbox_to_anchor=(1.1, 1.2), loc=1, borderaxespad=10)\n plt.title('Percent Matches Vs. Number of Sentences by SDG - ' + label)\n plt.xlabel('Number of Sentences')\n plt.ylabel('Percent Matches with Policy Experts')\n plt.yticks(np.arange(0, 105, 10))\n plt.savefig(results_filename + ' - SDG comparison.jpg')\n plt.close()", "def create_S1_plot(self, filename = \"s1_plot.pdf\"):\n\n S1_dataframe = pd.DataFrame(self.S1_indices)\n S1_dataframe.index = self.N\n\n cols = list(S1_dataframe.columns)\n\n fig, ax = plt.subplots(figsize=(12, 8))\n\n for col in cols:\n S1_dataframe.reset_index().plot(\n kind=\"scatter\", x=\"index\", y=col, ax=ax, c=\"r\", s=50\n )\n S1_dataframe.reset_index().plot(\n kind=\"line\", x=\"index\", y=col, ax=ax\n )\n plt.legend(loc=\"right\", fontsize=20)\n plt.xlim(min(self.N) - 1, max(self.N) + 1)\n plt.xlabel(\"$log_{10}N$\", fontsize=30)\n plt.ylabel(\"$S_i$\", fontsize=30)\n plt.title(r\"$S_i$ vs $log_{10}N$\", fontsize=30)\n plt.xticks(fontsize=20)\n plt.yticks(fontsize=20)\n plt.ylim(-0.2, 1.0)\n\n plt.savefig(filename)", "def save_output_vs_continuous_label_plot(self):\r\n\r\n for (trial, output_record), (_, label_record) in zip(self.trialwise_output_dict.items(), self.trialwise_continuous_label_dict.items()):\r\n\r\n complete_directory = self.complete_directory_to_save_plot()\r\n\r\n plot_filename = trial\r\n full_plot_filename = os.path.join(complete_directory, plot_filename + \".jpg\")\r\n\r\n # Find the y ranges for subplot with better clarity.\r\n if len(self.emotional_dimension) > 1:\r\n ylim_low, ylim_high = [], []\r\n for emotion in self.emotional_dimension:\r\n ylim_low.append(min(min(output_record[emotion]), min(label_record[emotion])))\r\n ylim_high.append(max(max(output_record[emotion]), max(label_record[emotion])))\r\n ylim_low, ylim_high = min(ylim_low) * 1.15, max(ylim_high) * 1.15\r\n else:\r\n ylim_low, ylim_high = None, None\r\n\r\n self.plot_and_save(full_plot_filename, trial, output_record, label_record, ylim_low, ylim_high)", "def plot_weight_posteriors(names, qm_vals, qs_vals, fname):\n fig = plt.figure(figsize=(12, 6))\n sns.set()\n\n ax = fig.add_subplot(1, 2, 1)\n for c, (n, qm) in enumerate(zip(names, qm_vals)):\n sns.distplot(tf.reshape(qm, shape=[-1]), ax=ax, label=n)\n # sns.histplot(tf.reshape(qm, shape=[-1]), color=color_palette[c], ax=ax, label=n, \n # stat=\"density\", kde=True, binrange=(0, 0.1))\n ax.set_title('weight means')\n ax.set_xlim([-1.5, 1.5])\n ax.legend()\n\n ax = fig.add_subplot(1, 2, 2)\n for c, (n, qs) in enumerate(zip(names, qs_vals)):\n sns.distplot(tf.reshape(qs, shape=[-1]), ax=ax)\n # sns.histplot(tf.reshape(qs, shape=[-1]), color=color_palette[c], ax=ax, label=n, \n # stat=\"density\", kde=True, binrange=(0, 0.1))\n ax.set_title('weight stddevs')\n ax.set_xlim([0, 1.])\n fig.tight_layout()\n ax.grid(True)\n tikzplotlib.save(fname + \".tex\", standalone=True)\n fig.savefig(fname, bbox_inches='tight')\n print(\"image is saved to {}\".format(fname))", "def main(raw_filenames, annotation_filenames, sessions, subjects, sensors, time_offsets):\n raw_data = w_utils.raw_csv_consolidator(raw_filenames, sessions, subjects, sensors)\n annotation_data = s_annotation.annotation_csv_consolidator(annotation_filenames, time_offsets, sessions, subjects, sensors)\n raw_data = s_raw.preprocess_raw(raw_data, annotation_data, by='sensor')\n # index of plot which needs to be regenerated\n regen = [11,19]\n secs = []\n for count in regen:\n try:\n lbound, rbound = w_utils.generate_random_bounds(raw_data, timedelta(minutes=5))\n # count = 4\n # lbound = w_utils.convert_fromstring(\"2012-05-03 12:43:16\", annotation.annotation_tstr_format)\n # rbound = w_utils.convert_fromstring(\"2012-05-03 12:48:16\", annotation.annotation_tstr_format)\n random_raw = s_raw.select_raw_by_ts(raw_data, lbound, rbound, by='sensor')\n random_annotation = s_annotation.select_annotation_by_ts(annotation_data, lbound, rbound, by='sensor')\n s_viewer.get_multisensor_raw_plot(random_raw, labels=random_annotation, subplots=False)\n true_filename = \"../visual_test_data/session\"+str(num_session)+\"/true/true\" + str(count) + '.png'\n pyplot.savefig(true_filename)\n s_viewer.get_multisensor_raw_plot(random_raw, subplots=False)\n test_filename = \"../visual_test_data/session\"+str(num_session)+\"/test/test\" + str(count) + '.png'\n pyplot.savefig(test_filename)\n # count += 1\n secs.append(lbound)\n except IndexError:\n continue\n # print the list of time ranges that is randomly generated \n for s in secs:\n print s", "def perform_eda(model_data):\n #churn and customer age distribution\n for col in ['Churn', 'Customer_Age']:\n plt.figure(figsize=FIG_SIZE)\n model_data[col].hist()\n plt.savefig(r'./images/eda/{}_distribution.png'.format(col.lower()))\n plt.close()\n\n #marital status distribution\n plt.figure(figsize=FIG_SIZE)\n model_data['Marital_Status'].value_counts('normalize').plot(kind='bar')\n plt.savefig(r'./images/eda/marital_status_distribution.png', dpi=300, bbox_inches = \"tight\")\n plt.close()\n\n #total transaction distribution\n plt.figure(figsize=FIG_SIZE)\n sns.distplot(model_data['Total_Trans_Ct'])\n plt.savefig(r'./images/eda/total_transaction_distribution.png', dpi=300, bbox_inches = \"tight\")\n plt.close()\n\n #correlation matrix heatmap\n plt.figure(figsize=FIG_SIZE)\n sns.heatmap(model_data.corr(), annot=False, cmap='Dark2_r', linewidths=2)\n plt.savefig(r'./images/eda/heatmap.png', dpi=300, bbox_inches = \"tight\")\n plt.close()", "def __show_distribution(self, train_data, test_data, valid_data):\r\n num_plots = 2\r\n \r\n if valid_data:\r\n num_plots = 3\r\n plt.figure(figsize=(10, 3))\r\n plt.subplot(1, num_plots, 1)\r\n objects = train_data.keys()\r\n x_pos = np.arange(len(objects))\r\n num_examples = [len(train_data[obj]) for obj in objects]\r\n \r\n plt.bar(x_pos, num_examples, align='center')\r\n plt.xticks(x_pos, objects)\r\n plt.ylabel('Number of examples')\r\n plt.title('Training set distribution')\r\n \r\n plt.subplot(1, num_plots, 2)\r\n objects = test_data.keys()\r\n x_pos = np.arange(len(objects))\r\n num_examples = [len(test_data[obj]) for obj in objects]\r\n \r\n plt.bar(x_pos, num_examples, align='center')\r\n plt.xticks(x_pos, objects)\r\n plt.ylabel('Number of examples')\r\n plt.title('Test set distribution') \r\n \r\n if valid_data:\r\n plt.subplot(1, num_plots, 3)\r\n objects = valid_data.keys()\r\n x_pos = np.arange(len(objects))\r\n num_examples = [len(valid_data[obj]) for obj in objects]\r\n\r\n plt.bar(x_pos, num_examples, align='center')\r\n plt.xticks(x_pos, objects)\r\n plt.ylabel('Number of examples')\r\n plt.title('Validation set distribution')\r\n \r\n plt.tight_layout()\r\n plt.show()", "def load_all_dataset(dir, fs, window_size=5, window_overlab=2):\n\n head=[\"acc_x\",\"acc_y\",\"acc_z\",\"ang_vel_x\",\"ang_vel_y\",\"ang_vel_z\",\"angle_x\",\"angle_y\",\"angle_z\",\"bump_class\"]\n df=pd.read_csv(dir,sep=\",\")\n df.columns=head\n\n label_peaks, _ = sg.find_peaks(\n df[\"bump_class\"].values, distance=200\n )\n\n for peak in label_peaks:\n df[\"bump_class\"].iloc[peak-250:peak+250]=1\n \n X = []\n Y = []\n window_len = window_size * fs\n window_shift_len = (window_size - window_overlab) * fs\n \n # Convert dataframe to samples each one is shifted 2s\n number_samples = int(len(df) / window_shift_len)\n for window_ind in range(number_samples):\n sample_start = int(window_ind * window_shift_len)\n sample_end = int(sample_start + window_len)\n acc_x = df[\"acc_x\"][sample_start:sample_end].values\n acc_y = df[\"acc_y\"][sample_start:sample_end].values\n acc_z = df[\"acc_z\"][sample_start:sample_end].values\n ang_vel_x=df[\"ang_vel_x\"][sample_start:sample_end].values\n ang_vel_y=df[\"ang_vel_y\"][sample_start:sample_end].values\n ang_vel_z=df[\"ang_vel_z\"][sample_start:sample_end].values\n ang_x=df[\"angle_x\"][sample_start:sample_end].values\n ang_y=df[\"angle_y\"][sample_start:sample_end].values\n ang_z=df[\"angle_z\"][sample_start:sample_end].values\n labels = df[\"bump_class\"][sample_start:sample_end].values\n # [acc_x, acc_y, acc_z, ang_vel_x,ang_vel_y,ang_vel_z,ang_x,ang_y,ang_z]\n X.append(np.array([acc_x, acc_y, acc_z,ang_vel_y,ang_y,ang_z]))\n Y.append(np.array([labels]))\n return X, Y", "def create_S2_plot(self, filename = \"s2_plot.pdf\"):\n\n elem = len(self.N) - 1\n\n S2_mat = self.S2_dataframe[elem].to_dict()\n df = pd.DataFrame(S2_mat)\n max_val = max(df.max(axis=0).values)\n var_names = sorted(df.columns)\n\n if len(df.columns) < 10:\n plt.figure(figsize=(12, 12))\n else:\n plt.figure(figsize=(15, 15))\n cmap = sns.diverging_palette(240, 10, n=9)\n g = sns.heatmap(\n df,\n cmap=cmap,\n annot=True,\n xticklabels=var_names,\n yticklabels=var_names,\n annot_kws={\"fontsize\": 10},\n vmax=max_val,\n vmin=-max_val,\n )\n plt.title(\n \"$S_{ij}$ ( $log_{10}N$ = \" + str(self.N[elem]) + \" )\", fontsize=30\n )\n plt.xticks(fontsize=15, rotation=30)\n plt.yticks(fontsize=15, rotation=0)\n\n plt.savefig(filename)", "def generate_histogram(avg_histogram_df, pass_counter, chip_name, metric_str, histo_metric, histo_dir):\n\n\n bin_array = np.array(avg_histogram_df.index, dtype='float')\n\n smooth_histo_df = avg_histogram_df.filter(regex='rollingmean').rename(columns=lambda x: x[:-12])\n\n sdm_histo_df = avg_histogram_df.filter(regex='sdm').rename(columns=lambda x: x[:-4])\n\n # smooth_max = np.max(np.max(smooth_histo_df))\n # sdm_max = np.max(np.max(sdm_histo_df))\n # if np.isnan(sdm_max):\n # sdm_max = 0\n # histo_max\n\n min_cont, max_cont = metric_str.split(\"-\")\n\n if pass_counter < 10:\n passes_to_show = 1\n else:\n passes_to_show = 2\n pass_counter // 10\n line_settings = dict(alpha=0.75, elinewidth = 0.5)\n vhf_colormap = get_vhf_colormap()\n\n\n\n for i in range(1, pass_counter+1, passes_to_show):\n sns.set_style('darkgrid')\n fig = plt.figure(figsize=(8,6))\n ax = fig.add_subplot(111)\n # ax.set_xscale('log')\n sns.set(style='ticks')\n\n c = 0\n max_list = []\n for col in smooth_histo_df:\n max_list.append(np.max(smooth_histo_df[col]))\n histo_max = np.ceil(max(max_list))\n splitcol = col.split(\"_\")\n if len(splitcol) == 2:\n spot_type, pass_num = splitcol\n else:\n spot_type, pass_num = splitcol[::2]\n pass_num = int(pass_num)\n if pass_num == i:\n ax.errorbar(x=bin_array,\n y=smooth_histo_df[col],\n yerr=sdm_histo_df[col],\n color = vhf_colormap[c],\n label = None,\n lw = 0,\n **line_settings\n )\n ax.step(x=bin_array,\n y=smooth_histo_df[col],\n color = vhf_colormap[c],\n label = spot_type,\n lw = 1,\n where= 'mid',\n alpha=0.75\n )\n c += 1\n\n ax.axhline(y=0, ls='dotted', c='k', alpha=0.75)\n ax.axvline(x=float(min_cont), ls='dashed', c='k', alpha=0.8)\n\n plt.legend(loc = 'best', fontsize = 10)\n\n plt.ylabel(\"Frequency (kparticles/mm\" + r'$^2$'+\")\", size = 14)\n plt.xlabel(\"{} (%)\".format(histo_metric), size = 14)\n\n if histo_max < 0.5:\n ysteps = 0.1\n else:\n ysteps = round(histo_max/10,1)\n\n plt.yticks(np.arange(0, histo_max, ysteps), size = 12)\n\n xlabels = np.append(bin_array, int(max_cont))[::(len(bin_array) // 10)]\n plt.xticks(xlabels, size = 12, rotation = 90)\n\n plt.title(chip_name+\" Pass \"+str(i)+\" Average Histograms\")\n\n figname = ('{}_combohisto_pass_{}_{}_{}.png'.format(chip_name,i,histo_metric,metric_str))\n plt.savefig('{}/{}'.format(histo_dir,figname), bbox_inches = 'tight', dpi = 300)\n print(\"File generated: {}\".format(figname))\n plt.clf()" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates accuracy for a given level of perturbation (=epsilon) based on the dataset provided through dataset_name. Applies gaussian perturbation to the samples in the dataset according to the given level of perturbation. The accuracy is calculated from the perturbed dataset and the resulting predictions of the model.
def get_accuracy(gauss_eps, *args): modelf, data, dataset_name = args gauss_eps = gauss_eps perturb_generator = PerturbationGenerator( dataset_name=dataset_name, gaussian_noise_eps=[gauss_eps] ) logits, labels = modelf.logits( data, perturb_generator, "general_gaussian_noise", range(1), from_cache=False, to_cache=False, save_to_file=False ) pred_classes = np.argmax(logits, axis=1) labels = np.argmax(labels, axis=1) matches = np.equal(pred_classes, labels) accuracy = np.sum(matches) / np.shape(matches)[0] print("Accuracy: %s Epsilon: %s" % (accuracy, gauss_eps)) return accuracy
[ "def accuracy(tree, dataset):\n\n right = 0\n for data in dataset:\n res = tree.predict(data)\n if abs(res - data[-1]) <= 0.5:\n right += 1\n return right / dataset[:, 0].size", "def estimate_epsilons(\n modelf,\n data,\n dataset_name,\n n_classes,\n number_perturbation_levels,\n accuracy_deviation_acceptable,\n accuracy_deviation_acceptable_last_step,\n gauss_eps_start=0.05,\n opt_delta_gauss_eps=0.5):\n\n start_time = time.time()\n # calculate target accuracies\n max_acc = get_accuracy(0.0, modelf, data, dataset_name)\n min_acc = 1 / n_classes\n perturbation_levels = range(number_perturbation_levels)\n target_accuracy_list = []\n for perturbation_level in perturbation_levels:\n target_accuracy_list.append(max_acc - (max_acc - min_acc) \\\n * perturbation_level / (len(perturbation_levels) - 1))\n # estimate gauss epsilons with regard to target accuracies\n print(\"Start estimating gaussian epsilons with regard to target \\\n accuracies: \", target_accuracy_list)\n epsilons = []\n for i, target_accuracy in enumerate(target_accuracy_list):\n print(\"Step_%s - Target Accuracy: %s\" % (str(i), str(target_accuracy)))\n if i == 0:\n epsilons.append(0.0)\n else:\n if i == 1:\n x0 = gauss_eps_start\n else:\n x0 = epsilons[i - 1]\n\n if i == len(target_accuracy_list) - 1:\n tolerance = max_acc * accuracy_deviation_acceptable_last_step\n else:\n tolerance = max_acc * accuracy_deviation_acceptable\n\n x = minimize_neldermead(\n optmize_accuracy,\n x0,\n args=(target_accuracy, modelf, data, dataset_name),\n tol_abs=tolerance,\n nonzdelt=opt_delta_gauss_eps,\n callback=None,\n maxiter=None, maxfev=None, disp=False,\n return_all=False, initial_simplex=None,\n xatol=1e-4, fatol=1e-4, adaptive=False,\n )\n epsilons.append(x[0])\n time_needed = time.time() - start_time\n print(\"Finished estimating gaussian epsilons!!\")\n print(\"Time needed: \", time_needed)\n return epsilons", "def average_precision_score(y, y_pred):\n pass", "def average_precision(predictions):\n precisions = []\n correct_predictions = 0\n for i in range(len(predictions)):\n if predictions[i]:\n correct_predictions += 1\n precisions.append(correct_predictions / (i + 1))\n if precisions:\n #return sum(precisions) / len(precisions)\n return mean(precisions)\n return 0", "def calculate_group_predictions(self, individual_predictions):", "def calc_accuracy(node, dataset):\r\n accuracy = 0.0\r\n Sum = 0\r\n ###########################################################################\r\n # TODO: Implement the function. #\r\n ###########################################################################\r\n for row in dataset:\r\n #get actual prediction\r\n actual_predic = row[-1]\r\n predicted_val = predict(node, row)\r\n if(actual_predic == predicted_val):\r\n Sum+=1\r\n ###########################################################################\r\n # END OF YOUR CODE #\r\n ###########################################################################\r\n accuracy = (Sum/len(dataset))*100\r\n \r\n return accuracy", "def calc_accuracy(model_dict, test_dict):\n\n \"\"\" Calculate the result \"\"\"\n\n all_prob = []\n result_dict = {}\n test_label = []\n predict_label = []\n\n for t_name, t in test_dict.items():\n result = []\n index = []\n hype_dict = {}\n sum = len(t)\n counter = 0\n letter = t_name\n for p in t:\n test_label.append(t_name)\n high_score = -100000\n for m_name, m in model_dict.items():\n score = m.score([p])\n if score > high_score:\n high_score = score\n hypo = m_name\n result.append(hypo)\n predict_label.append(hypo)\n if hypo == letter:\n counter += 1\n all_letters = list(set(result))\n for l in all_letters:\n hype_dict[l] = result.count(l)\n\n sorted_hype_dict = sorted(hype_dict.iteritems(), key=operator.itemgetter(1))\n sorted_hype_dict.reverse()\n\n if sum != 0:\n prob = float(counter)/sum\n print str(letter) + \"(\"+ str(counter) + \"/\" + str(sum) + \")\" + \" ==> Accuracy: \" + str(prob),\n print sorted_hype_dict\n all_prob.append(prob)\n result_dict[letter] = np.array([counter, sum])\n\n \"\"\" Print the average accuracy\"\"\"\n\n all_prob = np.array(all_prob)\n print \"Average accuracy is: \" + str(all_prob.mean())\n print \"=================================\"\n\n return all_prob, result_dict, test_label, predict_label", "def test_accuracy(model, dataset):\n # Normalize dataset\n (_, _), (x_test, y_test) = dataset.load_data()\n x_test = x_test.astype('float32')\n x_test /= 255\n # Test accuracy\n correct = 0\n for i in range(len(y_test)):\n correct += 1 if y_test[i] == np.argmax(model.predict(x_test[[i]])) else 0\n return 100 * (correct / len(y_test))", "def average_perceptron_accuracy(train_feature_matrix, val_feature_matrix, train_labels, val_labels, T):\r\n # Your code here\r\n theta, theta_0 = average_perceptron(train_feature_matrix, train_labels, T)\r\n\r\n train_predictions = classify(train_feature_matrix, theta, theta_0)\r\n val_predictions = classify(val_feature_matrix, theta, theta_0)\r\n\r\n train_accuracy = accuracy(train_predictions, train_labels)\r\n validation_accuracy = accuracy(val_predictions, val_labels)\r\n\r\n return (train_accuracy, validation_accuracy)", "def ensemble_models_and_evaluate_accuracy(train_probas, val_probas, test_probas, y_train, y_val, y_test):\n train_eq_ensemble_pred = equally_ensemble_results(train_probas)\n val_eq_ensemble_pred = equally_ensemble_results(val_probas)\n test_eq_ensemble_pred = equally_ensemble_results(test_probas)\n\n print(\"Equally weighted ensemble:\")\n print(\"--------------------------\")\n print(\"Train accuracy: \", accuracy_score(y_train, train_eq_ensemble_pred))\n print(\"Validation accuracy: \", accuracy_score(y_val, val_eq_ensemble_pred))\n print(\"Test accuracy: \", accuracy_score(y_test, test_eq_ensemble_pred))\n\n np.save(os.path.join('model', 'train_eq_ensemble_pred'), train_eq_ensemble_pred)\n np.save(os.path.join('model', 'val_eq_ensemble_pred'), val_eq_ensemble_pred)\n np.save(os.path.join('model', 'test_eq_ensemble_pred'), test_eq_ensemble_pred)\n\n confidence_train = calculate_confidence_val(train_probas, y_train)\n confidence_val = calculate_confidence_val(val_probas, y_val)\n confidence_test = calculate_confidence_val(test_probas, y_test)\n\n train_w_ensemble_pred = weighted_ensemble_results(train_probas, confidence_train)\n val_w_ensemble_pred = weighted_ensemble_results(val_probas, confidence_val)\n test_w_ensemble_pred = weighted_ensemble_results(test_probas, confidence_test)\n\n print(\"Weighted ensemble:\")\n print(\"--------------------------\")\n print(\"Train accuracy: \", accuracy_score(y_train, train_w_ensemble_pred))\n print(\"Validation accuracy: \", accuracy_score(y_val, val_w_ensemble_pred))\n print(\"Test accuracy: \", accuracy_score(y_test, test_w_ensemble_pred))\n\n np.save(os.path.join('model', 'train_w_ensemble_pred.npy'), train_w_ensemble_pred)\n np.save(os.path.join('model', 'val_w_ensemble_pred.npy'), val_w_ensemble_pred)\n np.save(os.path.join('model', 'test_w_ensemble_pred.npy'), test_w_ensemble_pred)", "def test_trial_ensemble(trial_name, classifier):\n models_dir = args.saved_models + '/{0}/best_models/'.format(trial_name)\n best_models = [m[2] for m in os.walk(models_dir)][0]\n classifiers = []\n for m in best_models:\n new_classifier = classifier\n new_classifier.load_checkpoint(models_dir+m)\n classifiers.append(new_classifier)\n \n total_correct = 0\n for i, x in enumerate(classifier.test_di):\n label = x[4] if classifier.classification_type == \"simple\" else x[5]\n predictions = [c.classify(x) for c in classifiers]\n avg_prediction = np.mean(predictions, 0)\n class_prediction = avg_prediction.argmax(0)\n if class_prediction == label:\n total_correct += 1\n \n return total_correct / len(classifier.test_di)", "def ACE(data, norm = \"shuffle_r\", threshold = \"median\", shuffles = 1, ea = \"mean\"):\n temp = []\n N = 0\n for e in data:\n e = func.binarize(e, threshold)\n E = func.entropy(func.map2(e))\n if norm == \"shuffle_p\":\n for sh in range(shuffles):\n for i in range(len(e)):\n random.shuffle(e[i])\n w = func.entropy(func.map2(e))\n N = w if w > N else N\n elif norm == \"max\":\n N = -2**len(e) * 1/2**len(e) * np.log(1/2**len(e)) / np.log(2.0)\n elif norm == \"shuffle_r\":\n for sh in range(shuffles):\n w = func.entropy(func.map2(np.random.randint(0, 2, np.shape(e))))\n N = w if w > N else N\n else:\n sys.exit(\"'{}' is not a valid argument for 'norm'\".format(norm))\n temp.append(E / float(N))\n try:\n return eval(\"np.{}(temp)\".format(ea)) if not ea == \"raw\" else temp\n except AttributeError:\n print(\"'{}' is an invalid value for 'ea', using 'mean'.\".format(ea))\n return np.mean(temp)", "def accuracy(self,X_test,Y_test): #returns the accuracy of the model for a given testing data set(X_test,Y_test), both should be provided\n predictions=self.predict(X_test)\n temp=np.abs(Y_test-predictions)\n temp=float(np.squeeze(np.sum(temp)))\n m=X_test.shape[1]\n accuracy=100-((temp/m)*100)\n return accuracy", "def calculate_uncertainty(self):\n\n tree_predition_df = pd.DataFrame(index=self.features_df.index)\n\n # Use each tree in the forest to generate the individual tree prediction\n for nth_tree, tree in enumerate(self.machina.estimators_):\n tree_predition_df.loc[:, 'Tree {}'.format(nth_tree)] = tree.predict(self.features)\n\n # print(tree_predition_df.var(axis=1))\n self.uncertainty = np.sqrt(self.tau**2 * tree_predition_df.var(axis=1).values)", "def compute_accuracy(testset, map_classifier):\n size = testset.shape[0]\n correct = 0.0\n for i in range(size):\n prediction = map_classifier.predict(testset[i])\n real_value = testset[i][-1]\n if prediction == real_value:\n correct += 1\n return (correct / size) * 100", "def test_dataset(dataset):\n\n ### SETUP #########################################################################################################\n\n reserve = 0.33\n\n # initial and only shuffle - makes each call to test_dataset unique\n # np.random.shuffle(dataset.winedata)\n\n # analyze before and after standardization\n analyze(dataset.winedata)\n dataset.standardize()\n analyze(dataset.winedata)\n\n dataset.split(reserve)\n\n examples_train, labels_train = extract(dataset.data_train)\n examples_test, labels_test = extract(dataset.data_test)\n\n\n ### PLOT RMSE AND MAD AS FUNCTION OF REGULARIZATION TERM ##########################################################\n best_reg = regress_and_find_errors(dataset, examples_train, labels_train, examples_test, labels_test)\n\n\n ### PLOT REC: ACCURACY VS TOLERANCE ###############################################################################\n one_reg = 1\n mid_reg = 5000\n high_reg = 20000\n low_reg = 0.0001\n\n weights = []\n weights.append(regress_ridge(examples_train, labels_train, one_reg))\n # w.append(regress_ridge(examples_train, labels_train, high_reg))\n # w.append(regress_ridge(examples_train, labels_train, low_reg))\n weights.append(regress_ridge(examples_train, labels_train, mid_reg))\n\n rec_curve(dataset, weights, examples_test, labels_test)\n\n\n ### EVALUATING FEATURE IMPORTANCE #################################################################################\n evaluate_feature_importance(dataset)\n\n \n return", "def test_accuracy(datafile, network, dicts):\n w2i, i2w, t2i, i2t, l2i, i2l = create_dictionaries(dicts)\n\n #open de dataset.\n with open(datafile, 'r', newline='\\n') as file_in:\n reader = csv.reader(file_in, delimiter=\"\\t\", quotechar=None)\n \n #add root to the sentences. \n sentence_in = [[w2i[\"root\"],t2i[\"ROOT\" ]]]\n sentence = [\"root\" ] \n \n #define variables\n tree = [] \n AUS = 0\n LAS = 0\n word_count = 0\n amount_of_sentences = 0\n \n for row in reader:\n if amount_of_sentences != 500:\n if len(row ) > 1 and row[0] != '8.1': \n word = row[1]\n sentence.append(word)\n if word in w2i:\n index_word = w2i[word]\n else:\n #word is unknown\n word = \"<unk>\"\n index_word = w2i[word]\n \n postag = row[3]\n index_postag = t2i[postag]\n # from this sentence the predicited tree is predicted\n sentence_in.append([index_word, index_postag])\n\n # This will be the golden tree\n tree.append([word, row[6], row[7]])\n\n if len(row) == 0: \n # then the end of a line is found.\n predicted_tree = dependency_parser(sentence_in, sentence, network, dicts)\n word_count += len(predicted_tree)\n amount_good_arcs, good_arcs_labels = compare(predicted_tree, tree, len(tree))\n AUS += amount_good_arcs\n LAS += good_arcs_labels\n \n # set varibles empty and ready for analyzing new sentence.\n sentence_in = [[w2i[\"root\" ],t2i[\"ROOT\" ]]]\n tree = []\n sentence = [\"root\"]\n amount_of_sentences += 1\n else:\n per_AUS = AUS/word_count *100\n per_LAS = LAS/word_count *100\n\n return per_AUS, per_LAS", "def fit(self):\n self.average_label_df = self.train_data.groupby(by='k_size')[self.label_col_name].mean().rename('prediction')\n if self.binary_classification:\n self.average_label_df[self.average_label_df > 0] = 1\n self.average_label_df[self.average_label_df < 0] = -1\n print(f'average_label_df is: {self.average_label_df}')", "def test_correctness_with_detections(self):\n expectedAgs = 0.96425\n singleValue = self.estimator.estimate(detection=self.detection1)\n batchValue = self.estimator.estimateBatch(detections=[self.detection1])[0]\n assert type(singleValue) == type(batchValue)\n assert isinstance(singleValue, float)\n assert abs(expectedAgs - singleValue) < EXPECTED_PRECISION" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Optimizes levels of gaussian perturbation (=epsilons) based on a list of target accuracies. The target accuracies are calcualted with interpolation between min & max. The data is perturbed with gaussian noise at a certain level (=epsilon). The model's accuracy for the perturbed data is calculated. The levels of perturbation are iteratively optimized with nelder mead.
def estimate_epsilons( modelf, data, dataset_name, n_classes, number_perturbation_levels, accuracy_deviation_acceptable, accuracy_deviation_acceptable_last_step, gauss_eps_start=0.05, opt_delta_gauss_eps=0.5): start_time = time.time() # calculate target accuracies max_acc = get_accuracy(0.0, modelf, data, dataset_name) min_acc = 1 / n_classes perturbation_levels = range(number_perturbation_levels) target_accuracy_list = [] for perturbation_level in perturbation_levels: target_accuracy_list.append(max_acc - (max_acc - min_acc) \ * perturbation_level / (len(perturbation_levels) - 1)) # estimate gauss epsilons with regard to target accuracies print("Start estimating gaussian epsilons with regard to target \ accuracies: ", target_accuracy_list) epsilons = [] for i, target_accuracy in enumerate(target_accuracy_list): print("Step_%s - Target Accuracy: %s" % (str(i), str(target_accuracy))) if i == 0: epsilons.append(0.0) else: if i == 1: x0 = gauss_eps_start else: x0 = epsilons[i - 1] if i == len(target_accuracy_list) - 1: tolerance = max_acc * accuracy_deviation_acceptable_last_step else: tolerance = max_acc * accuracy_deviation_acceptable x = minimize_neldermead( optmize_accuracy, x0, args=(target_accuracy, modelf, data, dataset_name), tol_abs=tolerance, nonzdelt=opt_delta_gauss_eps, callback=None, maxiter=None, maxfev=None, disp=False, return_all=False, initial_simplex=None, xatol=1e-4, fatol=1e-4, adaptive=False, ) epsilons.append(x[0]) time_needed = time.time() - start_time print("Finished estimating gaussian epsilons!!") print("Time needed: ", time_needed) return epsilons
[ "def fit(self):\n # if self.verbose == 1:\n # print ('The list of all perturbation with its probability: \\n')\n # for perturb in range(len(self.p_list)):\n # print('%s perturbation with probability of: %s \\n' %(self.p_list[perturb], self.p_prob[perturb]))\n #p_current, error_vec_current ,error_vec_normal_current = self.minus_log_prob_neuron(self.neuron) # log probability of the current neuron\n p_current, error_vec_current ,error_vec_normal_current = self.kl_distance(self.neuron) # log probability of the current neuron\n acc = 0\n for i in range(self.ite):\n if(self.verbose ==1):\n #p_current, er , error_vec_normal_current = self.minus_log_prob_neuron(self.neuron)\n p_current, er , error_vec_normal_current = self.kl_distance(self.neuron)\n #print('feature of current is: \\n %s' %(self.neuron.features)+ '\\n')\n print('\\n and its probability is: %s' %p_current)\n per = self.select_proposal() # MCMC index\n p_sym, details = self.do_MCMC(per)\n #p_proposal, error_vec_proposal, error_vec_normal_proposal = self.minus_log_prob_neuron(self.neuron)\n p_proposal, error_vec_proposal, error_vec_normal_proposal = self.kl_distance(self.neuron)\n if(self.verbose ==1):\n #print('feature of proposal is: \\n %s' %(self.neuron.features))\n print('\\n and its probability is: %s' %p_proposal)\n a = min(1, p_sym * np.exp(p_current - p_proposal)) # Metropolis choice, notice that the values are minus log probability\n B = self.accept_proposal(a) # the boolean of acceptance\n if(B):\n p_current = p_proposal\n error_vec_current = error_vec_proposal\n error_vec_normal_current = error_vec_normal_proposal\n self.trend[:,i] = error_vec_proposal\n self.trend_normal[:,i] = error_vec_normal_proposal\n acc = acc + 1\n else:\n self.undo_MCMC(per, details)\n self.trend[:,i] = error_vec_current\n self.trend_normal[:,i] = error_vec_normal_current\n if len(self.neuron.nodes_list) == self.neuron.n_soma:\n self.neuron = self.initial_neuron(int(self.n_node/self.initial_seg),self.initial_seg)\n #p_current, error_vec_current, error_vec_normal_current = self.minus_log_prob_neuron(self.neuron)\n p_current, error_vec_current, error_vec_normal_current = self.kl_distance(self.neuron)\n if(self.verbose ==1):\n print ('\\n')\n print('Selected perturbation = ' + per)\n print('the p of acceptance was %s and it was %s that it`s been accepted.'%(a,B))\n print ('\\n')\n if(np.remainder(i,100)==0):\n self.evo.append(deepcopy(self.neuron))\n self.neuron.set_nodes_values()\n print acc", "def run_EM(self, tol, min_probability=0.05, debug_plot=False, hard_assignment=False,rand_seed=None,\n use_templates=None,max_iter=500,min_iter=10):\n # if use_templates is None:\n # self.reset_templates()\n # if rand_seed is not None:\n # self.seed = rand_seed\n # np.random.seed(self.seed)\n # self.init_affinities_templates('unif_rand')\n # else:\n # self.templates = use_templates.copy()\n # self.reset_templates()\n\n\n self.hard_assignment = hard_assignment\n self.min_probability = np.float32(min_probability)\n loglikelihood = -np.inf\n # First E step plus likelihood computation\n new_loglikelihood = self._compute_loglikelihoods()\n\n # if debug_plot:\n # plw = ag.plot.PlottingWindow(subplots=(1, self.num_mix), figsize=(self.num_mix*3, 3))\n loglikelihood = new_loglikelihood/(1-tol) - 10\n self.iterations = 0\n print ((loglikelihood - new_loglikelihood)/loglikelihood)\n while (np.abs((loglikelihood - new_loglikelihood)/loglikelihood) > tol and self.iterations < max_iter) or self.iterations < min_iter:\n assert np.abs(self.data_mat).sum() > 0\n print(\"Iteration {0}: loglikelihood {1}, num_affinities bigger than 20 {2}\".format(self.iterations, loglikelihood,\n (np.bincount(np.argmax(self.affinities,1))>=20).sum()))\n loglikelihood = new_loglikelihood\n # M-step\n self.M_step()\n # E-step\n new_loglikelihood = self._compute_loglikelihoods()\n\n self.iterations += 1\n\n #if debug_plot and not self._plot(plw):\n # raise ag.AbortException\n\n print \"Likelihood is %f after %d iterations\" % (loglikelihood,self.iterations)\n self.set_templates()", "def exp(args):\n\n ####################################################################################################################\n #t_0 = time.time()\n # load the parameters from the arguments \n [x_init, i, seed, diff, h, f] = args\n sys_dim = len(x_init)\n\n\n # number of ensemble members generated from the initial condition\n N_ens = 100\n\n # time at which we compute an analysis of the ensemble in continuous time\n tanl = .01\n\n # the number of analyses we produce of the forward ensemble\n nanl = 2000\n\n # fourier truncation\n p = 1\n \n # static parameters based on fourier truncation\n RHO = rho(p)\n ALPHA = alpha(p)\n\n # set the storage for the ensemble means\n t_mean = np.zeros([sys_dim, nanl])\n e_mean = np.zeros([sys_dim, nanl])\n r_mean = np.zeros([sys_dim, nanl])\n a_mean = np.zeros([sys_dim, nanl])\n\n # set the storage for the spread of ensembles\n t_spread = np.zeros([nanl])\n e_spread = np.zeros([nanl])\n r_spread = np.zeros([nanl])\n a_spread = np.zeros([nanl])\n \n # we copy the initial condition into N_ens copies to forward propagate\n X_t_ens = np.tile(x_init, (N_ens, 1))\n X_e_ens = np.tile(x_init, (N_ens, 1))\n X_r_ens = np.tile(x_init, (N_ens, 1))\n X_a_ens = np.tile(x_init, (N_ens, 1))\n\n # set random seed for the same ensemble noise processes\n np.random.seed(seed)\n\n # for each forward time when we analyze the ensemble\n for j in range(nanl):\n #looping over the ensemble member\n for k in range(N_ens):\n # integrate until the next sample time\n for l in range(int(tanl/h)):\n # generate the weiner process over the interval at a fine discretization\n xi = np.random.standard_normal([sys_dim, int(round(tanl / 0.001))])\n\n # then compute the brownian motion a the current step size, re-normalized to unit variance\n tmp = np.zeros([sys_dim, int(round(tanl / h))])\n for m in range(int(round(tanl / h ))):\n tmp[:, m] = np.sum(xi[:, m * int(h / 0.001) : (m + 1) * int(h / 0.001)], axis=1) / np.sqrt(h / 0.001)\n \n # reset xi to be the Brownian path as generated by the finer discretization, normalized to have each component\n # drawn from a normal of unit variance\n xi = tmp\n\n\n # recursivley integrating one step forward via second order taylor, EM and RK schemes\n # note that the same weiner process is utilized for each integration scheme\n X_t_ens[k, :] = ty_step_path(X_t_ens[k, :], np.squeeze(xi[:, l]), h, [ALPHA, RHO, p, f, diff])\n X_e_ens[k, :] = em_step_path(X_e_ens[k, :], np.squeeze(xi[:, l]), h, [f, diff])\n X_r_ens[k, :] = rk_step_path(X_r_ens[k, :], np.squeeze(xi[:, l]), h, [f, diff])\n X_a_ens[k, :] = l96_rk4_step(X_r_ens[k, :], h, f)\n \n # make a final perturbation by the same Brownian process all at the end instead, for the ad hoc method\n ipdb.set_trace()\n X_a_ens[k, :] = X_a_ens[k, :] + diff * np.sum(xi * h, axis=1)\n \n ### then produce statistics of the ensemble at the analysis time\n \n # the ensemble mean for each method\n t_mean[:, j] = np.mean(X_t_ens, axis=0)\n e_mean[:, j] = np.mean(X_e_ens, axis=0)\n r_mean[:, j] = np.mean(X_r_ens, axis=0)\n a_mean[:, j] = np.mean(X_a_ens, axis=0)\n\n\t# we compute the spread as in whitaker & louge 98 by the standard deviation of the mean square deviation of the ensemble\n t_spread[j] = np.sqrt( ( 1 / (N_ens - 1) ) * np.sum(np.mean( (np.squeeze(t_mean[:, j]) - X_t_ens)**2, axis=1)))\n e_spread[j] = np.sqrt( ( 1 / (N_ens - 1) ) * np.sum(np.mean( (np.squeeze(e_mean[:, j]) - X_e_ens)**2, axis=1)))\n r_spread[j] = np.sqrt( ( 1 / (N_ens - 1) ) * np.sum(np.mean( (np.squeeze(r_mean[:, j]) - X_r_ens)**2, axis=1)))\n a_spread[j] = np.sqrt( ( 1 / (N_ens - 1) ) * np.sum(np.mean( (np.squeeze(a_mean[:, j]) - X_a_ens)**2, axis=1)))\n\n data = {\n 'e_mean': e_mean, 'e_spread': e_spread, \n 'r_mean': r_mean, 'r_spread': r_spread, \n 't_mean': t_mean, 't_spread': t_spread, \n 'a_mean': a_mean, 'a_spread': a_spread \n }\n \n fname = './data/ensemble_stats/' \\\n 'ensemble_statistics_h_' + str(h).zfill(3) + '_sys_dim_' + str(sys_dim).zfill(2) + '_tanl_' + \\\n str(tanl).zfill(3) + '_diffusion_' + str(diff).zfill(3) + \\\n '_init_con_' + str(i).zfill(6) + '.txt'\n \n f = open(fname, 'wb')\n pickle.dump(data, f)\n f.close()\n #print(time.time() - t_0)\n return i", "def posterior(epsilon, bs_dags, true_dag_dict, iv_means, iv_var, K):\n #read interventional data in\n T= len(bs_dags)\n # Generate observational data\n g = cd.GaussDAG.from_amat(np.asarray(true_dag_dict['A']))\n nsamples_iv = K\n\n ivs = [{target: cd.GaussIntervention(iv_means[target], iv_var) for target in targets} for targets in epsilon]\n y = [g.sample_interventional(iv, nsamples_iv) for iv in ivs] \n\n #convert epsilon to numpy\n logPy = finite.llhood(y, epsilon, bs_dags, (iv_means, iv_var))\n \n weighted_logPy = np.zeros(T)\n for j in range(T):\n weighted_logPy[j] = np.log(bs_dags[j]['w']) + logPy[j]\n \n P2 = np.zeros(T) #this will be the log dist, we'll convert after\n denom = logsumexp(weighted_logPy)\n for j in range(T):\n P2[j] = weighted_logPy[j] - denom\n P2 = np.exp(P2) #currently just have the log dist\n for j in range(T):\n bs_dags[j]['w'] = P2[j]\n return bs_dags", "def run_optimization_step(data:dict, all_supershots: List[List[int]], supershot_collation: List[List[int]], parameters: List[Parameter], max_iters: int=300) -> List[Parameter]:\n\toptimizer = optim.SGD([\n {'params': parameters[0]},\n {'params': parameters[1]},\n {'params': parameters[2]},\n {'params': parameters[3]},\n ], lr=1e-1, momentum=0.9)\n\n\tfor iteration in range(max_iters):\n\t\told_parameters = torch.clone(parameters[0])\n\t\ttotal_score = 0\n\t\ttensor_supershots = get_tensor_supershots(data, all_supershots, parameters)\n\t\t#for elem in tensor_supershots:\n\t\t#\tfor sub_elem in elem:\n\t\t#\t\tsub_elem = Variable(sub_elem.data, requires_grad=True)\n\t\toffset = 0\n\t\tclear_caches()\n\t\tfor supershot_group in supershot_collation:\n\t\t\ttotal_score += get_total_similarity(tensor_supershots[offset: offset + len(supershot_group)], offset)\n\t\t\toffset += len(supershot_group)\n\n\t\t#print('total score: ', total_score)\n\n\t\ttotal_score *= -1\n\t\ttotal_score.backward()\n\t\t#autograd.backward([total_score], [parameters[0], parameters[1], parameters[2], parameters[3]], \n\t\t#\tgrad_tensors=[torch.ones_like(parameters[0]), torch.ones_like(parameters[1]), torch.ones_like(parameters[2]), torch.ones_like(parameters[3])])\n\t\toptimizer.step()\n\t\toptimizer.zero_grad()\n\n\treturn parameters", "def gradient_boosting_mse(X, y, num_iter, max_depth=1, nu=0.1):\n trees = []\n N, _ = X.shape\n y_mean = np.mean(y)\n fm = y_mean\n ### BEGIN SOLUTION\n \n ### END SOLUTION\n return y_mean, trees", "def test_exponential_growth_model_bayesian_d_optimal_design(self):\n num_design_pts = 50\n optimal_design_samples = {10:([0.182],[1.0]),40:([0.048,0.354],[0.981,0.019]),50:([0.038,0.318],[0.973,0.027]),100:([0.019,0.215],[.962,0.038]),200:([0.010,0.134],[0.959,0.041]),300:([0.006,0.084,0.236],[0.957,0.037,0.006]),3000:([0.0006,0.009,0.055,1.000],[0.951,0.039,0.006,0.004])}\n lb2=1\n for ub2 in optimal_design_samples.keys():\n # assuming middle of parameter domain is used to find local design\n design_samples = np.linspace(0,1,num_design_pts)\n design_samples = np.sort(np.unique(np.concatenate(\n [design_samples,optimal_design_samples[ub2][0]])))\n noise_multiplier = None\n\n local_design_factors = \\\n lambda p,x: exponential_growth_model_grad_parameters(p,x).T\n xx2,ww2 = pya.gauss_jacobi_pts_wts_1D(40,0,0)\n xx2 = (xx2+1)/2*(ub2-lb2)+lb2 # transform from [-1,1] to [lb2,ub2]\n parameter_samples = xx2[np.newaxis,:]\n \n opt_problem = AlphabetOptimalDesign(\n 'D',local_design_factors,opts=None)\n \n mu,res = opt_problem.solve_nonlinear_bayesian(\n parameter_samples,design_samples[np.newaxis,:],\n sample_weights=ww2,options={'iprint': 0, 'ftol':1e-14,'disp':True,'tol':1e-12},return_full=True)\n I = np.where(mu>1e-5)[0]\n J =np.nonzero(design_samples==np.array(optimal_design_samples[ub2][0])[:,None])[1]\n mu_paper = np.zeros(design_samples.shape[0]);\n mu_paper[J] = optimal_design_samples[ub2][1]\n # published designs are not optimal for larger values of ub2\n if I.shape==J.shape and np.allclose(I,J):\n assert np.allclose(\n mu[I],optimal_design_samples[ub2][1],rtol=3e-2)\n assert (res.obj_fun(mu)<=res.obj_fun(mu_paper)+1e-6)", "def run_expgrad_classification(estimator, moment):\n X, Y, A = fetch_adult()\n\n expgrad = ExponentiatedGradient(\n estimator,\n constraints=moment)\n expgrad.fit(X, Y, sensitive_features=A)\n\n assert expgrad.n_oracle_calls_ > 1\n assert len(expgrad.predictors_) > 1", "def fit(pdf, prior, parameters, observations, iter=1000, lr=0.1):\n\n for i in range(iter):\n # Define objective function (log-likelihood) to maximize\n prior_ = torch.log(prior(parameters))\n posterior = torch.mean(torch.log(pdf(observations))) + prior_\n\n if np.isnan(posterior.data[0]) or np.isnan(prior_.data[0]):\n return\n\n # Determine gradients\n posterior.backward()\n\n # Update parameters with gradient descent\n for param in parameters:\n param.data.add_(lr * param.grad.data)\n param.grad.data.zero_()", "def entropy_fit(self, n_moments, tol=1e-10, verbose=False):\n # sum of probs constraint\n n_constraints = n_moments + 1\n\n # don't want to mess up the object...\n xs = self.xs.copy()\n p = self.agg_density.copy()\n # more aggressively de-fuzz\n p = np.where(abs(p) < 1e-16, 0, p)\n p = p / np.sum(p)\n p1 = p.copy()\n\n mtargets = np.zeros(n_constraints)\n for i in range(n_constraints):\n mtargets[i] = np.sum(p)\n p *= xs\n\n parm1 = np.zeros(n_constraints)\n x = np.array([xs ** i for i in range(n_constraints)])\n\n probs = np.exp(-x.T @ parm1)\n machieved = x @ probs\n der1 = -(x * probs) @ x.T\n\n er = 1\n iters = 0\n while er > tol:\n iters += 1\n try:\n parm1 = parm1 - inv(der1) @ (machieved - mtargets)\n except np.linalg.LinAlgError:\n print('Singluar matrix')\n print(der1)\n return None\n probs = np.exp(-x.T @ parm1)\n machieved = x @ probs\n der1 = -(x * probs) @ x.T\n er = (machieved - mtargets).dot(machieved - mtargets)\n if verbose:\n print(f'Error: {er}\\nParameter {parm1}')\n ans = pd.DataFrame(dict(xs=xs, agg=p1, fit=probs))\n ans = ans.set_index('xs')\n return dict(params=parm1, machieved=machieved, mtargets=mtargets, ans_df=ans)", "def fit(self):\n ln_l_all_array = [] #array of all log likelihoods\n ln_l_max = float(\"-inf\") #keep track of the maximum likelihood\n cp_parameter_array = None #parameters with the maximum likelihood\n #for multiple initial values\n for i in range(self.n_initial):\n print(\"initial value\", i)\n print(\"gradient descent\")\n super().fit() #regular gradient descent\n #copy the log likelihood\n for ln_l in self.ln_l_array:\n ln_l_all_array.append(ln_l)\n #check for convergence in the log likelihood\n ln_l = ln_l_all_array[len(ln_l_all_array)-1]\n if ln_l > ln_l_max:\n #the log likelihood is bigger, copy the parmeters\n ln_l_max = ln_l\n self.ln_l_max_index = len(ln_l_all_array)-1\n cp_parameter_array = self.copy_parameter()\n #do stochastic gradient descent to get a different initial value\n if i < self.n_initial-1:\n print(\"stochastic gradient descent\")\n #track when stochastic gradient descent was done for this entry\n #of ln_l_array\n self.ln_l_stochastic_index.append(len(ln_l_all_array))\n for j in range(self.n_stochastic_step):\n print(\"step\", j)\n self.m_stochastic_step()\n self.update_all_cp_parameters()\n ln_l_all_array.append(self.get_em_objective())\n #track when gradient descent was done\n #the E step right after this in super().fit() is considered part\n #of stochastic gradient descent\n self.ln_l_stochastic_index.append(len(ln_l_all_array)+1)\n else:\n self.ln_l_stochastic_index.append(len(ln_l_all_array))\n #copy results to the member variable\n self.ln_l_array = ln_l_all_array\n self.set_parameter(cp_parameter_array)\n self.e_step()", "def testBatch(self):\n pp = 100\n dd = 10\n tol = 1.0e-3\n\n data = np.zeros((pp,dd),dtype = float)\n fn = np.zeros((pp),dtype = float)\n\n f = open(\"tests/data/gp_exp_covar_data.sav\",\"r\");\n ff = f.readlines()\n f.close()\n for i in range(100):\n s = ff[i].split()\n for j in range(dd):\n data[i][j] = float(s[j])\n fn[i] = float(s[dd])\n\n xx=gp.SquaredExpCovariogramD();\n xx.setEllSquared(2.0)\n\n try:\n gg = gp.GaussianProcessD(data,fn,xx)\n except pex.LsstCppException, e:\n print e.args[0].what()\n\n gg.setLambda(0.0032)\n\n f = open(\"tests/data/gp_batch_solutions.sav\",\"r\")\n ff = f.readlines()\n f.close()\n\n ntest = len(ff)\n mushld = np.zeros((ntest),dtype = float)\n varshld = np.zeros((ntest),dtype = float)\n mu = np.zeros((ntest),dtype = float)\n var = np.zeros((ntest),dtype = float)\n\n queries = np.zeros((ntest,dd),dtype = float)\n\n for i in range(ntest):\n s = ff[i].split()\n for j in range(dd):\n queries[i][j] = float(s[j])\n mushld[i] = float(s[dd])\n varshld[i] = float(s[dd + 1])\n\n #test with variance calculation\n gg.batchInterpolate(mu,var,queries)\n\n worstMuErr = -1.0\n worstVarErr = -1.0\n for i in range(ntest):\n err = mu[i]-mushld[i]\n if mushld[i] != 0.0:\n err = err/mushld[i]\n if err < 0.0:\n err = -1.0 * err\n if err > worstMuErr:\n worstMuErr = err\n\n err = var[i]-varshld[i]\n if varshld[i] != 0.0:\n err = err/varshld[i]\n if err < 0.0:\n err = -1.0 * err\n if err > worstVarErr:\n worstVarErr = err\n\n #test without variance interpolation\n #continue keeping track of worstMuErr\n gg.batchInterpolate(mu,queries)\n for i in range(ntest):\n err = mu[i]-mushld[i]\n if mushld[i] != 0.0:\n err = err/mushld[i]\n if err < 0.0:\n err = -1.0 * err\n if err > worstMuErr:\n worstMuErr = err\n\n self.assertTrue(worstMuErr < tol)\n self.assertTrue(worstVarErr < tol)\n\n print \"\\nThe errors for batch interpolation\\n\"\n print \"worst mu error \",worstMuErr\n print \"worst sig2 error \",worstVarErr", "def setup(dm, key='%s', data_list=None):\n vars = {}\n\n\n param_type = 'all-cause_mortality'\n data = [d for d in data_list if d['data_type'] == 'all-cause mortality data']\n m_all_cause = dm.mortality(key % param_type, data)\n\n covariate_dict = dm.get_covariates()\n X_region, X_study = rate_model.regional_covariates(key, covariate_dict)\n est_mesh = dm.get_estimate_age_mesh()\n\n # update age_weights on non-incidence/prevalence data to reflect\n # prior prevalence distribution, if available\n prior_prev = dm.get_mcmc('emp_prior_mean', key % 'prevalence')\n if len(prior_prev) > 0:\n for d in data:\n if d['data_type'].startswith('incidence') or d['data_type'].startswith('prevalence'):\n continue\n age_indices = indices_for_range(est_mesh, d['age_start'], d['age_end'])\n d['age_weights'] = prior_prev[age_indices]\n d['age_weights'] /= sum(d['age_weights']) # age weights must sum to 1 (optimization of inner loop removed check on this)\n \n\n for param_type in ['incidence', 'remission', 'excess-mortality']:\n data = [d for d in data_list if d['data_type'] == '%s data' % param_type]\n\n lower_bound_data = []\n # TODO: include lower bound data when appropriate\n \n prior_dict = dm.get_empirical_prior(param_type)\n if prior_dict == {}:\n prior_dict.update(alpha=np.zeros(len(X_region)),\n beta=np.zeros(len(X_study)),\n gamma=-5*np.ones(len(est_mesh)),\n sigma_alpha=[1.],\n sigma_beta=[1.],\n sigma_gamma=[10.],\n # delta is filled in from the global prior dict in neg_binom setup\n )\n vars[key % param_type] = rate_model.setup(dm, key % param_type, data,\n emp_prior=prior_dict, lower_bound_data=lower_bound_data)\n\n i = vars[key % 'incidence']['rate_stoch']\n r = vars[key % 'remission']['rate_stoch']\n f = vars[key % 'excess-mortality']['rate_stoch']\n\n # Initial population with condition\n logit_C_0 = mc.Normal('logit_%s' % (key % 'C_0'), -5., 10.**-2, value=-5.)\n @mc.deterministic(name=key % 'C_0')\n def C_0(logit_C_0=logit_C_0):\n return mc.invlogit(logit_C_0)\n \n # Initial population without condition\n @mc.deterministic(name=key % 'S_0')\n def SC_0(C_0=C_0):\n return np.array([1. - C_0, C_0]).ravel()\n vars[key % 'bins'] = {'initial': [SC_0, C_0, logit_C_0]}\n \n \n # iterative solution to difference equations to obtain bin sizes for all ages\n import scipy.linalg\n @mc.deterministic(name=key % 'bins')\n def SCpm(SC_0=SC_0, i=i, r=r, f=f, m_all_cause=m_all_cause, age_mesh=dm.get_param_age_mesh()):\n SC = np.zeros([2, len(age_mesh)])\n p = np.zeros(len(age_mesh))\n m = np.zeros(len(age_mesh))\n \n SC[:,0] = SC_0\n p[0] = SC_0[1] / (SC_0[0] + SC_0[1])\n m[0] = trim(m_all_cause[age_mesh[0]] - f[age_mesh[0]] * p[0], .1*m_all_cause[age_mesh[0]], 1-NEARLY_ZERO)\n\n for ii, a in enumerate(age_mesh[:-1]):\n A = np.array([[-i[a]-m[ii], r[a] ],\n [ i[a] , -r[a]-m[ii]-f[a]]]) * (age_mesh[ii+1] - age_mesh[ii])\n\n SC[:,ii+1] = np.dot(scipy.linalg.expm(A), SC[:,ii])\n \n p[ii+1] = trim(SC[1,ii+1] / (SC[0,ii+1] + SC[1,ii+1]), NEARLY_ZERO, 1-NEARLY_ZERO)\n m[ii+1] = trim(m_all_cause[age_mesh[ii+1]] - f[age_mesh[ii+1]] * p[ii+1], .1*m_all_cause[age_mesh[ii+1]], 1-NEARLY_ZERO)\n\n SCpm = np.zeros([4, len(age_mesh)])\n SCpm[0:2,:] = SC\n SCpm[2,:] = p\n SCpm[3,:] = m\n return SCpm\n\n vars[key % 'bins']['age > 0'] = [SCpm]\n\n \n # prevalence = # with condition / (# with condition + # without)\n @mc.deterministic(name=key % 'p')\n def p(SCpm=SCpm, param_mesh=dm.get_param_age_mesh(), est_mesh=dm.get_estimate_age_mesh()):\n return dismod3.utils.interpolate(param_mesh, SCpm[2,:], est_mesh)\n data = [d for d in data_list if d['data_type'] == 'prevalence data']\n prior_dict = dm.get_empirical_prior('prevalence')\n if prior_dict == {}:\n prior_dict.update(alpha=np.zeros(len(X_region)),\n beta=np.zeros(len(X_study)),\n gamma=-5*np.ones(len(est_mesh)),\n sigma_alpha=[1.],\n sigma_beta=[1.],\n sigma_gamma=[10.],\n # delta is filled in from the global prior dict in neg_binom setup\n )\n \n vars[key % 'prevalence'] = rate_model.setup(dm, key % 'prevalence', data, p, emp_prior=prior_dict)\n p = vars[key % 'prevalence']['rate_stoch'] # replace perfectly consistent p with version including level-bound priors\n \n # make a blank prior dict, to avoid weirdness\n blank_prior_dict = dict(alpha=np.zeros(len(X_region)),\n beta=np.zeros(len(X_study)),\n gamma=-5*np.ones(len(est_mesh)),\n sigma_alpha=[1.],\n sigma_beta=[1.],\n sigma_gamma=[10.],\n delta=100.,\n sigma_delta=1.\n )\n # cause-specific-mortality is a lower bound on p*f\n @mc.deterministic(name=key % 'pf')\n def pf(p=p, f=f):\n return (p+NEARLY_ZERO)*f\n # TODO: add a 'with-condition population mortality rate date' type\n # data = [d for d in data_list if d['data_type'] == 'with-condition population mortality rate data']\n data = []\n lower_bound_data = [d for d in data_list if d['data_type'] == 'cause-specific mortality data']\n vars[key % 'prevalence_x_excess-mortality'] = rate_model.setup(dm, key % 'pf', rate_stoch=pf, data_list=data, lower_bound_data=lower_bound_data, emp_prior=blank_prior_dict)\n \n\n # m = m_all_cause - f * p\n @mc.deterministic(name=key % 'm')\n def m(SCpm=SCpm, param_mesh=dm.get_param_age_mesh(), est_mesh=dm.get_estimate_age_mesh()):\n return dismod3.utils.interpolate(param_mesh, SCpm[3,:], est_mesh)\n vars[key % 'm'] = m\n\n # m_with = m + f\n @mc.deterministic(name=key % 'm_with')\n def m_with(m=m, f=f):\n return m + f\n data = [d for d in data_list if d['data_type'] == 'mortality data']\n # TODO: test this\n #prior_dict = dm.get_empirical_prior('excess-mortality') # TODO: make separate prior for with-condition mortality\n vars[key % 'mortality'] = rate_model.setup(dm, key % 'm_with', data, m_with, emp_prior=blank_prior_dict)\n\n # mortality rate ratio = mortality with condition / mortality without\n @mc.deterministic(name=key % 'RR')\n def RR(m=m, m_with=m_with):\n return m_with / (m + .0001)\n data = [d for d in data_list if d['data_type'] == 'relative-risk data']\n vars[key % 'relative-risk'] = log_normal_model.setup(dm, key % 'relative-risk', data, RR)\n \n # standardized mortality rate ratio = mortality with condition / all-cause mortality\n @mc.deterministic(name=key % 'SMR')\n def SMR(m_with=m_with, m_all_cause=m_all_cause):\n return m_with / (m_all_cause + .0001)\n data = [d for d in data_list if d['data_type'] == 'smr data']\n vars[key % 'smr'] = log_normal_model.setup(dm, key % 'smr', data, SMR)\n\n # duration = E[time in bin C]\n @mc.deterministic(name=key % 'X')\n def X(r=r, m=m, f=f):\n hazard = r + m + f\n pr_not_exit = np.exp(-hazard)\n X = np.empty(len(hazard))\n X[-1] = 1 / hazard[-1]\n for i in reversed(range(len(X)-1)):\n X[i] = pr_not_exit[i] * (X[i+1] + 1) + 1 / hazard[i] * (1 - pr_not_exit[i]) - pr_not_exit[i]\n return X\n data = [d for d in data_list if d['data_type'] == 'duration data']\n vars[key % 'duration'] = normal_model.setup(dm, key % 'duration', data, X)\n\n # YLD[a] = disability weight * i[a] * X[a] * regional_population[a]\n @mc.deterministic(name=key % 'i*X')\n def iX(i=i, X=X, p=p, pop=rate_model.regional_population(key)):\n return i * X * (1-p) * pop \n vars[key % 'incidence_x_duration'] = {'rate_stoch': iX}\n\n return vars", "def experiment1(n=1000, m=100, mus=None, ss=None, s=1.0):\n if mus is None:\n mus = [-5, 1, 4]\n if ss is None:\n ss = [1, 0.3, 2]\n eps = 0.01\n\n # define a gaussian kernel with scale s\n k = GaussianKernel1D(s)\n\n # define the target distribution: sum of gaussians in dim 1\n p = SumOfGaussians1D(mus, ss)\n\n # start by random n points between -8 and 8\n np.random.seed(30082018) # fix the seed for consistent data over runs\n xi = np.random.uniform(-8, 8, n)\n\n # define a learning rate, and do the gradient descent\n lr = 10\n nsteps = 1500\n z = k.sample((n, m))\n e = [energy1D(xi, p, k, z)]\n e2 = [energy1D(xi, p, k, z)]\n\n x = xi.copy()\n x2 = xi.copy()\n for _ in tqdm(range(nsteps)):\n z = k.sample((n, m)) # generate for each position m samples from the kernel k\n dx = -2 / (n * m) * np.sum(p.b(x.reshape((n, 1)) + z), axis=1) + 1 / (n * (n - 1)) * (\n np.sum(k.b(x.reshape((n, 1)) - x.reshape((1, n))) - k.b(x.reshape((1, n)) - x.reshape((n, 1))), axis=1))\n dx2 = -2 / (n * m) * np.sum(p.b(x2.reshape((n, 1)) + z), axis=1) + 1 / (n * (n - 1)) * (\n np.sum(k.b(x2.reshape((n, 1)) - x2.reshape((1, n))) - k.b(x2.reshape((1, n)) - x2.reshape((n, 1))), axis=1))\n x -= lr * dx\n x2 -= np.diag(1 / (p(x2) + eps)).dot(dx2)\n e.append(energy1D(x, p, k, z))\n e2.append(energy1D(x2, p, k, z))\n\n # plotting\n t = np.linspace(-10, 10, 250)\n fig, axes = plt.subplots(nrows=3, ncols=1)\n for ax in axes:\n ax.plot(t, p(t))\n axes[0].hist(xi, 100, density=True)\n axes[0].set_title('initial')\n axes[1].hist(x, 100, density=True)\n axes[1].set_title('fixed lr')\n axes[2].hist(x2, 100, density=True)\n axes[2].set_title('adaptive lr')\n\n fig2, ax = plt.subplots()\n ax.plot(e, color='red')\n ax.plot(e2, color='green')\n\n plt.show()", "def UnbiasedEstimate(n,k,theta,Beta,theta0,Beta0,func,minT=1000,logf=None,zipfParam=1.5):\n # Draw the length of the Markov chain from a power law\n #T = minT + np.random.zipf(a=zipfParam)\n # Draw the length of the Markov chain from a geometric distribution\n T = minT + np.random.geometric(zipfParam)\n print(\"The number of steps in the Markov chain is %i\"%T)\n\n # Initialize variables\n R,I = np.shape(n)\n G1 = np.ones(R)\n G2 = np.ones(R)\n try:\n logf.size\n except AttributeError:\n logf = GetArray(n.max(),Beta)\n\n est = func(n,k,theta,Beta,theta0,Beta0)\n k1 = k.copy() # This is the equivalent of k\n k2 = k.copy() # This is the equivalent of \\tilde k\n for step in range(1,T+1):\n kR1 = k1.sum(1)\n kI1 = k1.sum(0)\n kR2 = k2.sum(1)\n kI2 = k2.sum(0)\n # Resample G\n for r in range(R):\n auxGammas = gamma(1,size=max(kR1[r],kR2[r]))\n G1[r] = gamma(theta/Beta)\n G2[r] = G1[r]\n G1[r] += sum(auxGammas[:kR1[r]])\n G2[r] += sum(auxGammas[:kR2[r]])\n # Resample D\n auxGammas = gamma(1,size=[I,max(kI1.max(),kI2.max())])\n auxGammas2 = gamma(1-Beta0,size=I)\n auxGamma = gamma(theta0+I*Beta0)\n D1 = auxGammas2 + np.array([sum(auxGammas[i,:kI1[i]-1]) for i in range(I)])\n D1 = D1/(D1.sum()+auxGamma)\n D2 = auxGammas2 + np.array([sum(auxGammas[i,:kI2[i]-1]) for i in range(I)])\n D2 = D2/(D2.sum()+auxGamma)\n # Resample k\n unif = np.random.uniform(size=k.shape)\n UpdateK(k1,n,I,R,G1,D1,unif,logf,Beta)\n if step>1:\n UpdateK(k2,n,I,R,G2,D2,unif,logf,Beta)\n # Terminate if coupling has merged\n if (k1==k2).all():\n break\n # Otherwise continue sum\n #denom = (1-zipf.cdf(step-minT-1,a=zipfParam)) if step>minT else 1.0\n denom = (1-geom.cdf(step-minT-1,p=zipfParam)) if step>minT else 1.0\n summand = (func(n,k1,theta,Beta,theta0,Beta0)-func(n,k2,theta,Beta,theta0,Beta0))/denom\n est += summand\n print summand\n print est\n return est", "def gaussNewton(function,startParam,paramRange, paramStep, target, optimise, cov = None, cov_iv=None,\r\n scalings=None, constraint_target=None, trace=False):\r\n\r\n\r\n\r\n # stage 0 -- setup\r\n nrandom = optimise.get('nrandom', None)\r\n deterministicPerturb = optimise.get('deterministicPertub', True)\r\n statusInfo='Continue'\r\n npt=len(target) # how many points we expect.\r\n if constraint_target is not None: npt+=1 # increment number of points to deal with constraint\r\n iterCount=0 # how many iterations we done.\r\n nFail = 0 # how many cases have failed since last sucess\r\n totalFail =0 # total number of failure we have had.\r\n prevBestParam=startParam[:] # copy startParam so have a prevBestParam if needed.\r\n\r\n # stage 1 -- Work out parameters for first iteration\r\n paramsGN, randIndx = rangeAwarePerturbations(startParam, paramRange, paramStep,\r\n nrandom = nrandom, deterministic = deterministicPerturb, trace=trace)\r\n statusList=[] # a list of the status\r\n while statusInfo == 'Continue':\r\n obsValuesGN, constraintGN = run_fn(function,paramsGN, npt, constraint_target=constraint_target) # run the functions.\r\n optStatus, paramsLS, err, err_constraint, infoGN =\\\r\n doGaussNewton(paramsGN,paramRange, obsValuesGN, target, cov=cov, scalings=scalings,\r\n constraint=constraintGN, constraint_target=constraint_target,\r\n studyJSON=optimise,trace=trace) # run GN\r\n # add some more information to the info dict.\r\n infoGN['err_constraint']=err_constraint\r\n infoGN['obsValues']=obsValuesGN\r\n infoGN['paramValues']=paramsGN\r\n if trace: # print out some information\r\n print \"GN: paramValues: \",paramsLS,\" err_constraint\",err_constraint[0]\r\n\r\n # run the functions on the linesearch values\r\n obsValuesLS, constraintLS = run_fn(function, paramsLS, npt, constraint_target=constraint_target)\r\n # need to merge paramsGS and paramsLS, obsValesGN & obsValuesGN & constraintGN and constraintLS\r\n params=np.vstack((paramsGN,paramsLS))\r\n obsValues=np.vstack((obsValuesGN,obsValuesLS))\r\n constraint=np.hstack((constraintGN,constraintLS))\r\n statusInfo, err, err_constraint, paramsGN, index, bestParam, infoLS = \\\r\n doLineSearch(params, paramRange, obsValues, target, paramStep, cov=cov, cov_iv=cov_iv,\r\n scalings=scalings,\r\n constraint=constraint, constraint_target=constraint_target,\r\n studyJSON=optimise,trace=trace) # run LS\r\n\r\n # add some information to the LineSearch info dict.\r\n infoLS['err_constraint']=err_constraint\r\n infoLS['paramValues']=paramsLS\r\n infoLS['obsValues']=obsValuesLS\r\n statusList.append({'gaussNewton':infoGN,'lineSearch':infoLS})\r\n iterCount += 1 # increase iteration count\r\n if trace:\r\n print \"LS: statusInfo %s Iter: %d Err_constraint\"%(statusInfo,iterCount),err_constraint\r\n\r\n\r\n if statusInfo == 'Continue' or statusInfo == 'Converged':\r\n nFail==0 # reset failure count as we are ok\r\n prevBestParam=bestParam[:] # update prevBestParam in case we restart\r\n else: # we've failed...\r\n nFail += 1 # increment failure count\r\n totalFail +=1 # and total fail count\r\n if (nrandom is not None) and (nFail < optimise.get('maxFails',0)): # random perturbation so allow retry\r\n # generate list of perturbed parameters.\r\n # the tricky issue here is that if we are running deterministically then\r\n # we will always get the same parameters perturbed...\r\n # Will hack this by passing a number to deterministic\r\n # then using that to increment the RNG.\r\n params, randIndx = rangeAwarePerturbations(prevBestParam, paramRange, paramStep, nrandom = nrandom,\r\n deterministic=totalFail + 1, trace=trace)\r\n statusInfo='continue' # keep going.\r\n\r\n if trace:\r\n print \"prevBestParam on iter %i is \"%iterCount,prevBestParam\r\n\r\n # end of iterative loop running doGaussNewton and doLineSearch.\r\n\r\n # rearrange the info array\r\n # start with the err_constraint from lineSearch\r\n if nrandom != None:\r\n raise NotImplementedError(\"Need to make info code work with random algorithm...If you don't care switch this off\")\r\n\r\n jacobian=[]\r\n hessian=[]\r\n alpha=[]\r\n err_constraint=[statusList[0]['gaussNewton']['err_constraint'][0]]\r\n bestParams=[startParam]\r\n iter=np.arange(len(statusList))\r\n for iterInfo in statusList:\r\n jacobian.append(iterInfo['gaussNewton']['jacobian'])\r\n hessian.append(iterInfo['gaussNewton']['hessian'])\r\n bestAlpha=iterInfo['lineSearch']['bestrun']\r\n err_constraint.append(iterInfo['lineSearch']['err_constraint'][bestAlpha])\r\n bestParams.append(iterInfo['lineSearch']['paramValues'][bestAlpha])\r\n alpha.append(iterInfo['lineSearch']['params']['alphas'][bestAlpha])\r\n\r\n #err_constraint=err_constraint[:-1]\r\n ## we don't want the last linesearch values...\r\n bestParams=bestParams[:-1]\r\n #for var in (jacobian,hessian,bestAlpha,err_constraint,bestParams,alpha):\r\n # var=np.asscalar(var)\r\n\r\n jacobian=np.asarray(jacobian)\r\n hessian=np.asarray(hessian)\r\n err_constraint=np.asarray(err_constraint)\r\n bestParams=np.asarray(bestParams)\r\n alpha=np.asarray(alpha)\r\n statusList={'jacobian':jacobian,'hessian':hessian,'alpha':alpha,'err_constraint':err_constraint,'iter':iter,'bestParams':bestParams}\r\n\r\n\r\n return prevBestParam, statusInfo, statusList # would also like to return a bunch of info to help trace the performance of the algorithm.\r", "def test_exponential_growth_model_local_d_optimal_design(self):\n lb2,ub2=1,10\n design_samples = np.linspace(0,1,5*int(ub2+lb2)+1)\n noise_multiplier = None\n parameter_sample = np.array([(ub2+lb2)/2])\n design_factors = exponential_growth_model_grad_parameters(\n parameter_sample,design_samples[np.newaxis,:]).T\n opt_problem = AlphabetOptimalDesign('D',design_factors)\n mu = opt_problem.solve({'iprint': 1, 'ftol':1e-8})\n I = np.where(mu>1e-5)[0]\n assert np.allclose(mu[I],1)\n assert np.allclose(design_samples[I],1/parameter_sample)", "def adabelief(\n params: List[Tensor],\n grads: List[Tensor],\n exp_avgs: List[Tensor],\n exp_avg_sqs: List[Tensor],\n max_exp_avg_sqs: List[Tensor],\n state_steps: List[int],\n amsgrad: bool,\n beta1: float,\n beta2: float,\n lr: float,\n weight_decay: float,\n eps: float,\n) -> None:\n\n for i, param in enumerate(params):\n\n grad = grads[i]\n exp_avg = exp_avgs[i]\n exp_avg_sq = exp_avg_sqs[i]\n step = state_steps[i]\n if amsgrad:\n max_exp_avg_sq = max_exp_avg_sqs[i]\n\n bias_correction1 = 1 - beta1**step\n bias_correction2 = 1 - beta2**step\n\n if weight_decay != 0:\n grad = grad.add(param, alpha=weight_decay)\n\n # Decay the first and second moment running average coefficient\n exp_avg.mul_(beta1).add_(grad, alpha=1 - beta1)\n grad_residual = grad - exp_avg\n exp_avg_sq.mul_(beta2).addcmul_(grad_residual, grad_residual, value=1 - beta2)\n\n if amsgrad:\n # Maintains the maximum of all 2nd moment running avg. till now\n torch.maximum(max_exp_avg_sq, exp_avg_sq, out=max_exp_avg_sq)\n # Use the max. for normalizing running avg. of gradient\n denom = (max_exp_avg_sq.sqrt() / math.sqrt(bias_correction2)).add_(eps)\n else:\n denom = (exp_avg_sq.sqrt() / math.sqrt(bias_correction2)).add_(eps)\n\n step_size = lr / bias_correction1\n\n param.addcdiv_(exp_avg, denom, value=-step_size)", "def run_model(Y,X,EM_DICT=None,verbose=0,modalpha=0.0005,removecells=1):\n\n enet=sklearn.linear_model.ElasticNet(precompute=True,l1_ratio=0.5,alpha=modalpha,max_iter=10000)\n enet.fit(X,Y)\n if verbose==1:\n print(enet.score(X,Y))\n\n Be=pd.DataFrame(enet.coef_)\n Be.columns=X.columns\n Be.index=Y.columns\n\n #EM iterateit\n Yhat=pd.DataFrame(enet.predict(X))\n Yhat.index=Y.index\n Yhat.columns=Y.columns\n SSE_all=np.square(Y.subtract(Yhat))\n\n X_adjust=X.copy()\n X_adjust['unperturbed']=[0]*len(X)\n\n df_SSE = []\n df_logit = []\n df_pf = []\n\n if EM_DICT is not None:\n\n for curcov in EM_DICT.keys():\n\n curcells=EM_DICT[curcov]\n\n X_notcur=X.copy()\n X_notcur[curcov]=[0]*len(X_notcur)\n\n X_sub=X_notcur.loc[curcells]\n\n Y_sub=Y.loc[curcells]\n\n GENE_var=2.0*Y_sub.var(axis=0)\n vargenes=GENE_var[GENE_var>0].index\n\n\n Yhat_notcur=pd.DataFrame(enet.predict(X_sub))\n Yhat_notcur.index=Y_sub.index\n Yhat_notcur.columns=Y_sub.columns\n\n SSE_notcur=np.square(Y_sub.subtract(Yhat_notcur))\n SSE=SSE_all.loc[curcells].subtract(SSE_notcur)\n SSE_sum=SSE.sum(axis=1)\n\n SSE_transform=SSE.div(GENE_var+0.5)[vargenes].sum(axis=1)\n logitify=np.divide(1.0,1.0+np.exp(SSE_sum))#SSE_transform))#sum))\n\n df_SSE.append(SSE_sum)\n df_logit.append(logitify)\n pf=np.mean(logitify>0.99)\n\n if verbose==1:\n \n print(curcov,pf)\n df_pf.append([curcov,pf])\n weak_perturb=1.0*(logitify<0.1)\n X_adjust[curcov].loc[curcells]=logitify\n X_adjust['unperturbed'].loc[curcells]=weak_perturb\n\n print('done with EM')\n\n #refit model\n\n enet=sklearn.linear_model.ElasticNet(precompute=True,l1_ratio=0.5,alpha=0.0005,max_iter=10000)\n\n if removecells==1:\n goodcells=X_adjust['unperturbed']!=1\n print(np.mean(goodcells))\n Y=Y[goodcells]\n X_adjust=X[goodcells]\n \n enet.fit(X_adjust,Y)\n Yhat=pd.DataFrame(enet.predict(X_adjust))\n Yhat.index=Y.index\n Yhat.columns=Y.columns\n\n if verbose==1:\n print(enet.score(X_adjust,Y))\n\n Be=pd.DataFrame(enet.coef_)\n Be.columns=X_adjust.columns\n Be.index=Y.columns\n RES_out=Y.subtract(Yhat) \n\n if EM_DICT is not None:\n return(Be,X_adjust,RES_out,df_pf)#,df_SSE,df_logit)\n\n return(Be,X_adjust,RES_out)#,df_SSE,df_logit)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Stores levels of gaussian perturbation (=epsilons) to a file.
def store_epsilons( model_path, epsilons, modelf, data, data_name, filename="optimized_epsilons"): resulting_accuracy_list = [] for gauss_eps in epsilons: resulting_accuracy_list.append(get_accuracy(gauss_eps, modelf, data, data_name)) dict_gauss_results = { "Epsilons of Gaussian Perturbation: ": epsilons, "Accuracies of Gaussian Perturbation: ": resulting_accuracy_list } print("Epsilons: ", epsilons) print("Accuracies: ", resulting_accuracy_list) print("File path: ", model_path) print() save_dict_to_txt(model_path, dict_gauss_results, filename)
[ "def add_gaussian_noise(path, sigma):\n \n data = np.loadtxt(path + '/output_data.txt').view(complex)\n noise = np.random.normal(0,sigma,data.size)\n noise = np.reshape(noise, data.shape)\n noised_data = data + noise\n np.savetxt(path + '/noised_data.txt', noised_data.view(float))\n return noised_data", "def write(self):\n\n # Write lines according to qst3 requirements for gaussian\n with open(self.filepath, 'w') as file:\n # file.write('%Chk={}checkpoint.com\\n'.format(utils.sanitize_path(os.path.dirname(self.filepath),\n # add_slash=True)))\n file.write(self.calculation.get_calc_line() + '\\n\\n')\n\n # Mol coords have to specified r -> p -> ts, otherwise gaussian will complain\n for coords, name in zip(self.mol_coords, ('reactant', 'product', 'ts')):\n file.write(self.molecule_name + ' {}\\n\\n'.format(name))\n file.write(self.multiplicity + '\\n')\n file.write(''.join(line for line in coords))\n file.write('\\n')\n\n file.write('\\n')", "def write_prob_dists_gnb_file(setting, names, X, y, clf, clf_name):\n\n # Get the directory of the probability distribution file\n prob_dists_file_dir = setting.prob_dists_file_dir + clf_name + '/'\n # Get the pathname of the probability distribution file\n prob_dists_file = prob_dists_file_dir + setting.prob_dists_file_name + setting.prob_dists_file_type\n\n # Make directory\n directory = os.path.dirname(prob_dists_file)\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n # Get the dictionary of probability distribution\n prob_dists = get_prob_dists_gnb(X, y, clf, clf_name)\n\n with open(prob_dists_file, 'w') as f:\n # Write header\n f.write(\"Class,Feature,Value,Probability\" + '\\n')\n\n for class_ in range(len(np.unique(y))):\n # Get the original value of class_ before the encoding\n class_ori = str(setting.encoder.inverse_transform(np.array([class_]))[0])\n\n for j in sorted(prob_dists[class_].keys()):\n # Get the name of the jth feature\n xj_name = names.features[j]\n\n # Get the original value of the jth feature before the scaling\n xijs_ori = [xij_ori for xij_ori in np.unique(sorted(X[:, j]))]\n\n # Get the probabilities\n pijs = [prob_dists[class_][j][xij] for xij in\n np.unique(sorted(prob_dists[class_][j].keys()))]\n\n for idx in range(len(pijs)):\n pij = pijs[idx]\n xij_ori = xijs_ori[idx]\n f.write(class_ori + ',' + xj_name + ',' + str(xij_ori) + ',' + str(pij) + '\\n')", "def saveGene(self, path):\r\n\r\n # Format a numpy array as a string, stripping extra spaces, and neatly\r\n # comma delimiting the numbers followed by a space:\r\n # np.array([1.0, 2.0, 3.0])\r\n def fm(a):\r\n return 'np.' + ''.join(repr(a).split()).replace(',', ', ')\r\n\r\n config = ConfigParser.ConfigParser(allow_no_value = True)\r\n config.optionxform=str\r\n config.add_section('PROPAGATION')\r\n config.set('PROPAGATION', '; Optimised using ' + self.__class__.__name__)\r\n config.set('PROPAGATION', 'ontimes', fm(self.ontimes))\r\n config.set('PROPAGATION', 'durations', fm(self.offtimes-self.ontimes))\r\n\r\n with open(path, 'wb') as f:\r\n config.write(f)", "def write_lgfile(self,directory):\n if not os.path.exists(directory):\n os.makedirs(directory)\n filepath = os.path.join(directory,os.path.splitext(os.path.basename(self.filename))[0]+'.lg')\n with open(filepath,'w') as f:\n for symbol in self.symbols:\n f.write('O, '+str(symbol.symbol_id)+', '+symbol.symbol_class+', 1.0')\n for stroke_id in symbol.stroke_list:\n f.write(', '+str(stroke_id))\n f.write('\\n')", "def save_gmm(gmm, filename):\n with open(filename, 'w') as _file:\n gmm_write(gmm, _file)", "def save_energy(self, path=''):\n\n assert(self.Gelec is not None)\n\n if path != '':\n if not os.path.isdir(path):\n print('Directory does not exist. Will try creating it...')\n os.mkdir(path)\n\n with open(path + self.name + '_energy.dat', 'w') as file:\n file.write('%1.15e eV\\n' % self.Gelec)", "def generate_lognorm_outdegree(vertices, filename):\n f = open(filename, \"wb\")\n mu = 4\n sigma = 1.3\n for i in xrange(vertices):\n outdegree = int(random.lognormvariate(mu, sigma))\n data = struct.pack('i', outdegree)\n f.write(data)\n f.close()", "def save_gamma(fileName, gamma, num_docs):\n f = open(fileName, 'w')\n for d in xrange(num_docs):\n f.write(\" \".join(\"{:5.10f}\".format(g) for g in gamma[d]))\n f.write(\"\\n\")\n f.close()", "def write(self):\n\n # Write file lines according to gaussian requirements\n with open(self.filepath, 'w') as file:\n # file.write('%Chk={}checkpoint.com\\n'.format(utils.sanitize_path(os.path.dirname(self.filepath),\n # add_slash=True)))\n file.write(self.calculation.get_calc_line() + '\\n\\n')\n file.write(self.molecule_name + '\\n\\n')\n file.write(self.multiplicity + '\\n')\n file.write(''.join(line for line in self.mol_coords))\n file.write('\\n\\n')", "def write_prob_dists_file(setting, names, X, y, clf, clf_name):\n\n # Get the directory of the probability distribution file\n prob_dists_file_dir = setting.prob_dists_file_dir + clf_name + '/'\n # Get the pathname of the probability distribution file\n prob_dists_file = prob_dists_file_dir + setting.prob_dists_file_name + setting.prob_dists_file_type\n\n # Make directory\n directory = os.path.dirname(prob_dists_file)\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n # Get the dictionary of probability distribution\n prob_dists = get_prob_dists(X, clf, clf_name)\n\n with open(prob_dists_file, 'w') as f:\n # Write header\n f.write(\"Class,Feature,Value,Probability\" + '\\n')\n\n for class_ in range(len(np.unique(y))):\n # Get the original value of class_ before the encoding\n class_ori = str(setting.encoder.inverse_transform(np.array([class_]))[0])\n\n for j in sorted(prob_dists[class_].keys()):\n # Get the name of the jth feature\n xj_name = names.features[j]\n\n # Get the original value of the jth feature before the scaling\n xijs_ori = [xij_ori for xij_ori in np.unique(sorted(X[:, j]))]\n\n # Get the probabilities\n pijs = [prob_dists[class_][j][xij] for xij in\n np.unique(sorted(prob_dists[class_][j].keys()))]\n\n for idx in range(len(pijs)):\n pij = pijs[idx]\n xij_ori = xijs_ori[idx]\n f.write(class_ori + ',' + xj_name + ',' + str(xij_ori) + ',' + str(pij) + '\\n')", "def save_values(self):\r\n print 'Storing values: average_income and histogram (latter in '\\\r\n'separate\\ncolumns [val,bin] and name Hist+filename'\r\n avg = self.average_in\r\n binss = self.binss[:-1]\r\n H = self.H \r\n np.savetxt(self.filename,np.c_[avg])\r\n np.savetxt(self.filename_b,np.c_[H,binss])\r\n if hasattr(self,'C_agent'):\r\n print 'Storing the average number agent (i) has interacted with\\nall j in column,'\r\n print 'filename = C_Model%g_gamma%g_lam%g_alpha%g'%(self.model,self.gamma,self.lam,self.alpha)\r\n print \"with '.' changed to '_'.\\n\" \r\n fold = self.fold\r\n C_agent = self.C_agent\r\n gam = str(float(self.gamma))\r\n l = str(float(self.lam))\r\n al = str(self.alpha)\r\n gam = gam[:gam.find('.')] + '_' + gam[gam.find('.')+1:]\r\n l = l[:l.find('.')] + '_' + l[l.find('.')+1:]\r\n al = al[:al.find('.')] + '_' + al[al.find('.')+1:]\r\n fil = 'C_Model%g_'%(self.model) + 'gamma' + gam + '_'+ 'lam' + l + \\\r\n '_' + 'alpha' + al + '.txt'\r\n if fold is not False:\r\n if not '/' in fold[-1]:\r\n fold = fold + '/'\r\n fil = fold + fil\r\n if os.path.isfile(fil):\r\n pass # Implement C check\r\n np.savetxt(fil,np.c_[C_agent])\r\n print 'Values stored'\r\n return None", "def save_data(halo_particles):\n mass, pos, vel = halo_particles(N_part=100, seed=42)\n data = np.ndarray([len(mass), 4])\n data[:, 0] = pos[:, 0]\n data[:, 1] = pos[:, 1]\n data[:, 2] = pos[:, 2]\n data[:, 3] = mass\n\n np.savetxt(\"mock_particles.dat\", data, fmt=\"%12.6f\")", "def save_intensities_data(self, intensities_array, hw_name):\n append = '_' + hw_name + '_intensity_sums.txt' #string to append to sample name\n self.check_filename(append)\n transposed = np.transpose(intensities_array)\n np.savetxt(self.app.settings['save_dir']+\"/\"+ self.app.settings['sample'] + append, transposed, fmt='%f')", "def save_particles(self, p_pth, w_pth):\n np.save(p_pth, self.poses)\n np.save(w_pth, self.weights)", "def save_geometric_features(features_dict, output_path, file_name):\n output_path += \"/\"\n path = join(output_path, file_name + \"_\" +\n SAVE_GEOMETRICAL_FEATURES)\n with open(path, 'w') as output_file:\n for k, v in features_dict.items():\n output_file.write(k + \": \" + v + \"\\n\")", "def write_probabilities_file(probabilities, filename, num_machines='all'):\n # open file\n f = open(filename, 'w')\n\n # write header\n f.write('{},{}\\n'.format('em_name', 'probability'))\n\n if num_machines == 'all':\n for em_name in sorted(probabilities.iterkeys()):\n f.write('{},{}\\n'.format(em_name, probabilities[em_name]))\n else:\n try:\n number_machines = int(num_machines)\n avail_machines = len(probabilities.keys())\n if number_machines > avail_machines:\n number_machines = avail_machines\n except:\n raise Exception(\"\\nNumber of machines requested not an integer\"\n \" that makes sense!\\n\")\n \n #sort_probs = sorted(probabilities, key=probabilities.get, reverse=True) \n # sort by probability, then machine name\n sort_probs = sorted(probabilities.items(),\n key = lambda x : (x[1], x[0]),\n reverse = True)\n \n for em_name, em_prob in sort_probs[0:number_machines]:\n f.write('{},{}\\n'.format(em_name, em_prob))\n\n f.close()", "def gaussian(self):\n i=0\n variance=1\n while (i < self.npoints):\n \n \n self.data[i] = np.random.normal(self.mean, variance)\n self.like[i] = 1/(2*np.pi)*np.exp(-(self.data[i,0]-self.mean[0])**2/2*variance**2)*np.exp(-(self.data[i,1]-self.mean[1])**2/2*variance**2)\n i+=1\n self.volume = math.pi**(self.dim/2)*(variance*2)**(self.dim)/math.gamma(self.dim/2+1) # the factor around variance is the number of sigma\n self.maindensity=self.npoints/self.volume \n print(\"main density is\", self.maindensity)", "def writeHessian(self):\n\t\tself.makeHessian()\n\t\tnp.savetxt(\"hessian.dat\",self.H,\"%15.7f\",\" \",\"\\n\")" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test an ir transceiver.
async def test_ir_transceiver( hass: HomeAssistant, ir_transceiver: Sensor, receive_message: Callable[[str], None], transport_write: MagicMock, ) -> None: entity_id = "remote.ir_transceiver_1_1" state = hass.states.get(entity_id) assert state assert state.state == "off" # Test turn on await hass.services.async_call( REMOTE_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) assert transport_write.call_count == 2 assert transport_write.call_args_list[0] == call("1;1;1;1;32;test_code\n") assert transport_write.call_args_list[1] == call("1;1;1;1;2;1\n") receive_message("1;1;1;0;32;test_code\n") receive_message("1;1;1;0;2;1\n") await hass.async_block_till_done() state = hass.states.get(entity_id) assert state assert state.state == "on" transport_write.reset_mock() # Test send command await hass.services.async_call( REMOTE_DOMAIN, SERVICE_SEND_COMMAND, {ATTR_ENTITY_ID: entity_id, ATTR_COMMAND: "new_code"}, blocking=True, ) assert transport_write.call_count == 1 assert transport_write.call_args == call("1;1;1;1;32;new_code\n") receive_message("1;1;1;0;32;new_code\n") await hass.async_block_till_done() state = hass.states.get(entity_id) assert state assert state.state == "on" transport_write.reset_mock() # Test learn command await hass.services.async_call( REMOTE_DOMAIN, SERVICE_LEARN_COMMAND, {ATTR_ENTITY_ID: entity_id, ATTR_COMMAND: "learn_code"}, blocking=True, ) assert transport_write.call_count == 1 assert transport_write.call_args == call("1;1;1;1;50;learn_code\n") receive_message("1;1;1;0;50;learn_code\n") await hass.async_block_till_done() state = hass.states.get(entity_id) assert state assert state.state == "on" transport_write.reset_mock() # Test learn command with missing command parameter with pytest.raises(ValueError): await hass.services.async_call( REMOTE_DOMAIN, SERVICE_LEARN_COMMAND, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) assert transport_write.call_count == 0 transport_write.reset_mock() # Test turn off await hass.services.async_call( REMOTE_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) assert transport_write.call_count == 1 assert transport_write.call_args == call("1;1;1;1;2;0\n") receive_message("1;1;1;0;2;0\n") await hass.async_block_till_done() state = hass.states.get(entity_id) assert state assert state.state == "off" transport_write.reset_mock() # Test turn on with new default code await hass.services.async_call( REMOTE_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) assert transport_write.call_count == 2 assert transport_write.call_args_list[0] == call("1;1;1;1;32;new_code\n") assert transport_write.call_args_list[1] == call("1;1;1;1;2;1\n") receive_message("1;1;1;0;32;new_code\n") receive_message("1;1;1;0;2;1\n") await hass.async_block_till_done() state = hass.states.get(entity_id) assert state assert state.state == "on" # Test unknown state ir_transceiver.children[1].values.pop(SetReq.V_LIGHT) # Trigger state update receive_message("1;1;1;0;32;new_code\n") await hass.async_block_till_done() state = hass.states.get(entity_id) assert state assert state.state == "unknown"
[ "def test_connection(self):\n for sender in self.senders:\n sender.test_connection()", "def _testBee(self, source):\n pass\n source.send('at',command='vr')\n return source.wait_read_frame()", "def device_test(self):\n # Create a MPI packet object\n mpi_packet = MPI()\n mpi_packet.descriptor = MPI.MPI_BASE_CMD_DESCRIPTOR\n \n # Set to idle payload\n field_len = 0x02\n field_desc = 0x05\n mpi_packet.payload = [field_len, field_desc]\n\n # Payload length \n mpi_packet.payload_len = len(mpi_packet.payload)\n \n # Build imu ping command in bytes\n command = mpi_packet.build()\n \n # Send byte packet to microstrain imu \n self.ser.write(command)\n \n # Read output from the imu adter sleeping for 2 ms\n sleep(0.002)\n reply = self.ser.read(16)\n \n if reply[7] == \"\\x00\":\n print \" Device Built-In Test (BIT) successful!\"\n print \" BIT Error Flags : \"\n print \" Byte 1 : \", '0x' + reply[10].encode('hex') \n print \" Byte 2 : \", '0x' + reply[11].encode('hex')\n print \" Byte 3 : \", '0x' + reply[12].encode('hex')\n print \" Byte 4 : \", '0x' + reply[13].encode('hex')\n else:\n print \" Command unsuccessful\"\n err = '0x' + reply[7].encode('hex')\n print \" Error Code : \", err\n print \" Error Message : \", MPI.MPI_ACK_NACK_ERROR[err]\n \n return", "def test_bus_timetable_with_route():\n dublinbus = DublinBusRTPI(\"312\", \"67\")\n dublinbus.raw_rtpi_data = Mock(return_value=EXAMPLE_API_RESPONSE)\n assert dublinbus.bus_timetable() == EXPECTED_OUTPUT_ROUTE_FILTER", "async def test_contract_internal_erc20_transfers_with_weth_through_toshi(self, *, parity, push_client, monitor):\n\n zrx = await self.deploy_erc20_contract(\"ZRX\", \"0x\", 18)\n tok = await self.deploy_erc20_contract(\"TOK\", \"TOK Token\", 18)\n weth = await Contract.from_source_code(WETH_CONTRACT.encode('utf8'), \"WETH9\", deployer_private_key=FAUCET_PRIVATE_KEY)\n async with self.pool.acquire() as con:\n await con.execute(\"INSERT INTO tokens (contract_address, symbol, name, decimals) VALUES ($1, $2, $3, $4)\",\n weth.address, \"WETH\", \"Wrapped Ether\", 18)\n\n # monkey patch WETH contract variable\n import toshieth.constants\n toshieth.constants.WETH_CONTRACT_ADDRESS = weth.address\n import toshieth.manager\n toshieth.manager.WETH_CONTRACT_ADDRESS = weth.address\n import toshieth.monitor\n toshieth.monitor.WETH_CONTRACT_ADDRESS = weth.address\n\n exchange = await Contract.from_source_code(SIMPLE_EXCHANGE_CONTRACT.encode('utf8'), \"SimpleExchange\", constructor_data=[zrx.address], deployer_private_key=FAUCET_PRIVATE_KEY)\n\n await self.faucet(TEST_ADDRESS, 10 * 10 ** 18)\n await self.faucet(TEST_ADDRESS_2, 10 * 10 ** 18)\n\n await zrx.transfer.set_sender(FAUCET_PRIVATE_KEY)(TEST_ADDRESS, 10 * 10 ** 18)\n await zrx.transfer.set_sender(FAUCET_PRIVATE_KEY)(TEST_ADDRESS_2, 10 * 10 ** 18)\n await tok.transfer.set_sender(FAUCET_PRIVATE_KEY)(TEST_ADDRESS_2, 10 * 10 ** 18)\n\n raw_tx = await weth.deposit.get_raw_tx.set_sender(TEST_PRIVATE_KEY)(value=5 * 10 ** 18)\n await self.send_raw_tx(raw_tx)\n\n raw_tx = await zrx.approve.get_raw_tx.set_sender(TEST_PRIVATE_KEY)(exchange.address, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)\n await self.send_raw_tx(raw_tx)\n raw_tx = await zrx.approve.get_raw_tx.set_sender(TEST_PRIVATE_KEY_2)(exchange.address, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)\n await self.send_raw_tx(raw_tx)\n\n raw_tx = await tok.approve.get_raw_tx.set_sender(TEST_PRIVATE_KEY)(exchange.address, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)\n await self.send_raw_tx(raw_tx)\n raw_tx = await tok.approve.get_raw_tx.set_sender(TEST_PRIVATE_KEY_2)(exchange.address, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)\n await self.send_raw_tx(raw_tx)\n\n raw_tx = await weth.approve.get_raw_tx.set_sender(TEST_PRIVATE_KEY)(exchange.address, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)\n await self.send_raw_tx(raw_tx)\n raw_tx = await weth.approve.get_raw_tx.set_sender(TEST_PRIVATE_KEY_2)(exchange.address, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)\n await self.send_raw_tx(raw_tx)\n\n resp = await self.fetch(\"/tokens/{}\".format(TEST_ADDRESS))\n self.assertResponseCodeEqual(resp, 200)\n body = json_decode(resp.body)\n self.assertEqual(len(body['tokens']), 2)\n resp = await self.fetch(\"/tokens/{}\".format(TEST_ADDRESS_2))\n self.assertResponseCodeEqual(resp, 200)\n body = json_decode(resp.body)\n self.assertEqual(len(body['tokens']), 2)\n\n raw_tx = await exchange.createOrder.get_raw_tx.set_sender(TEST_PRIVATE_KEY)(\n weth.address, 5 * 10 ** 18, tok.address, 5 * 10 ** 18)\n await self.send_raw_tx(raw_tx)\n raw_tx = await exchange.fillOrder.get_raw_tx.set_sender(TEST_PRIVATE_KEY_2)(\n TEST_ADDRESS, weth.address, 5 * 10 ** 18, tok.address, 5 * 10 ** 18)\n await self.send_raw_tx(raw_tx)\n\n await monitor.filter_poll()\n await asyncio.sleep(0.1)\n\n self.assertEqual(await zrx.balanceOf(TEST_ADDRESS), 9 * 10 ** 18)\n self.assertEqual(await zrx.balanceOf(TEST_ADDRESS_2), 9 * 10 ** 18)\n self.assertEqual(await tok.balanceOf(TEST_ADDRESS), 5 * 10 ** 18)\n self.assertEqual(await tok.balanceOf(TEST_ADDRESS_2), 5 * 10 ** 18)\n self.assertEqual(await weth.balanceOf(TEST_ADDRESS), 0)\n self.assertEqual(await weth.balanceOf(TEST_ADDRESS_2), 5 * 10 ** 18)\n\n resp = await self.fetch(\"/tokens/{}\".format(TEST_ADDRESS))\n\n self.assertResponseCodeEqual(resp, 200)\n body = json_decode(resp.body)\n self.assertEqual(len(body['tokens']), 2)\n\n has_tok = has_weth = has_zrx = False\n for token in body['tokens']:\n if token['symbol'] == 'TOK':\n self.assertEqual(token['value'], hex(5 * 10 ** 18))\n has_tok = True\n elif token['symbol'] == 'WETH':\n has_weth = True\n elif token['symbol'] == 'ZRX':\n self.assertEqual(token['value'], hex(9 * 10 ** 18))\n has_zrx = True\n else:\n self.fail(\"unexpected token symbol\")\n\n self.assertTrue(has_tok and has_zrx and not has_weth)\n\n resp = await self.fetch(\"/tokens/{}\".format(TEST_ADDRESS_2))\n\n self.assertResponseCodeEqual(resp, 200)\n body = json_decode(resp.body)\n self.assertEqual(len(body['tokens']), 3)\n\n has_tok = has_weth = has_zrx = False\n for token in body['tokens']:\n if token['symbol'] == 'TOK':\n self.assertEqual(token['value'], hex(5 * 10 ** 18))\n has_tok = True\n elif token['symbol'] == 'WETH':\n self.assertEqual(token['value'], hex(5 * 10 ** 18))\n has_weth = True\n elif token['symbol'] == 'ZRX':\n self.assertEqual(token['value'], hex(9 * 10 ** 18))\n has_zrx = True\n else:\n self.fail(\"unexpected token symbol\")\n\n self.assertTrue(has_tok and has_zrx and has_weth)\n\n resp = await self.fetch(\"/balance/{}\".format(TEST_ADDRESS_2))\n self.assertResponseCodeEqual(resp, 200)\n body = json_decode(resp.body)\n balance_before_withdral = int(body['confirmed_balance'], 16)\n\n raw_tx = await weth.withdraw.get_raw_tx.set_sender(TEST_PRIVATE_KEY_2)(5 * 10 ** 18)\n await self.send_raw_tx(raw_tx)\n\n await monitor.filter_poll()\n await asyncio.sleep(0.1)\n\n resp = await self.fetch(\"/tokens/{}\".format(TEST_ADDRESS_2))\n\n self.assertResponseCodeEqual(resp, 200)\n body = json_decode(resp.body)\n self.assertEqual(len(body['tokens']), 2, body)\n\n has_tok = has_weth = has_zrx = False\n for token in body['tokens']:\n if token['symbol'] == 'TOK':\n self.assertEqual(token['value'], hex(5 * 10 ** 18))\n has_tok = True\n elif token['symbol'] == 'WETH':\n has_weth = True\n elif token['symbol'] == 'ZRX':\n self.assertEqual(token['value'], hex(9 * 10 ** 18))\n has_zrx = True\n else:\n self.fail(\"unexpected token symbol\")\n\n self.assertTrue(has_tok and has_zrx and not has_weth)\n resp = await self.fetch(\"/balance/{}\".format(TEST_ADDRESS_2))\n self.assertResponseCodeEqual(resp, 200)\n body = json_decode(resp.body)\n\n balance_after_withdral = int(body['confirmed_balance'], 16)\n self.assertLess(balance_before_withdral, balance_after_withdral)", "async def test_passing_in_bleak_to_controller():\n with patch.object(\n controller_module, \"BLE_TRANSPORT_SUPPORTED\", False\n ), patch.object(controller_module, \"COAP_TRANSPORT_SUPPORTED\", False), patch.object(\n controller_module, \"IP_TRANSPORT_SUPPORTED\", False\n ):\n controller = Controller(\n bleak_scanner_instance=AsyncMock(register_detection_callback=MagicMock())\n )\n await controller.async_start()\n\n assert len(controller.transports) == 1\n assert isinstance(controller.transports[TransportType.BLE], BleController)", "def listen_tester(stop):\n while not stop.is_set():\n command = tester.read()\n if len(command) > 0:\n log.info(f\"Tester -> IUT :: {command.hex()}\")\n ocf, ogf, length, data = decode_hci(command.hex())\n if (ocf, ogf) in iut.commands_black_list:\n mutex.acquire()\n ble_cmd = iut.commands_black_list[(ocf, ogf)]\n event = ble_cmd(data) if length > 0 else ble_cmd()\n log.info(f\"IUT -> Tester :: {event.decode()}\")\n tester.write(event)\n mutex.release()\n else:\n iut.interface.write(binascii.hexlify(command))", "def test_drivers(devices, expected, current_actor_context):\n current_actor_context.feed(PCIDevices(devices=devices))\n current_actor_context.run()\n if expected:\n assert not current_actor_context.consume(Report)\n else:\n assert current_actor_context.consume(Report)", "def test_rd_send_router_solicitation(self):\n\n count = 2\n self.pg_enable_capture(self.pg_interfaces)\n self.pg_start()\n self.vapi.ip6nd_send_router_solicitation(self.pg1.sw_if_index, mrc=count)\n rx_list = self.pg1.get_capture(count, timeout=3)\n self.assertEqual(len(rx_list), count)\n for packet in rx_list:\n self.assertEqual(packet.haslayer(IPv6), 1)\n self.assertEqual(packet[IPv6].haslayer(ICMPv6ND_RS), 1)\n dst = ip6_normalize(packet[IPv6].dst)\n dst2 = ip6_normalize(\"ff02::2\")\n self.assert_equal(dst, dst2)\n src = ip6_normalize(packet[IPv6].src)\n src2 = ip6_normalize(self.pg1.local_ip6_ll)\n self.assert_equal(src, src2)\n self.assertTrue(bool(packet[ICMPv6ND_RS].haslayer(ICMPv6NDOptSrcLLAddr)))\n self.assert_equal(packet[ICMPv6NDOptSrcLLAddr].lladdr, self.pg1.local_mac)", "def testRTUFramerPacket(self):\n old_encode = ModbusRequest.encode\n ModbusRequest.encode = lambda self: b''\n message = ModbusRequest()\n message.unit_id = 0xff\n message.function_code = 0x01\n expected = b\"\\xff\\x01\\x81\\x80\" # only header + CRC - no data\n actual = self._rtu.buildPacket(message)\n self.assertEqual(expected, actual)\n ModbusRequest.encode = old_encode", "def test_Bridge_setBlockedIn_IR_address(self):\n self.bridge.updateFromNetworkStatus(self.networkstatus)\n self.bridge.updateFromServerDescriptor(self.serverdescriptor)\n self.bridge.updateFromExtraInfoDescriptor(self.extrainfo)\n\n self.bridge.setBlockedIn('IR', address='179.178.155.140')\n self.assertTrue(self.bridge.isBlockedIn('ir'))\n self.assertFalse(self.bridge.isBlockedIn('cn'))", "def main():\n print(\"Opening port...\")\n try:\n if use_uart:\n port = UART(2, 9600)\n port.init(9600, bits=8, parity=None, stop=1)\n else:\n port = I2C()\n except Exception as exception:\n raise Exception(\"error opening port: \"\n + NotecardExceptionInfo(exception))\n\n print(\"Opening Notecard...\")\n try:\n if use_uart:\n card = notecard.OpenSerial(port)\n else:\n card = notecard.OpenI2C(port, 0, 0)\n except Exception as exception:\n raise Exception(\"error opening notecard: \"\n + NotecardExceptionInfo(exception))\n\n # If success, do a transaction loop\n print(\"Performing Transactions...\")\n while True:\n time.sleep(2)\n transactionTest(card)", "async def test_contract_internal_erc20_transfers_with_weth(self, *, parity, push_client, monitor):\n\n zrx = await self.deploy_erc20_contract(\"ZRX\", \"0x\", 18)\n tok = await self.deploy_erc20_contract(\"TOK\", \"TOK Token\", 18)\n weth = await Contract.from_source_code(WETH_CONTRACT.encode('utf8'), \"WETH9\", deployer_private_key=FAUCET_PRIVATE_KEY)\n async with self.pool.acquire() as con:\n await con.execute(\"INSERT INTO tokens (contract_address, symbol, name, decimals) VALUES ($1, $2, $3, $4)\",\n weth.address, \"WETH\", \"Wrapped Ether\", 18)\n\n # monkey patch WETH contract variable\n import toshieth.constants\n toshieth.constants.WETH_CONTRACT_ADDRESS = weth.address\n import toshieth.manager\n toshieth.manager.WETH_CONTRACT_ADDRESS = weth.address\n import toshieth.monitor\n toshieth.monitor.WETH_CONTRACT_ADDRESS = weth.address\n\n exchange = await Contract.from_source_code(SIMPLE_EXCHANGE_CONTRACT.encode('utf8'), \"SimpleExchange\", constructor_data=[zrx.address], deployer_private_key=FAUCET_PRIVATE_KEY)\n\n await self.faucet(TEST_ADDRESS, 10 * 10 ** 18)\n await self.faucet(TEST_ADDRESS_2, 10 * 10 ** 18)\n\n await zrx.transfer.set_sender(FAUCET_PRIVATE_KEY)(TEST_ADDRESS, 10 * 10 ** 18)\n await zrx.transfer.set_sender(FAUCET_PRIVATE_KEY)(TEST_ADDRESS_2, 10 * 10 ** 18)\n await tok.transfer.set_sender(FAUCET_PRIVATE_KEY)(TEST_ADDRESS_2, 10 * 10 ** 18)\n await weth.deposit.set_sender(TEST_PRIVATE_KEY)(value=5 * 10 ** 18)\n\n await zrx.approve.set_sender(TEST_PRIVATE_KEY)(exchange.address, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)\n await zrx.approve.set_sender(TEST_PRIVATE_KEY_2)(exchange.address, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)\n\n await tok.approve.set_sender(TEST_PRIVATE_KEY)(exchange.address, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)\n await tok.approve.set_sender(TEST_PRIVATE_KEY_2)(exchange.address, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)\n\n await weth.approve.set_sender(TEST_PRIVATE_KEY)(exchange.address, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)\n await weth.approve.set_sender(TEST_PRIVATE_KEY_2)(exchange.address, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)\n\n resp = await self.fetch(\"/tokens/{}\".format(TEST_ADDRESS))\n self.assertResponseCodeEqual(resp, 200)\n body = json_decode(resp.body)\n self.assertEqual(len(body['tokens']), 2)\n resp = await self.fetch(\"/tokens/{}\".format(TEST_ADDRESS_2))\n self.assertResponseCodeEqual(resp, 200)\n body = json_decode(resp.body)\n self.assertEqual(len(body['tokens']), 2)\n\n await exchange.createOrder.set_sender(TEST_PRIVATE_KEY)(\n weth.address, 5 * 10 ** 18, tok.address, 5 * 10 ** 18)\n await exchange.fillOrder.set_sender(TEST_PRIVATE_KEY_2)(\n TEST_ADDRESS, weth.address, 5 * 10 ** 18, tok.address, 5 * 10 ** 18)\n\n await monitor.filter_poll()\n await asyncio.sleep(0.1)\n\n self.assertEqual(await zrx.balanceOf(TEST_ADDRESS), 9 * 10 ** 18)\n self.assertEqual(await zrx.balanceOf(TEST_ADDRESS_2), 9 * 10 ** 18)\n self.assertEqual(await tok.balanceOf(TEST_ADDRESS), 5 * 10 ** 18)\n self.assertEqual(await tok.balanceOf(TEST_ADDRESS_2), 5 * 10 ** 18)\n self.assertEqual(await weth.balanceOf(TEST_ADDRESS), 0)\n self.assertEqual(await weth.balanceOf(TEST_ADDRESS_2), 5 * 10 ** 18)\n\n resp = await self.fetch(\"/tokens/{}\".format(TEST_ADDRESS))\n\n self.assertResponseCodeEqual(resp, 200)\n body = json_decode(resp.body)\n self.assertEqual(len(body['tokens']), 2)\n\n has_tok = has_weth = has_zrx = False\n for token in body['tokens']:\n if token['symbol'] == 'TOK':\n self.assertEqual(token['value'], hex(5 * 10 ** 18))\n has_tok = True\n elif token['symbol'] == 'WETH':\n has_weth = True\n elif token['symbol'] == 'ZRX':\n self.assertEqual(token['value'], hex(9 * 10 ** 18))\n has_zrx = True\n else:\n self.fail(\"unexpected token symbol\")\n\n self.assertTrue(has_tok and has_zrx and not has_weth)\n\n resp = await self.fetch(\"/tokens/{}\".format(TEST_ADDRESS_2))\n\n self.assertResponseCodeEqual(resp, 200)\n body = json_decode(resp.body)\n self.assertEqual(len(body['tokens']), 3)\n\n has_tok = has_weth = has_zrx = False\n for token in body['tokens']:\n if token['symbol'] == 'TOK':\n self.assertEqual(token['value'], hex(5 * 10 ** 18))\n has_tok = True\n elif token['symbol'] == 'WETH':\n self.assertEqual(token['value'], hex(5 * 10 ** 18))\n has_weth = True\n elif token['symbol'] == 'ZRX':\n self.assertEqual(token['value'], hex(9 * 10 ** 18))\n has_zrx = True\n else:\n self.fail(\"unexpected token symbol\")\n\n self.assertTrue(has_tok and has_zrx and has_weth)\n\n resp = await self.fetch(\"/balance/{}\".format(TEST_ADDRESS_2))\n self.assertResponseCodeEqual(resp, 200)\n body = json_decode(resp.body)\n balance_before_withdral = int(body['confirmed_balance'], 16)\n\n await weth.withdraw.set_sender(TEST_PRIVATE_KEY_2)(5 * 10 ** 18)\n\n await monitor.filter_poll()\n await asyncio.sleep(0.1)\n\n resp = await self.fetch(\"/tokens/{}\".format(TEST_ADDRESS_2))\n\n self.assertResponseCodeEqual(resp, 200)\n body = json_decode(resp.body)\n self.assertEqual(len(body['tokens']), 2)\n\n has_tok = has_weth = has_zrx = False\n for token in body['tokens']:\n if token['symbol'] == 'TOK':\n self.assertEqual(token['value'], hex(5 * 10 ** 18))\n has_tok = True\n elif token['symbol'] == 'WETH':\n has_weth = True\n elif token['symbol'] == 'ZRX':\n self.assertEqual(token['value'], hex(9 * 10 ** 18))\n has_zrx = True\n else:\n self.fail(\"unexpected token symbol\")\n\n self.assertTrue(has_tok and has_zrx and not has_weth)\n resp = await self.fetch(\"/balance/{}\".format(TEST_ADDRESS_2))\n self.assertResponseCodeEqual(resp, 200)\n body = json_decode(resp.body)\n\n balance_after_withdral = int(body['confirmed_balance'], 16)\n self.assertLess(balance_before_withdral, balance_after_withdral)", "def test_is_remote_response_parsed_as_io(self):\n # Build IO data\n # One sample, ADC 0 enabled\n # DIO 1,3,5,7 enabled\n header = b'\\x01\\x02\\xAA'\n\n # First 7 bits ignored, DIO8 low, DIO 0-7 alternating\n # ADC0 value of 255\n sample = b'\\x00\\xAA\\x00\\xFF'\n data = header + sample\n\n device = Serial()\n device.set_read_data(APIFrame(\n data=b'\\x97D\\x00\\x13\\xa2\\x00@oG\\xe4v\\x1aIS\\x00' + data).output()\n )\n\n xbee = XBee(device, io_loop=self._patch_io)\n\n xbee._process_input(None, None)\n info = yield xbee.wait_read_frame()\n expected_info = {'id': 'remote_at_response',\n 'frame_id': b'D',\n 'source_addr_long': b'\\x00\\x13\\xa2\\x00@oG\\xe4',\n 'source_addr': b'v\\x1a',\n 'command': b'IS',\n 'status': b'\\x00',\n 'parameter': [{'dio-1': True,\n 'dio-3': True,\n 'dio-5': True,\n 'dio-7': True,\n 'adc-0': 255}]}\n self.assertEqual(info, expected_info)", "def try_send(self, args): \n if self.debug_stub:\n print \"{0}_stub : ------- : \".format(self.stub_name)\n \n\n \n # send IR wake up \n try :\n if self.debug_stub:\n print \"{0}_stub : {1} --> {2} : IR\".format(self.stub_name, self.dongle_addr, self.smart_board_addr)\n self.Xbee.IR_wake_up_trought_Xbee()\n \n except IOError:\n raise IOError(\"send IR wake up serial error\")\n\n \n\n # send the chaski cmd \n try :\n self.Xbee.send(args['SString'], self.smart_board_addr)\n if self.debug_stub :\n print \"{0}_stub : {1} --> {2} : {3}\".format(self.stub_name, self.dongle_addr, self.smart_board_addr, args['SString'])\n \n except AssertionError as e:\n raise AssertionError(\"send {0} assert error : {1}\".format(self.stub_name, e)) #fatal error ...\n except IOError:\n raise IOError(\"{0} serial error\".format(self.stub_name))\n \n\n \n # wait for cmd reply with \"return\" ident. Treat debug reply. \n try :\n while True:\n src,rcv = self.Xbee.read(src_exp = self.smart_board_addr, timeout = self.com_timeout)\n if rcv[len(rcv)-1] == '\\n' and self.debug_board:\n print \"{0}_stub : {1} <-- {2} : {3}\".format(self.stub_name, self.dongle_addr, self.smart_board_addr, rcv[:-1])\n if rcv[:5] == \"reply\":\n reply = rcv[6:-1]\n break\n \n except IOError:\n raise IOError(\"{0} serial error\".format(self.stub_name))\n except TypeError:\n\t self.Xbee.flushInput() \n\t self.Xbee.flushOutput() \n\t raise IOError(\"received {0} timeout error\".format(self.stub_name))\n \n \n \n return {'error':None, 'reply':reply, 'op':args['op']}", "def test_connection(self, test_values=None):\n if not test_values:\n test_values = [0, self.range_dac[0], randint(0, 4095)]\n instructions = []\n for v in test_values:\n instructions.append([0, 0, v])\n\n for n in xrange(N_TRIES):\n self.serial_device.send_instructions(instructions)\n time.sleep(0.1)\n if self.bytes_available():\n if test_values == map(int, self.read_all().splitlines()):\n if self.serial_device.get_pins():\n return True\n return False", "def test_a_register_device_for_loan_license(self):\n self.status.register(self.status.DEVICEID1, self.status.DEVICENAME1)", "def test_sendMsg(self):\n # Send test message\n testMsg = b'123456789'\n msgBytes = testMsg\n self.radio.sendMsg(testMsg)\n time.sleep(0.1)\n self.radio.readBytes(True)\n readBytes = self.radio.getRxBytes()\n assert(readBytes == msgBytes)", "def test_active_tor_reboot_upstream(\n upper_tor_host, lower_tor_host, send_server_to_t1_with_action, # noqa F811\n toggle_all_simulator_ports_to_upper_tor, toggle_upper_tor_pdu, # noqa F811\n wait_for_device_reachable, wait_for_mux_container, cable_type # noqa F811\n):\n send_server_to_t1_with_action(\n upper_tor_host, verify=True, delay=MUX_SIM_ALLOWED_DISRUPTION_SEC,\n action=toggle_upper_tor_pdu, stop_after=60\n )\n wait_for_device_reachable(upper_tor_host)\n wait_for_mux_container(upper_tor_host)\n\n if cable_type == CableType.active_standby:\n verify_tor_states(\n expected_active_host=lower_tor_host,\n expected_standby_host=upper_tor_host\n )\n elif cable_type == CableType.active_active:\n verify_tor_states(\n expected_active_host=[upper_tor_host, lower_tor_host],\n expected_standby_host=None,\n cable_type=cable_type,\n verify_db_timeout=60\n )" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Elevation matrix to read the elevation text
def load_elevation_matrix(): with open("mpp.txt") as f: elevation_matrix = [elevation_matrix.split() for elevation_matrix in f] for i in range(5): for row in elevation_matrix: del row[-1] return elevation_matrix
[ "def print_elevation_ME():\n dem = ee.Image('USGS/SRTMGL1_003')\n xy = ee.Geometry.Point([86.9250, 27.9881])\n elev = dem.sample(xy, 30).first().get('elevation').getInfo()\n print('Mount Everest elevation (m):', elev)\n return", "def elevation_plot_data(self):\n if self.elevations is None:\n raise ValueError(\"Elevation samples must be obtained first\")\n if self.segments is None:\n self.calculate_segment_data()\n segment_distance = [segment.distance for segment in self.segments]\n distance = [0] + list(accumulate(segment_distance))\n height = [elevation.height for elevation in self.elevations]\n return {\"distance\": distance, \"height\": height}", "def clean_elevation(elevation):\n cleaned_elevation_list = [letter.replace(\n '\\n', '').strip().split() for letter in open_file(file)]\n elevation_list = [[int(cleaned_elevation_list) for cleaned_elevation_list\n in row] for row in cleaned_elevation_list]\n return elevation_list", "def elevation_model(input_file, elevation_file, lat, lon, maps_key=None):\r\n print(\"Getting elevation data...\")\r\n file = calc_elevation(input_file, elevation_file, lat, lon, map_key=maps_key)\r\n # Compute connectivity of the spatial system\r\n print(\"Creating connectivity matrix...\")\r\n connectivity = construct_adjacency(file, lat, lon)\r\n # Connectivity includes an adjacency matrix, elevation vector and object reference to the data\r\n return connectivity", "def read_dem(dem_path):\n\n src = rasterio.open(dem_path)\n arr = src.read(1)\n profile = src.profile\n pixel_size = profile['transform'][0]\n return arr, pixel_size, profile", "def dem2array(filename, variable_name='elevation',\n easting_min=None, easting_max=None,\n northing_min=None, northing_max=None,\n use_cache=False, verbose=False,):\n\n\n\n\n import os\n from anuga.file.netcdf import NetCDFFile\n\n\n\n\n msg = 'Filename must be a text string'\n assert isinstance(filename, str), msg\n \n\n \n msg = 'Extension should be .dem'\n assert os.path.splitext(filename)[1] in ['.dem'], msg\n \n msg = 'Variable name must be a text string'\n assert isinstance(variable_name, str), msg\n \n\n\n # Get NetCDF\n infile = NetCDFFile(filename, netcdf_mode_r) \n\n if verbose: log.critical('Reading DEM from %s' % (filename))\n\n ncols = int(infile.ncols)\n nrows = int(infile.nrows)\n xllcorner = float(infile.xllcorner) # Easting of lower left corner\n yllcorner = float(infile.yllcorner) # Northing of lower left corner\n cellsize = float(infile.cellsize)\n NODATA_value = float(infile.NODATA_value)\n\n\n zone = int(infile.zone)\n false_easting = float(infile.false_easting)\n false_northing = float(infile.false_northing)\n \n # Text strings\n projection = infile.projection\n datum = infile.datum\n units = infile.units\n \n Z = infile.variables[variable_name][:]\n Z = Z.reshape(nrows,ncols)\n Z = num.where(Z == NODATA_value , num.nan, Z)\n #changed the orientation of Z array to make it consistent with grd2array result\n Z = num.fliplr(Z.T)\n\n #print ncols, nrows, xllcorner,yllcorner, cellsize, NODATA_value, zone\n\n x = num.linspace(xllcorner, xllcorner+(ncols-1)*cellsize, ncols)\n y = num.linspace(yllcorner, yllcorner+(nrows-1)*cellsize, nrows)\n\n return x,y, Z", "def test_get_elevation_data(self):\n self.assertEqual(get_elevation_data(-34.9281805,138.5999312), 2)", "def test_decimate_dem(self):\n\n import os\n from anuga.file.netcdf import NetCDFFile\n\n #Write test dem file\n root = 'decdemtest'\n\n filename = root + '.dem'\n fid = NetCDFFile(filename, netcdf_mode_w)\n\n fid.institution = 'Geoscience Australia'\n fid.description = 'NetCDF DEM format for compact and portable ' +\\\n 'storage of spatial point data'\n\n nrows = 15\n ncols = 18\n\n fid.ncols = ncols\n fid.nrows = nrows\n fid.xllcorner = 2000.5\n fid.yllcorner = 3000.5\n fid.cellsize = 25\n fid.NODATA_value = -9999\n\n fid.zone = 56\n fid.false_easting = 0.0\n fid.false_northing = 0.0\n fid.projection = 'UTM'\n fid.datum = 'WGS84'\n fid.units = 'METERS'\n\n fid.createDimension('number_of_points', nrows*ncols)\n\n fid.createVariable('elevation', netcdf_float, ('number_of_points',))\n\n elevation = fid.variables['elevation']\n\n elevation[:] = (num.arange(nrows*ncols))\n\n fid.close()\n\n #generate the elevation values expected in the decimated file\n ref_elevation = [( 0+ 1+ 2+ 18+ 19+ 20+ 36+ 37+ 38) / 9.0,\n ( 4+ 5+ 6+ 22+ 23+ 24+ 40+ 41+ 42) / 9.0,\n ( 8+ 9+ 10+ 26+ 27+ 28+ 44+ 45+ 46) / 9.0,\n ( 12+ 13+ 14+ 30+ 31+ 32+ 48+ 49+ 50) / 9.0,\n ( 72+ 73+ 74+ 90+ 91+ 92+108+109+110) / 9.0,\n ( 76+ 77+ 78+ 94+ 95+ 96+112+113+114) / 9.0,\n ( 80+ 81+ 82+ 98+ 99+100+116+117+118) / 9.0,\n ( 84+ 85+ 86+102+103+104+120+121+122) / 9.0,\n (144+145+146+162+163+164+180+181+182) / 9.0,\n (148+149+150+166+167+168+184+185+186) / 9.0,\n (152+153+154+170+171+172+188+189+190) / 9.0,\n (156+157+158+174+175+176+192+193+194) / 9.0,\n (216+217+218+234+235+236+252+253+254) / 9.0,\n (220+221+222+238+239+240+256+257+258) / 9.0,\n (224+225+226+242+243+244+260+261+262) / 9.0,\n (228+229+230+246+247+248+264+265+266) / 9.0]\n\n # generate a stencil for computing the decimated values\n stencil = num.ones((3,3), float) / 9.0\n\n dem2dem(filename, stencil=stencil, cellsize_new=100)\n\n # Open decimated NetCDF file\n fid = NetCDFFile(root + '_100.dem', netcdf_mode_r)\n\n # Get decimated elevation\n elevation = fid.variables['elevation']\n\n # Check values\n assert num.allclose(elevation, ref_elevation)\n\n # Cleanup\n fid.close()\n\n os.remove(root + '.dem')\n os.remove(root + '_100.dem')", "def test_elevation_getter_array_dtype(self):\n\n poly = get_raster_bbox_as_polygon(test_dem)\n bounds = poly.bounds\n mean_x = np.mean(bounds[0::2]) # middle of xs\n mean_y = np.mean(bounds[1::2]) # middle of ys\n x = np.array((mean_x, mean_x))\n y = np.array((mean_y, mean_y))\n\n result = get_elevation(test_dem, x, y)\n result_type = result.dtype.kind\n self.assertIsInstance(result, np.ndarray)\n self.assertIn(result_type, ['i', 'u', 'f'])", "def viz_elevation(self) -> (hv.DynamicMap, hv.Layout):\n\n OA_da = self.parallel_request_OA()\n\n if OA_da is None:\n print(\"No data\")\n return (None,) * 2\n\n else:\n\n cols = (\n [\"lat\", \"lon\", \"elevation\", \"canopy\", \"rgt\", \"cycle\"]\n if self.product == \"ATL08\"\n else [\"lat\", \"lon\", \"elevation\", \"rgt\", \"cycle\"]\n )\n ddf = dd.io.from_dask_array(OA_da, columns=cols).astype(\n {\n \"lat\": \"float\",\n \"lon\": \"float\",\n \"elevation\": \"float\",\n \"rgt\": \"int\",\n \"cycle\": \"int\",\n }\n )\n\n print(\"Plot elevation, please wait...\")\n\n x, y = ds.utils.lnglat_to_meters(ddf.lon, ddf.lat)\n ddf_new = ddf.assign(x=x, y=y).persist()\n dset = hv.Dataset(ddf_new)\n\n raster_cycle = dset.to(\n hv.Points,\n [\"x\", \"y\"],\n [\"elevation\"],\n groupby=[\"cycle\"],\n dynamic=True,\n )\n raster_rgt = dset.to(\n hv.Points, [\"x\", \"y\"], [\"elevation\"], groupby=[\"rgt\"], dynamic=True\n )\n curve_rgt = dset.to(\n hv.Scatter, [\"lat\"], [\"elevation\"], groupby=[\"rgt\"], dynamic=True\n )\n\n tiles = hv.element.tiles.EsriImagery().opts(\n xaxis=None, yaxis=None, width=450, height=450\n )\n map_cycle = tiles * rasterize(\n raster_cycle, aggregator=ds.mean(\"elevation\")\n ).opts(colorbar=True, tools=[\"hover\"])\n map_rgt = tiles * rasterize(\n raster_rgt, aggregator=ds.mean(\"elevation\")\n ).opts(colorbar=True, tools=[\"hover\"])\n lineplot_rgt = rasterize(curve_rgt, aggregator=ds.mean(\"elevation\")).opts(\n width=450, height=450, cmap=[\"blue\"]\n )\n\n return map_cycle, map_rgt + lineplot_rgt", "def open_file(file):\n elevation_small_file = open(file, 'r')\n elevation = elevation_small_file.readlines()\n return elevation", "def getElevation(self,time):\n ele = self.orb.get_observer_look(time, self.lon, self.lat,self.alt)\n return ele[1]", "def elevation(x, y):\n \n z = numpy.zeros(x.shape,dtype='d')\n z[:] = elevation_0\n \n numpy.putmask(z, x > d_length/2, elevation_1)\n \n return z", "def _parse_4ti2_matrix(self, string):\n try:\n ints = [int(_) for _ in string.split()]\n except ValueError:\n raise RuntimeError(\"Format error: encountered non-number.\")\n if len(ints) < 2:\n raise RuntimeError(\"Format error: \" +\n \"matrix dimensions not specified.\")\n\n term_count = ints[0]\n var_count = ints[1]\n ints = ints[2:]\n\n if term_count * var_count != len(ints):\n raise RuntimeError(\"Format error: incorrect matrix dimensions.\")\n\n exponents = []\n for i in range(term_count):\n exponents.append(ints[:var_count])\n ints = ints[var_count:]\n return exponents;", "def calc_elevation(filename, elevation_file, latfield, lonfield, map_key=None):\r\n try:\r\n if map_key:\r\n file = processdbf(filename)\r\n file.openfile()\r\n\r\n gmaps = googlemaps.Client(key=map_key)\r\n elevations = []\r\n\r\n lat_index = file.get_column(latfield)\r\n lon_index = file.get_column(lonfield)\r\n\r\n tmp = []\r\n e = []\r\n for i in range(len(lat_index[1])):\r\n # iterate through and check for NaN values.\r\n try:\r\n tmp.append((float(lat_index[1][i]), float(lon_index[1][i])))\r\n # if value is NaN append the row index value to the e list\r\n except ValueError:\r\n e.append(i)\r\n pass\r\n\r\n if len(tmp) > 499: # API Rate Limit 2500 queries per day | 520 points per query\r\n geocode_result = gmaps.elevation(tmp)\r\n for k in geocode_result:\r\n ele = k['elevation']\r\n # convert to feet\r\n ele = ele * 3.28084\r\n elevations.append(float(ele))\r\n tmp = []\r\n else:\r\n pass\r\n\r\n if len(tmp) > 0:\r\n geocode_result = gmaps.elevation(tmp)\r\n for l in geocode_result:\r\n ele = l['elevation']\r\n # convert to feet\r\n ele = ele * 3.28084\r\n elevations.append(float(ele))\r\n else:\r\n pass\r\n # remove rows with NaN values\r\n cnt = 0\r\n for i in e:\r\n dex = i + 1\r\n dex = dex - cnt\r\n del file.output[dex]\r\n cnt = cnt + 1\r\n\r\n file.add_column('Elevation', elevations)\r\n return file\r\n else:\r\n ele = processdbf(elevation_file)\r\n ele.open_csv()\r\n\r\n # elevations = ele.get_column(\"Elevation\")\r\n parcels = ele.get_column('PARCELATT')\r\n\r\n file = processdbf(filename)\r\n file.openfile()\r\n\r\n data = synch_files(file, ele, parcels)\r\n # data.add_column('Elevation', elevations[1])\r\n return data\r\n except MemoryError:\r\n print('Memory Error')\r\n pass\r\n except RuntimeError:\r\n print('Runtime Error')\r\n pass\r\n except TypeError:\r\n print('Type Error')\r\n pass\r\n except NameError:\r\n print('Name Error')\r\n pass", "def get_eman2_tilts(info_file):\n with open(info_file, \"r\") as f:\n info = json.load(f)\n tlt_params = np.array(info[\"tlt_params\"])\n tlt_angles = tlt_params[:, 3]\n tilt_axis = np.mean(tlt_params[:, 2])\n\n return tilt_axis, tlt_angles", "def extract_data(npy_file, dat_file): \n page = np.load(npy_file)\n letters = np.genfromtxt(dat_file)\n \n page_height = page.shape[0] # Define a height of a page\n n_rows = int(letters.shape[0])\n \n width, height = 39,51# Width and height of a box, where I place each letter\n n_columns = width*height\n pixels = np.zeros((n_rows, n_columns))\n labels = np.ndarray((2, n_rows))\n \n # Detect a boundary box around letter; move corresponding pixels into array\n for rows in xrange(n_rows):\n temp_pixels = np.zeros((width, height))\n x1 = int(letters[rows, 1])\n y1 = page_height - int(letters[rows, 4])\n x2 = int(letters[rows, 3])\n y2 = page_height - int(letters[rows, 2])\n let_pix=page[y1:y2, x1:x2];\n temp_pixels[1:1+let_pix.shape[0], 1:1+let_pix.shape[1]] = let_pix\n pixels[rows, :] = temp_pixels.flatten()\n \n # Extract labels and letter's state\n with open(dat_file) as f:\n for index, line in enumerate(f):\n x = line.split() \n let = x[0]\n labels[0,index] = dictionary[let]\n labels[1,index] = x[5]\n \n return pixels, labels", "def load_r_ind_oaat_mats():\n mats = []\n for text in texts:\n mats.append(np.load('Textbooks/{}/r_ind_oaat_mats.npy'.format(text)))\n return mats", "def read_elevation_raster(session):\n\n name = 'elevation-cached.tif'\n\n dataset = gdal.Open(name, GA_ReadOnly)\n if dataset is not None:\n logging.info('elevation raster loaded from cached file')\n else:\n logging.info('building elevation raster from nyc3dcars')\n # pylint: disable-msg=E1101\n union = func.ST_Union(Elevation.rast)\n # pylint: enable-msg=E1101\n gtiff = func.ST_AsGDALRaster(union, 'GTiff')\n\n raster, = session.query(gtiff) \\\n .one()\n\n with open(name, 'wb') as raster_file:\n raster_file.write(raster)\n\n dataset = gdal.Open(name, GA_ReadOnly)\n\n return parse_dataset(dataset)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Connects to a PostgreSQL service through DSN.
def connect_dsn(self, dsn): if self.debug: print("Connecting to PostgreSQL") try: self.con = I_sql.connect(dsn) if self.debug: print("Connected to PostgreSQL") self.con.set_isolation_level(I_sql.extensions.ISOLATION_LEVEL_AUTOCOMMIT) except (Exception, I_sql.DatabaseError) as error: print("SQL Connection Error Occured >> ") print(error) return self.con
[ "def _get_conn(self, dsn):\n return psycopg2.connect(dsn)", "def setup_postgres():\n conn = psycopg2.connect(\"postgresql://python:{}@{}:5432/kin\".format(PYTHON_PASSWORD, POSTGRES_HOST))\n logging.info('Successfully connected to the database')\n return conn", "def open(self):\n\n conn_string = f\"host={self.host} user={self.user} password={self.password} dbname={self.dbname} port={self.port}\"\n try:\n self.conn = psycopg2.connect(conn_string)\n print(\"POSTGRES::Connection established\")\n except Exception as e:\n print(str(e))", "def init_postgresql_connection():\n connection = connect(user='test',\n password='test',\n host='localhost',\n port='5432',\n database='infrastructure')\n cursor = connection.cursor()\n return connection, cursor", "def __connect() -> psycopg2.extensions.connection:\n db_connection = psycopg2.connect(\n database=os.environ[\"DATABASE\"],\n user=os.environ[\"USER\"],\n password=os.environ[\"PASSWORD\"],\n host=os.environ[\"HOST\"],\n port=\"5432\",\n )\n\n db_connection.autocommit = True\n return db_connection", "def connect_to_db():\n conn_info = {'host': DB_HOST,\n 'port': 5433,\n 'user': DB_USER,\n 'password': DB_PASSWORD,\n 'database': DB_NAME,\n # 10 minutes timeout on queries\n 'read_timeout': 600,\n # default throw error on invalid UTF-8 results\n 'unicode_error': 'strict',\n # SSL is disabled by default\n 'ssl': False}\n\n db = vertica_python.connect(**conn_info)\n if db:\n db.cursor().execute('set search_path to ' + DB_SCHEMA + ', \"$user\", public;')\n return db", "def oracle_connection(self):\n import cx_Oracle\n oracle_host = self.configs.get('oracle', 'host')\n oracle_port = self.configs.get('oracle', 'port')\n oracle_sid = self.configs.get('oracle', 'sid')\n oracle_user = self.configs.get('oracle', 'user') \n oracle_pass = self.configs.get('oracle', 'password')\n oracle_dsn_tns = cx_Oracle.makedsn(oracle_host, oracle_port, oracle_sid)\n\n return cx_Oracle.connect(oracle_user, oracle_pass, oracle_dsn_tns)", "def build_db_conn(host, port, database, username, password):\n postgres = PgConn(host=host,\n port=port,\n database=database,\n username=username,\n password=password)\n\n return postgres", "async def try_connect_postgres(self, host, user, password, database):\n\n while True:\n logger.info(\"Trying to connect to postgres... {}@{}/{}\".format(user, host, database))\n logger.debug(\"loop: {}\".format(self.loop))\n try:\n postgres = await aiopg.create_pool(\n loop=self.loop,\n host=host,\n user=user,\n database=database,\n password=password)\n logger.info(\"Successfully connected to postgres\")\n return postgres\n except:\n logger.warn(\"Failed to connect to postgres\")\n time.sleep(5)", "def connectToDB(cnxn_info):\r\n driver = cnxn_info['driver']\r\n server = cnxn_info['server']\r\n database = cnxn_info['database']\r\n username = cnxn_info['username']\r\n password = cnxn_info['password']\r\n return pyodbc.connect('driver={%s};server=%s;database=%s;uid=%s;pwd=%s' %\r\n (driver, server, database, username, password))", "def init_db():\n with open(\"../config.yml\", 'r') as config:\n cfg = yaml.load(config, Loader=yaml.FullLoader)\n\n logger.info(\"Connecting to {} on port {}\".format(cfg['hostname'], cfg['port']))\n connection = psycopg2.connect(host=cfg['hostname'],\n port=cfg['port'],\n user=cfg['username'],\n password=cfg['password'],\n dbname=cfg['database'])\n logger.info(\"Connected!\")\n\n return connection", "def connect(self):\n conn_str = self.__user + \"/\" + self.__password + \"@\" + self.__host + \":\" + self.__port + \"/\" + self.__service\n try:\n self.__conn = cx_Oracle.connect(conn_str, encoding = \"UTF-8\", nencoding = \"UTF-8\")\n except Exception as e:\n self.__logger.log(\"Exception caught whilst establishing connection to database! [\" + str(e) + \"]\")\n #raise Exception(\"Couldn't connect to database: [\" + str(e) + \"]\")", "def pg_params(request, pg_conn):\n if is_psycopg2(pg_conn): # pragma: no cover\n dsn = pg_conn.get_dsn_parameters()\n del dsn[\"tty\"]\n else: # assume psycopg 3.x\n dsn = pg_conn.info.get_parameters()\n # non empty password?\n if \"password\" not in dsn:\n dsn[\"password\"] = request.config.getoption(\"postgresql_password\") or \"\"\n if \"port\" not in dsn:\n dsn[\"port\"] = 5432\n return dsn", "def dbconn_from_args(argv=sys.argv[1:], environ=os.environ):\n parser = optparse.OptionParser()\n parser.add_option(\"-D\",\"--dbname\", action=\"store\", dest=\"dbname\",\n help=\"database name of the topology network\")\n parser.add_option(\"-H\",\"--dbhost\", action=\"store\", dest=\"dbhost\",\n help=\"database host address of the topology network\")\n parser.add_option(\"-P\",\"--dbport\", action=\"store\", dest=\"dbport\",\n help=\"database port of the topology network\")\n parser.add_option(\"-U\",\"--dbuser\", action=\"store\", dest=\"dbuser\",\n help=\"database user name of the topology network\")\n parser.add_option(\"-X\",\"--dbpwrd\", action=\"store\", dest=\"dbpwrd\",\n help=\"database user password of the topology network\")\n\n (options, args) = parser.parse_args(argv)\n # Options have precedence over environment variables, which have\n # precedence over defaults.\n\n # NB: None (or null) host and port values are completely reasonable and\n # mean a local (unix domain socket) connection. This way postgresql can\n # be configured without network support, which is convenient and secure.\n dbhost = options.dbhost or environ.get('PGHOST')\n dbport = options.dbport or environ.get('PGPORT')\n # postgres is the default database role, and why not use it?\n dbuser = options.dbuser or environ.get('PGUSER', 'postgres')\n # A None password is also valid but it implies the server must be configured\n # to support either 'trust' or 'ident' identification. For a local server this\n # is convenient, but it isn't secure for network installations. Review\n # man pg_hba.conf for the details.\n dbpwrd = options.dbpwrd or environ.get('PGPASSWORD')\n dbname = options.dbname or environ.get('PGDATABASE', 'eu_power_160718')\n\n try:\n logging.info(\"PostgreSQL connection parameters:\")\n logging.info(\"--> Host: \" + str(dbhost))\n logging.info(\"--> Port: \" + str(dbport))\n logging.info(\"--> User: \" + str(dbuser))\n logging.info(\"--> Database: \" + str(dbname))\n return psycopg2.connect(host=dbhost, port=dbport, user=dbuser,\n password=dbpwrd, database=dbname)\n except psycopg2.Error as e:\n logging.error(\"Could not connect to database with supplied information\", exc_info=True)\n if len(argv) == 0 or len(args) == len(argv):\n parser.print_help()\n raise e", "def database_connection(self, database_name):\n return psycopg2.connect(dbname=database_name, user='andela', host='localhost', password='bootcamp')", "def postgres():\n utils.create_db()\n try:\n yield utils.get_postgres_dsn()\n finally:\n utils.drop_db()", "def connect(self, dbCredentials):\n\t\tself.dbConnection = psycopg2.connect(dbCredentials)\n\t\tself.cursor = self.dbConnection.cursor()", "def testing_connection_string(self):\n return f\"postgresql://{self.postgres_user}:{self.postgres_pass}@{self.postgres_host_writer}:{self.postgres_port}/pgstactestdb\"", "def create_connection(username):\n \n cred_location = \"/mnt/data/{}/utils/data_creds_redshift.json.nogit\".format(username)\n db = db_connection.DBConnection(cred_location)\n return db" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Deletes an entire schema from a database.
def deleteSchema(self, schema): if self.schemaTarget == schema: self.schemaTarget = "" return self.query("DROP SCHEMA IF EXISTS {}", (), schema)
[ "def delete_schema(self):\n try:\n os.remove(self.schema_shelf_file)\n except OSError:\n pass", "def _drop_schema(schema_name, database):\n database.engine.execute(f'DROP USER {schema_name}')", "def drop_schemas(self) -> None:\n self.drop_schema()\n for service in self.storage_services.values():\n if service.schema_exists:\n service.drop_schema()", "def dropall(conn):\n with conn.cursor() as cur:\n cur.execute(\"SELECT table_schema,table_name FROM information_schema.tables \"\n \"WHERE table_schema = 'public' ORDER BY table_schema,table_name\")\n rows = cur.fetchall()\n for row in rows:\n logger.info('Dropping table: {0}'.format(row[1]))\n cur.execute(\"drop table {} cascade\".format(row[1]))", "def dropdb():\n db.drop_all()\n click.echo('Dropping the db')", "def cli_cosmosdb_database_delete(client, database_id):\n client.DeleteDatabase(_get_database_link(database_id))", "def drop(self):\n self.client.delete_database(self.database_name)", "def deleteAllTables():\n\n # Creates connections to our databases and cursors to work with it\n mainDBConn = connect(\"database/database.sqlite\")\n mainDBCursor = mainDBConn.cursor()\n historyDBConn = connect(\"database/history.sqlite\")\n historyDBCursor = historyDBConn.cursor()\n\n mainDBCursor.execute(\"DROP TABLE animals\")\n mainDBCursor.execute(\"DROP TABLE clients\")\n mainDBCursor.execute(\"DROP TABLE petsClientsLink\")\n mainDBCursor.execute(\"DROP TABLE appointments\")\n historyDBCursor.execute(\"DROP TABLE history\")\n\n mainDBConn.commit()\n historyDBConn.commit()\n mainDBConn.close()\n historyDBConn.close()", "def drop_database():\n drop_service_db()", "def clear_db(wd):\n files = glob.glob(\n os.path.join(wd, '*.json'))\n files.extend(glob.glob(\n os.path.join(wd, '*.db')))\n\n logger.debug(f'Removing files: {files}')\n\n for f in files:\n try:\n os.remove(f)\n except OSError:\n logger.error(f'Error while deleting file: {f}')", "def purge_database() -> None:\n _confirm_intent('purge cardbuilder\\'s entire local database')\n\n with InDataDir():\n os.remove(DATABASE_NAME)", "def wipe_database():\r\n dbpath = \"/\".join(__file__.split('/')[:-1] + ['samples.db'])\r\n os.system(\"rm -f {0}\".format(dbpath))", "def delete_database(ctx, app_name, yes, database_id):\n logging.getLogger(\"gigalixir-cli\").info(\"WARNING: Deleting your database will destroy all your data and backups.\")\n logging.getLogger(\"gigalixir-cli\").info(\"WARNING: This can not be undone.\")\n logging.getLogger(\"gigalixir-cli\").info(\"WARNING: Please make sure you backup your data first.\")\n if yes or click.confirm('Do you want to delete your database and all backups?'):\n gigalixir_database.delete(ctx.obj['host'], app_name, database_id)", "def destroy_db():\n run('mysqladmin --defaults-file={home}/.my-admin.cnf --force drop {dbname}'.format(\n home=env.HOME, dbname=env.DB_NAME))\n run(\"mysql --defaults-file={home}/.my-admin.cnf -e 'DROP USER \\\"{user}\\\"@\\\"%\\\"'\".format(\n home=env.HOME, user=env.DB_USER))", "def wipe_db():\n User.objects.all().delete()\n models.Issue.objects.all().delete()", "def drop_everything(engine: Engine):\n from sqlalchemy.engine.reflection import Inspector\n from sqlalchemy.schema import (\n DropConstraint,\n DropTable,\n MetaData,\n Table,\n ForeignKeyConstraint,\n )\n\n con = engine.connect()\n trans = con.begin()\n inspector = Inspector.from_engine(engine)\n\n # We need to re-create a minimal metadata with only the required things to\n # successfully emit drop constraints and tables commands for postgres (based\n # on the actual schema of the running instance)\n meta = MetaData()\n tables = []\n all_fkeys = []\n\n for table_name in inspector.get_table_names():\n fkeys = []\n\n for fkey in inspector.get_foreign_keys(table_name):\n if not fkey[\"name\"]:\n continue\n\n fkeys.append(ForeignKeyConstraint((), (), name=fkey[\"name\"]))\n\n tables.append(Table(table_name, meta, *fkeys))\n all_fkeys.extend(fkeys)\n\n for fkey in all_fkeys:\n con.execute(DropConstraint(fkey))\n\n for table in tables:\n con.execute(DropTable(table))\n\n trans.commit()", "def removeGraphDB (self):\n self.graph_db.delete_all()", "def clearDatabase(self, really = False):\n # WARNING: THIS WILL REMOVE ALL DOCUMENTS IN THE DATABASE!\n # IT WILL ONLY KEEP BEHIND THE DESIGN DOCUMENTS!\n if really:\n self.logger.warn(\"Deleting all documents in the database!\")\n for result in self.db:\n if (result.find(\"_design\") == -1):\n doc = self.db[result]\n self.db.delete(doc)", "def test_delete_schema(self):\n try:\n Draft4Validator.check_schema(token.TokenView2.DELETE_SCHEMA)\n schema_valid = True\n except RuntimeError:\n schema_valid = False\n\n self.assertTrue(schema_valid)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Inserts fields into a table.
def insert(self, table, fields): field_keys = ', '.join(fields.keys()) _fields = '\',\''.join(fields.values()) return self.query("INSERT INTO {} ({}) VALUES ({})", (field_keys, _fields), table)
[ "def insert_into_table(db_conn, field_names_list, field_values_list, table_name):\n with db_conn, db_conn.cursor() as cursor:\n execute_values(cursor, \"\"\"INSERT INTO {tbl_name}({field_names_list})\n VALUES %s\"\"\".format(tbl_name=table_name,\n field_names_list=', '.join(field_names_list)),\n field_values_list)", "def insert(self, table, **kw):\n return self.operation(table.insert().values(**kw))", "def _insert_rows_sql_insert(cls,\n table_context: \"TableContext\"\n ) -> None:\n if UploadType.SQL_INSERT not in cls.supported_uploads:\n raise Exception(f\"SQL INSERT not supported by `{cls.__name__}`\")\n with table_context.engine_context.engine.begin() as conn:\n conn.execute(table_context.table.insert(), *table_context.output_rows)", "def insert(self, sql):", "def insert_table_row(self, table, values, cursor=None):\n\t\tsql = \"\"\n\t\tfor value in values:\n\t\t\t# TODO: quote values?\n\t\t\tif sql: sql += \", \"\n\t\t\tsql += value\n\t\tsql = \"INSERT INTO %s VALUES (%s)\" % (self._quote(table), sql)\n\t\tif cursor:\n\t\t\tself._exec_sql(cursor, sql)\n\t\telse:\n\t\t\tself._exec_sql_and_commit(sql)", "def insert_record(table, record):\n columns = record.keys()\n values = record.values()\n\n # ['col1', 'col2', 'col3' ] -> \"col1,col2,col3\"\n columns_fragment = \",\".join(columns)\n\n # ['val1', 'val2', 'val3' ] to \"'val1', 'val2', 'val3'\"\n values_fragment = \"'\" + \"', '\".join(values) + \"'\"\n\n query = \"insert into `{}` ({}) values({})\".format(table, \n columns_fragment, values_fragment)\n sql(query)", "def insert(self,dict,name=None):\n if name is None:\n name = self.tableName\n\n columnNames = [sanitizeString(x) for x in dict.keys()]\n values = [sanitizeString(x) if isinstance(x,str) else x for x in dict.values()]\n\n columns = ', '.join(columnNames)\n placeholders = ', '.join(['?'] * len(dict))\n insertStr = 'INSERT INTO %s ' % name\n insertStr += '(%s) VALUES ( %s )' % (columns,placeholders) \n self.execute(insertStr,values)", "def insert():\n try:\n if tab[\"tbheaders\"] == None:\n raise Exception(\"tbheaders not set\")\n except Exception:\n print t['sel_st']\n return\n # TODO, optimize for many inserts\n # rows = [ ('itm', itm, 'itm'),\n # ('itm', itm, 'itm'),\n # ('itm', itm, 'itm') ]\n # c.executemany('insert into table values (?,?,?,?,?)', rows )\n # connection.commit()\n\n # ouch the pain. Why did i do that like that.\n ret = [ tuple( cli.show(sep( t['provide'], \n \"format: (X; Y; 3; Z),\", \n tab[\"tbheaders\"])).split(\";\") \n ) \n ]\n prep = lambda: \"\".join( [ \"?,\" for x in tab[\"tbheaders\"].split(\",\") ] )[:-1]\n for item in ret:\n sql = \"INSERT INTO %s %s VALUES(%s)\" \\\n % ( tab[\"tbname\"], tab['tbheaders'], prep() )\n try:\n tab[\"cur\"].execute(sql, item)\n tab[\"conn\"].commit()\n except sqlite3.ProgrammingError:\n print t['notallowed']", "def insert_into(conn, table_name, columns, values):\n try:\n values_string = \"?\"\n if isinstance(columns, basestring):\n #sanitizing input to be an array if string\n columns = columns.split(',') \n for i in range(len(columns)-1):\n values_string = values_string + \",\" + values_string\n \n columns = ','.join(columns) #making sure columns is formatted correctly\n INSERT_STRING = (\n \"INSERT INTO {0} ( {1} ) \"\n \"VALUES({2})\"\n ).format(table_name, columns, values_string)\n c = conn.cursor()\n c.execute(INSERT_STRING, values)\n except Error as e:\n print e", "def add_values_from_dict(self, table, conv_dict):\n\n sql_insert = \"INSERT INTO {0} ({1}) VALUES ({2});\"\n\n fields_list = []\n values_list = []\n\n for tram in conv_dict:\n fields_list.append(tram)\n values_list.append(conv_dict[tram])\n\n fields = ', '.join(fields_list)\n values = ', '.join(values_list)\n\n executed_sql = sql_insert.format(table, fields, values)\n\n #print(executed_sql)\n self.cur.execute(executed_sql)\n\n self.conn.commit()", "def addRow(self, conn, info, dryrun=False, create=False, table=None):\n if table is None:\n table = self.config.table\n sql = \"INSERT\"\n if self.config.ignore:\n sql += \" OR IGNORE\"\n sql += \" INTO %s VALUES (NULL\" % table\n sql += \", ?\" * len(self.config.columns)\n sql += \")\"\n values = [info[col] for col in self.config.columns]\n if dryrun:\n print \"Would execute: '%s' with %s\" % (sql, \",\".join([str(value) for value in values]))\n else:\n conn.execute(sql, values)", "def dbInsert(table, *args):\n connection = sqlite3.connect(Constants.DATABASE)\n connection.row_factory = sqlite3.Row\n\n cursor = connection.cursor()\n query = 'INSERT INTO ' + table + ' VALUES (\\'' + str(args[0]) + '\\''\n\n for i in range(1, len(args)):\n query += ', \\'' + str(args[i]) + '\\''\n\n query += ')'\n\n cursor.execute(query)\n\n connection.commit()\n cursor.close()\n connection.close()", "def get_add_sql(self, add_fields):\n # Insert into table.\n sql = \"INSERT INTO \" + str(self.test_table) + \" (\"\n # Get the keys set.\n key_list = list(add_fields.keys())\n # Variable for holding values.\n vals = \"\"\n # For each key, add the text 'key = value, ' so that each field is updated correctly.\n for i in range(len(key_list)):\n # Get the field being updated.\n field = key_list[i]\n val = add_fields[field]\n # Change how the value should look in the sql depending on it's type.\n if type(val) is str:\n value = self.connector.connect().escape(val)\n elif type(val) is int:\n value = str(val)\n elif type(val) is bool:\n value = str(val).upper()\n # Add the necessary text.\n sql += field\n vals += value\n # If this is not the last key, add a comma.\n if i < len(key_list) - 1:\n sql += \", \"\n vals += \", \"\n\n # Finish off the command.\n sql += \") VALUES (\" + vals + \")\"\n\n if self.verbose:\n print(\"Adding: \" + sql)\n\n return sql", "def insert_data(self, data:dict,):\n \n assert(isinstance(data, dict))\n field, value = \"\", \"\"\n for key in data.keys():\n field += key + ', '\n value += ':' + key + ', '\n \n field = field[:-2]\n value = value[:-2]\n sql_query = \"\"\"INSERT INTO %s (%s) VALUES(%s)\"\"\"%(self.db, field, value)\n self.conn.execute(sql_query, data)\n self.conn.commit()", "def insert_with_check_foreignkey(table, *fields):\n fkeys = []\n for fkey in table.foreign_keys:\n if fkey.parent.name in fields:\n fkeys.append(fkey)\n sql = [\"INSERT INTO %s \" % table.name]\n sql.append(\"(\" + \",\".join(fields) + \") \")\n if fkeys:\n sql.append(\"SELECT \" + \",\".join(\":%s AS %s\" % (f, f) for f in fields) + \" \")\n sql.append(\"FROM \" + \",\".join(fk.column.table.name for fk in fkeys) + \" \")\n sql.append(\"WHERE \" + \" AND \".join(\"%s=:%s\" % (str(fk.column), fk.parent.name) for fk in fkeys) + \";\")\n else:\n sql.append(\"VALUES (\" + \",\".join(\":%s\" % f for f in fields) + \");\")\n return text(\n \"\".join(sql)\n ).bindparams(\n *[bindparam(f, table.columns[f].type) for f in fields]\n )", "def insert(self, df, table, schema):\r\n df.to_sql(table, self.engine, schema=schema,\r\n if_exists=\"append\", index=False, chunksize=1000)", "def insert_rows(self, rows: list, table: object) -> int:\n raise NotImplementedError", "def insertValue(table, columnName, value, idcolunmName, id):\n\tcursor.execute(\"Select * from %s LIMIT 0\" %(table))\n\tcolnames = [desc[0] for desc in cursor.description]\n\tif columnName in colnames:\n\t\tcursor.execute(\"Update %s set %s = %s where %s = %s\" %(table, columnName, value,idcolunmName,id))\n\t\tconn.commit()", "def insert_many(self, table, **values):\n if len(values) < 1:\n # TODO: raise exception here instead of just returning\n return \n if len(values) == 1:\n self.insert(values[0])\n return\n placeholder = \",\".join([\"?\" for _ in values[0]])\n print(f\"INSERT INTO {table} VALUES {placeholder} {values}\")\n self.__cursor.executemany(f\"INSERT INTO {table} VALUES ({placeholder})\", values)\n self.__connection.commit()" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates rows within a table, when given a where clause with the fields given.
def update(self, table, where, fields): whereClasues = ' AND '.join(where) _resolvedFields = [] for key in fields.keys(): _resolvedFields.append(key + " = '" + fields[key] + "'") _resolvedFieldsToStr = ', '.join(_resolvedFields) return self.query("UPDATE {} SET {} {}", (_resolvedFieldsToStr, ((" WHERE " + whereClasues) if len(where) != 0 else "")), table)
[ "def update_data(self, table_name,\n updated_fields,\n updated_values,\n condition_fields,\n condition_values):\n s = [\"{0}={1}\".format(f, v) for f,v in zip(updated_fields, updated_values)]\n update_str = \",\".join(s)\n s = [\"{0}={1}\".format(f, v) for f,v in zip(condition_fields, condition_values)]\n condition_str = \" AND \".join(s)\n sql_command = \"\"\" UPDATE {0}\n SET {1}\n WHERE {2}\n \"\"\".format(table_name, update_str, condition_str)\n log.debug(\"Updating %s: %s\",table_name, sql_command)\n self.execute(sql_command)\n self.commit()", "def update(self, tables, where, vars=None, _test=False, **values):\n if vars is None: vars = {}\n where = self._where(where, vars)\n\n query = (\"UPDATE \" + sqllist(tables) + \" SET \" + sqlwhere(values, ', ')\n + \" WHERE \" + where)\n\n if _test: return query\n\n db_cursor = self._db_cursor()\n self._db_execute(db_cursor, query)\n if not self.ctx.transactions:\n self.ctx.commit()\n return db_cursor.rowcount", "def update(self, fields, cond=None, doc_ids=None):\n if callable(fields):\n return self._process_docs(\n lambda data, doc_id: fields(data[doc_id]),\n cond, doc_ids\n )\n else:\n return self._process_docs(\n lambda data, doc_id: data[doc_id].update(fields),\n cond, doc_ids\n )", "def update(self, sql):", "def UpdateQuery(self, data, table, where, delayed=None):\n sql = \"UPDATE \"\n\n if delayed:\n sql += \"DELAYED \"\n\n sql += table + \" SET \"\n\n sets = []\n for k, v in data.iteritems():\n sets.append(self.FieldClause(k, v))\n\n sql += \", \".join(sets)\n sql += \" WHERE \" + self.WhereClause(where)\n\n return sql", "def test_update_no_params(self, values, twotable):\n\n table1 = self.tables.mytable\n table2 = self.tables.myothertable\n\n stmt = table1.update().where(table1.c.name == \"jill\")\n if twotable:\n stmt = stmt.where(table2.c.otherid == table1.c.myid)\n\n if values.blank:\n stmt = stmt.values()\n\n if twotable:\n if values.blank:\n self.assert_compile(\n stmt,\n \"UPDATE mytable SET FROM myothertable \"\n \"WHERE mytable.name = :name_1 \"\n \"AND myothertable.otherid = mytable.myid\",\n )\n elif values.none:\n self.assert_compile(\n stmt,\n \"UPDATE mytable SET myid=:myid, name=:name, \"\n \"description=:description FROM myothertable \"\n \"WHERE mytable.name = :name_1 \"\n \"AND myothertable.otherid = mytable.myid\",\n )\n elif values.blank:\n self.assert_compile(\n stmt,\n \"UPDATE mytable SET WHERE mytable.name = :name_1\",\n )\n elif values.none:\n self.assert_compile(\n stmt,\n \"UPDATE mytable SET myid=:myid, name=:name, \"\n \"description=:description WHERE mytable.name = :name_1\",\n )", "def __update(self, update_criteria, con, where_criteria=None):\n if where_criteria:\n assert isinstance(where_criteria, Criteria.Criteria)\n else:\n pk = self.getPrimaryKey(update_criteria)\n\n where_criteria = Criteria.Criteria( self.getProofInstance(),\n db_name = self.getDBName(),\n logger = self.getLogger() )\n if pk and update_criteria.has_key(pk.getFullyQualifiedName()):\n where_criteria[pk.getFullyQualifiedName()] = \\\n update_criteria.remove(pk.getFullyQualifiedName())\n\n if len(where_criteria) == 0:\n raise ProofException.ProofImproperUseException( \\\n \"No where clause in %s.doUpdate.\" % (self.__class__.__name__) )\n\n results = {}\n\n db_map = self.__proof.getDatabaseMap(self.__db_name)\n adapter = self.__proof.getAdapter(self.__db_name)\n sql_expr = SQLExpression.SQLExpression()\n \n tables = UniqueList.UniqueList()\n for k in where_criteria.keys():\n tables.append(where_criteria.getTableName(k))\n\n for table in tables:\n table_map = db_map.getTable(table)\n column_maps = table_map.getColumns()\n\n where_clause = UniqueList.UniqueList()\n column_list = []\n value_list = []\n for column_map in column_maps:\n k = column_map.getFullyQualifiedName()\n if where_criteria.has_key(k):\n if where_criteria.getComparison(k) == SQLConstants.CUSTOM:\n where_clause.append(where_criteria[k])\n else:\n where_clause.append( sql_expr.build(\n column_map.getColumnName(),\n where_criteria.getValue(k),\n where_criteria.getComparison(k),\n where_criteria.isIgnoreCase(),\n adapter ) )\n \n # build set clause using buildInsertList method\n if update_criteria.has_key(k):\n column_list.append(k)\n value_list.append(update_criteria[k])\n \n (column_list, value_list) = sql_expr.buildInsertList(column_list, value_list)\n\n set_clause = UniqueList.UniqueList()\n for column, value in zip(column_list, value_list):\n set_clause.append(\"%s=%s\" % (column, value))\n\n set_str = string.join(set_clause, \", \")\n where_str = string.join(where_clause, SQLConstants.AND)\n \n sql = \"UPDATE %s set %s WHERE %s\" % (table, set_str, where_str)\n\n self.log(\"%s.doUpdate: %s\" % (self.__class__.__name__, sql))\n \n results[table] = self.__execute(sql, con)\n\n return results", "def filter_and_update(cls, filter_args=None, updated_args=None):\n res = db.session.query(cls).filter_by(**filter_args).update(updated_args)\n db.session.commit()\n return res", "def update_row(self, row_index, values):\n\n pass", "def update_row(table_name: str,\n old_value: dict[str: Union[str, int, float, bool, dict]],\n new_value: dict[str: Union[str, int, float, bool, dict]]):\n\n command = f\"\"\"UPDATE \"{table_name}\"\n SET {list(old_value.keys())[0]} = '{list(new_value.values())[0]}'\n WHERE {list(new_value.keys())[0]} = '{list(old_value.values())[0]}'\n ;\"\"\"\n\n execute_sql(command)", "def update(self, row: RowType) -> None:\n with self.connect() as db:\n res = db.execute(\n f'UPDATE {self.name} '\n f'SET {fields_to_update_str(self.field_names)} '\n f'WHERE {fields_to_search_str(self.primary_keys)}',\n row._asdict(),\n )\n if res.rowcount > 1:\n raise ValueError('Updated more than one row!')\n elif res.rowcount == 0:\n res = db.execute(\n f'INSERT INTO {self.name} VALUES '\n f'({fields_to_insert_str(self.field_names)})',\n row._asdict(),\n )\n\n self.all.cache_clear()\n self.get.cache_clear()", "def by_id(\n cls, id_: int, table: Table, update_values: Mapping, extra_filters: Filters = None\n ) -> 'UpdateQuery':\n extra_filters = extra_filters or []\n return UpdateQuery(table, update_values, [table.c.id == id_, *extra_filters])", "def update_stored_data(self, the_model, rows):\n for row in rows:\n filter_dict = {self.config['timefield_default']: row[self.config['timefield_default']]}\n if self.flight:\n filter_dict['flight'] = self.flight\n found = the_model.objects.filter(**filter_dict)\n if found.count() != 1:\n print \"ERROR: DID NOT FIND MATCH FOR %s\" % str(row[self.config['timefield_default']])\n else:\n item = found[0]\n for key, value in row.iteritems():\n setattr(item, key, value)\n print 'UPDATED: %s ' % str(item)\n item.save()", "def db_update(session, cls, value, filterby):\n return session.query(cls).filter_by(**filterby).update(value)", "def pg_bulk_update(model, filter_name, update_name,\n filter_column_data, update_column_data, cursor=None):\n cursor = cursor or con.cursor()\n # Get table name and column name for filter and update attributes as\n # stored in database.\n db_table = model._meta.db_table\n model_filter = model._meta.get_field(filter_name).column\n model_update = model._meta.get_field(update_name).column\n # Auto-convert tuples to lists.\n if type(filter_column_data) is tuple:\n filter_column_data = list(filter_column_data)\n if type(update_column_data) is tuple:\n update_column_data = list(update_column_data)\n # Input data as Django sanitized parameters,\n cursor.execute(\n \"UPDATE \" + db_table +\n \" SET \" + model_update + \" = input.update\" +\n \" FROM (SELECT unnest(%s), unnest(%s)) AS input (filter, update)\"\n \" WHERE \" + model_filter + \" = input.filter;\", [filter_column_data,\n update_column_data])\n cursor.execute(\"COMMIT;\")", "def update_record(self, name, new_data, condition, update_only=False,\n debug=False):\n # add numeric index column temporarily\n self.df['num'] = range(len(self.df))\n df_data = self.df\n # edit first of existing data that meets condition\n if len(df_data[condition]) > 0: #we have one or more records to update or delete\n condition2 = df_data.index == name\n # list of all rows where condition is true and index == name\n inds = df_data[condition & condition2]['num']\n #inds = df_data[condition]['num'] # list of all rows where condition is true\n existing_data = dict(df_data.iloc[inds[0]]) # get first record of existing_data from dataframe\n existing_data.update(new_data) # update existing data with new interpretations\n # update row\n self.update_row(inds[0], existing_data)\n # now remove all the remaining records of same condition\n if len(inds) > 1:\n for ind in inds[1:]:\n print \"deleting redundant records for:\", name\n df_data = self.delete_row(ind)\n else:\n if update_only:\n print \"no record found for that condition, not updating \", name\n else:\n print 'no record found - creating new one for ', name\n # add new row\n df_data = self.add_row(name, new_data)\n # sort so that all rows for an item are together\n df_data.sort_index(inplace=True)\n # redo temporary index\n df_data['num'] = range(len(df_data))\n self.df = df_data\n return df_data", "def updateRecords(self, template, condition):\n # get the table\n table = template.pyre_layout\n # build the tuple of affected fields and their values\n names = []\n values = []\n # iterate over all the fields\n for field in table.pyre_fields:\n # get the corresponding name from {template}\n name = field.name\n # and the value\n value = getattr(template, name)\n # skip values set to {None}\n if value is None: continue\n\n # handle 'NULL'\n if value is table.null: value = 'NULL'\n # handle 'DEFAULT'\n elif value is table.default: value = 'DEFAULT'\n # this pair needs an update\n names.append(name)\n values.append(field.sql(value))\n\n # render the names\n names = \"(\" + \", \".join(names) + \")\"\n values = \"(\" + \", \".join(values) + \")\"\n\n # initiate the statement\n yield self.place(\"UPDATE {}\".format(table.pyre_name))\n # indent\n self.indent()\n # the data section\n yield self.place(\"SET\")\n # indent\n self.indent()\n # render the assignments\n yield self.place(\"{} = {}\".format(names, values))\n # outdent\n self.outdent()\n # build the filtering expression\n predicate = self.expression(root=condition, context=table)\n # and render it\n yield self.place(\"WHERE ({});\".format(predicate))\n # outdent\n self.outdent()\n # and return\n return", "def update_record(conn, data):\n\n query = \"\"\" UPDATE person\n SET serial_num = ?,\n fname = ?,\n lname = ?,\n birth_date = ?,\n identification_num = ?,\n street = ?,\n city = ?,\n postcode_num = ?,\n phone_num = ?,\n note = ?\n WHERE id = ? \"\"\"\n c = conn.cursor()\n c.execute(query, data)\n conn.commit()\n\n print(f\"SQL: Record UPDATED with id={data[-1]}\")", "def _to_update_query(table_name, id_column, id_, etag, key_values) -> (str, list):\n sets = []\n values = []\n for k, v in key_values.items():\n sets.append(f\"{k}=%s\")\n values.append(v)\n\n update = \", \".join(sets)\n values.append(id_)\n\n sql = f\"UPDATE {table_name} SET {update} WHERE {id_column}=%s\"\n if etag:\n sql += \" AND str_etag=%s\"\n values.append(etag)\n\n return sql, values" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if a Schema Exists within the targeted Database.
def checkIfSchemaExists(self, name): result = self.query( """ SELECT EXISTS( SELECT schema_name FROM information_schema.schemata WHERE schema_name = {} ); """, (name)) value = str(result[0]).replace("(", "").replace(")", "").replace(",", "") return True if 'true' in value.lower() else False
[ "def checkExistence_DB(self):\n DBlist = self.client.list_database_names()\n if self.DB_NAME in DBlist:\n # print(f\"DB: '{self.DB_NAME}' exists\")\n return True\n # print(f\"DB: '{self.DB_NAME}' not yet present OR no collection is present in the DB\")\n return False", "def database_exists(self, db):\n return db in self.list_database()", "def valid_database_exists(self):\n if self._valid_database_exists is None:\n self.refresh_db_valid_from()\n return self._valid_database_exists", "def check_schemas(table_metadata: TableMetadata) -> TableMetadata:\n current_schema_id = table_metadata.current_schema_id\n\n for schema in table_metadata.schemas:\n if schema.schema_id == current_schema_id:\n return table_metadata\n\n raise ValidationError(f\"current-schema-id {current_schema_id} can't be found in the schemas\")", "def db_exists(self):\r\n return self.func.file_exists(self.conf[\"path_to_database\"])", "def _check_db_exists(db, cursor):\n cursor.execute('SELECT datname FROM pg_database')\n # It's a list of tuple, so just create the tuple to check if exists\n return (db,) in cursor.fetchall()", "def table_exists(self, table_name, schema='public'):\r\n sql = \"SELECT EXISTS(SELECT * FROM information_schema.tables WHERE table_name ='%s' AND table_schema = '%s' );\" %(table_name,schema)\r\n return self.engine.execute(sql)[0]['exists']", "def table_exists(self):\n query = \"\"\"select name from sqlite_master \\\n where type='table' and name='%s' \"\"\" % self.table_name\n result = self.conn.execute(query)\n return result.fetchone() != None", "def _create_schema(self):\n\n try:\n with DBContext(self) as db:\n if db.error:\n return db.error\n\n cfg = config.Config()\n cfg.set_main_option(\"script_location\", self.migration_root)\n cfg.attributes[\"connection\"] = db.connection\n\n mcontext = migration.MigrationContext.configure(db.connection)\n database_schema_revision = mcontext.get_current_revision()\n LOG.debug('Schema revision in the database: ' +\n str(database_schema_revision))\n\n if database_schema_revision:\n LOG.debug('Database schema was found.'\n ' No need to initialize new.')\n else:\n LOG.debug('No schema was detected in the database.')\n LOG.debug('Initializing new ...')\n command.upgrade(cfg, \"head\")\n db.session.commit()\n LOG.debug('Done.')\n return True\n\n return True\n\n except sqlalchemy.exc.SQLAlchemyError as alch_err:\n LOG.error(str(alch_err))\n return False\n\n except Exception as ex:\n LOG.error(\"Failed to create initial database schema\")\n LOG.error(ex)\n return False", "def has_database(self, name=''):\n\n try:\n database = self._conn.database(name)\n database.properties()\n except exceptions.DatabasePropertiesError:\n return False\n else:\n return True", "def check_db(self):\n if not os.path.exists(self.db_base_path):\n raise DatabaseDoesNotExist", "def check_schema(self):\n\n try:\n with DBContext(self) as db:\n if db.error:\n return db.error\n\n cfg = config.Config()\n cfg.set_main_option(\"script_location\", self.migration_root)\n cfg.attributes[\"connection\"] = db.connection\n\n scriptt = script.ScriptDirectory.from_config(cfg)\n mcontext = migration.MigrationContext.configure(\n db.connection)\n database_schema_revision = mcontext.get_current_revision()\n LOG.debug(\"Schema revision in the database: %s\",\n str(database_schema_revision))\n\n if database_schema_revision is None:\n LOG.debug(\"Database schema should have been created!\")\n return DBStatus.SCHEMA_MISSING\n\n LOG.debug(\"Checking schema versions in the package.\")\n schema_config_head = scriptt.get_current_head()\n\n if database_schema_revision != schema_config_head:\n LOG.debug(\"Database schema mismatch detected \"\n \"between the package and the database\")\n LOG.debug(\"Checking if automatic upgrade is possible.\")\n all_revs = [rev.revision for rev in\n scriptt.walk_revisions()]\n\n if database_schema_revision not in all_revs:\n LOG.debug(\"Automatic schema upgrade is not possible!\")\n LOG.debug(\"Please re-check your database and\"\n \"CodeChecker versions!\")\n return DBStatus.SCHEMA_MISMATCH_NO\n\n # There is a schema mismatch.\n return DBStatus.SCHEMA_MISMATCH_OK\n else:\n LOG.debug(\"Schema in the package and\"\n \" in the database is the same.\")\n LOG.debug(\"No schema modification is needed.\")\n return DBStatus.OK\n\n except sqlalchemy.exc.SQLAlchemyError as alch_err:\n LOG.debug(str(alch_err))\n return DBStatus.FAILED_TO_CONNECT\n except CommandError as cerr:\n LOG.debug(\"Database schema and CodeChecker is incompatible. \"\n \"Please update CodeChecker.\")\n LOG.debug(str(cerr))\n return DBStatus.SCHEMA_MISMATCH_NO", "def environment_needs_upgrade(self, db):\n if self.env.config.get('trac', 'database').startswith('postgres'):\n found_version = self._check_schema_version(db)\n if not found_version:\n self.log.debug(\"Initial schema needed for businessintelligence plugin for views\")\n return True\n else:\n if found_version < self._schema_version:\n self.log.debug(\"Upgrade schema from %d to %d needed for businessintelligence plugin for view table\",\n found_version,\n self._schema_version)\n return True\n return False", "def database_exists():\n # Check that the database file exists. #\n expected_db_name = 'pokemon.db'\n expected_db_abspath = os.path.abspath(os.path.join(\n os.path.dirname(__file__),\n expected_db_name\n ))\n\n return os.path.exists(expected_db_abspath)", "def table_exists(table, conn):\n result = conn.execute('select name from sqlite_master where name=?', \\\n (table,))\n return not (not result.fetchall()) #False if does not exist, True otherwise", "def cli_cosmosdb_sql_database_exists(client,\n resource_group_name,\n account_name,\n database_name):\n try:\n client.get_sql_database(resource_group_name, account_name, database_name)\n except HttpResponseError as ex:\n return _handle_exists_exception(ex)\n\n return True", "def checkSchema(dbversion, verbose=False):\n\n dbschema = dumpCurrentSchema(verbose)\n\n # Find current schema\n fp = FilePath(SCHEMADIR)\n fpschema = fp.child(\"old\").child(\"postgres-dialect\").child(\"v{}.sql\".format(dbversion))\n if not fpschema.exists():\n fpschema = fp.child(\"current.sql\")\n expectedSchema = schemaFromPath(fpschema)\n\n mismatched = dbschema.compare(expectedSchema)\n if mismatched:\n print(\"\\nCurrent schema in database is mismatched:\\n\\n\" + \"\\n\".join(mismatched))\n else:\n print(\"\\nCurrent schema in database is a match to the expected server version\")", "def table_exists(self, table_name):\n cursor = self._db_conn.cursor()\n exists = False\n\n #Check for the table\n cursor.execute('''SELECT name FROM sqlite_master WHERE type='table' AND name='?';'''),table_name\n\n if cursor.rowcount > 0:\n exists = True\n\n return exists", "def test_check_schema_schema(schema):\n returned_schema, _ = column.check_schema(schema=copy.deepcopy(schema))\n\n assert returned_schema == schema" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the Debugger Mode. (Enabled) will display all the SQL Commands within the console.
def setDebugMode(self, debugMode): self.debug = debugMode
[ "def set_debug_mode(self, mode):\n self._debug_mode = mode\n self.config.debug = mode", "def set_debug(cls, on=True):\n cls.debug = on", "def setDebugMode(self, debug):\n return _core.CGPkronSum_setDebugMode(self, debug)", "def SetDebugMode(self, debug):\n self.config.set(\"Settings\", \"debug_mode\", debug, write=True)\n self.debug_mode = misc.to_bool(debug)\n self.wifi.debug = debug\n self.wired.debug = debug\n self.wireless_bus.debug_mode = debug\n self.wired_bus.debug_mode = debug", "def set_debug_on():\n global _debug\n _debug = True\n print 'Debug on.'", "def setDebug(cls, isDebug):\n \n cls.isDebug = isDebug", "def cmd_debug(self):\r\n self.log.setLevel(logging.DEBUG)\r\n self.log.debug('Switching to DEBUG threshold')", "def debug_enable(self) -> bool:\n return pulumi.get(self, \"debug_enable\")", "def toggle_debug():\n global DEBUG\n if DEBUG:\n DEBUG = False\n print(\"debug disabled\")\n else:\n DEBUG = True\n print(\"debug enabled\")", "def on_runDebugMenuItem_activate(self,*args):\n self.run_mode = \"Debug\"\n self.set_run_menu(running=True,status=\"Debugging...\",debug=True)\n self._ui.interpreter = piedit.interpreter.Interpreter()\n self._ui.interpreter.debug.DEBUG = True\n self._ui.interpreter.run_program(pixels=self._ui.pixels,width=self._ui.width,height=self._ui.height,start=False)\n self._ui.highlight_pixel(0,0)", "def enable_debug_mode(self, flag):\n if flag:\n self._policy = _DebugContextPolicy()\n else:\n self._policy = _OptimizedContextPolicy()", "def setDebug(debug: bool = False) -> None:\n if debug:\n debugFlag = True\n else:\n debugFlag = False", "def setDebugging(on: bool) -> None:\n Deferred.debug = bool(on)", "def debug(self, value):\n self._debug = bool(value)\n self.serial_device.setDebug(value)", "def debug(self, text):\n if self.args.debug:\n self.console(text).nl()", "def debug(self, value):\n for driver in self.drivers:\n driver.debug = value", "def setGDB(cls, isGDB):\n \n cls.isGDB = isGDB", "def set_debug_off():\n global _debug\n _debug = False\n print 'Debug off.'", "def devmode(cmd, params, p, arena):\n\tif not hasattr(p, 'devmode'): p.devmode = True\n\telif p.devmode: p.devmode = False\n\telse: p.devmode = True" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the amount of rows that were affected by the last Execution.
def getAffectedRowsCount(self): return self.affectedRows
[ "def rowcount(self):\n self._check_that_read_query_was_issued()\n return self._delegate.rowcount", "def _get_rowCount(self) -> \"int\" :\n return _core.TableCommandInput__get_rowCount(self)", "def total_rows_count(self) -> int:\n return pulumi.get(self, \"total_rows_count\")", "def get_num_rows(self):\r\n return len(self.rows)", "def row_count(self):\n return len(self._table)", "def row_count(self):\n with self._conn.cursor() as cursor:\n cursor.execute('SELECT COUNT(*) FROM {0}'.format(self._import_relation_name))\n return cursor.fetchone()[0]", "def NumRows(self):\n return _handle.OperatorHandle_NumRows(self)", "def table_est_row_count():\n query_est_row_count(current_app.extensions['sqlalchemy'].db)", "def getNoOfRows(self):\n if self.query.exec_(\"SELECT * FROM dictin\"):\n i = 0\n while self.query.next():\n i = i + 1\n\n return i", "def row_count(self, selectStatement, **named_args):\n return len(self.query(selectStatement, **named_args))", "def get_num_updates(self):\n return 0", "def num_updates(self):\n return self.parameter_server.num_updates()", "def numRows(self) -> int:\n return self._java_matrix_wrapper.call(\"numRows\")", "def count(self):\n info = self.describe()\n return info['Table'].get('ItemCount', 0)", "def getTxCount(self):\n\t\tquery = 'SELECT * from transactions ORDER BY id DESC LIMIT 1'\n\t\tself.executeQuery(query)\n\t\trawTransaction = self.fetchOne()\n\t\treturn rawTransaction[0]", "def get_queryLength(self): \n results = self.generateQuery()\n return len(results)", "def countUndo(self):\n return self.index", "def getLineCount( self ):\n return len( self.lines )", "def getOutputCount(self):\n\t\tquery = 'SELECT * from outputs ORDER BY id DESC LIMIT 1'\n\t\tself.executeQuery(query)\n\t\trawOutput = self.fetchOne()\n\t\treturn rawOutput[0]" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the ID of the last Row in the last Execution.
def getLastRowID(self): return self.lastRowID
[ "def lastrowid(self):\n if self._last is not None:\n return self._last\n with self._statement.getGeneratedKeys() as rs:\n if rs.isClosed():\n return self._last\n last = []\n while rs.next():\n last.append(rs.getLong(1))\n if len(last) == 0:\n return None\n if len(last) == 1:\n self._last = last[0]\n return last[0]\n self._last = last\n return last", "def lastrowid(self):\n try:\n return self.context.get_lastrowid()\n except BaseException as e:\n self.connection._handle_dbapi_exception(\n e, None, None, self.cursor, self.context\n )", "def lastrowid(self):\n try:\n return self.context.get_lastrowid()\n except BaseException as e:\n self.cursor_strategy.handle_exception(self, self.cursor, e)", "def getLastIdBaseline(self):\n try:\n cursor = self.db.cursor()\n sql = \"SELECT MAX(id) FROM baseline;\"\n cursor.execute(sql)\n resultset = cursor.fetchall()\n return resultset\n except:\n return \"Error!\"", "def get_dataset_last_record_id(self):\n offset = int(self.get_dataset_total_count()) - 1\n return self.get_dataset_record_by_limit_offset_order(limit=1, offset=offset, order=\"record_id\")", "def get_dataset_last_row(self):\n df = self.get_dataset()\n# row_num = len(df)\n return df[-1:]", "def get_last_id(self):\n\n return self._last_id", "def last_job_id(self):\n return self._last_job_id", "def last_task_id(self) -> pulumi.Output[str]:\n return pulumi.get(self, \"last_task_id\")", "def get_last_id(self):\n last_id = 0\n for task in self.tasks:\n if not task.id is None and task.id > last_id:\n last_id = task.id\n return last_id", "def get_next_row_id(self):\n if len(self.deleted_row_ids) > 0:\n # is there an existing deleted row?\n rowid = self.deleted_row_ids.pop()\n else:\n rowid = len(self.tuples)\n # append an empty row\n self.tuples.append([])\n return rowid", "def get_indicator_last_row(self):\n indi = self.get_indicator()\n return indi[-1:]", "def get_last_processed_id(connection):\n query = 'select id from last_processed_id;'\n res = connection.execute(text(query)).fetchall()\n if res:\n first_id = res[-1][0]\n else:\n query = 'select id from public.raw_data limit 1'\n res = connection.execute(text(query)).fetchall()\n if not res:\n raise Exception('Tables last_processed_id and raw_data is empty, run fill_db.py !')\n first_id = res[0][0]\n\n print('first_id', first_id)\n return first_id", "def last_id(cls):\r\n sql = \"SELECT MAX(id) FROM hive_posts WHERE counter_deleted = 0\"\r\n return DB.query_one(sql) or 0", "def GetLast(self):\n return _TColStd.TColStd_ListOfInteger_GetLast(self)", "def getmaxRow( self ):\n\n return self.maxRow -1", "def get_last_transaction_id():\n try:\n last_id = models.AccountTransaction.objects.latest().transaction_id\n except models.AccountTransaction.DoesNotExist:\n last_id = 0\n # last_id = 14462590267\n return last_id", "def last(self):\n return int(self._end)", "def get_last_line(self):\n if self._last_line == 0 and self._ast_elem_list != []:\n self._last_line = self._ast_elem_list[-1].coord.line\n\n return self._last_line" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run srw in ``cfg_dir`` The files in ``cfg_dir`` must be configured properly.
def run(cfg_dir): with pkio.save_chdir(cfg_dir): _run_elegant()
[ "def run_srun():\n import sys\n import subprocess\n from batchSettings import independent_srun_args\n script_name = sys.argv[0]\n args = independent_srun_args + [\"python\", script_name, \"all\"]\n logging.debug(\"Calling srun with the following arguments: %s\", args)\n subprocess.run([\"srun\"] + args)", "def run_config(conf):\n global loggers # contains the created Syslogger objects\n\n def handle_dir(path):\n \"\"\"Get the config options and create the DirSyslogger.\"\"\"\n t = DirSyslogger(path,\n config.get(path, \"filetypes\").split(','),\n config.get(path, \"interval\"),\n config.get(path, \"backlog\"))\n loggers.append(t)\n\n def handle_file(path):\n \"\"\"Get the config options and create the FileSyslogger.\"\"\"\n if not config.has_option(path, \"mode\"):\n raise ConfigError(path, \"no mode option configured\")\n mode = config.get(path, \"mode\")\n if mode == \"trace\" or mode == \"t\": mode = 't'\n elif mode == \"one-time\" or mode == \"o\": mode = 'o'\n else: raise ConfigError(path, \"invalid mode given: \" + mode)\n t = FileSyslogger(path, mode)\n loggers.append(t)\n\n loggers = []\n config = ConfigParser.SafeConfigParser({'filetypes':'',\n 'interval':0,\n 'backlog':'7d'})\n config.read(conf)\n for sec in config.sections():\n if os.path.isdir(sec):\n handle_dir(sec)\n elif os.path.isfile(sec):\n handle_file(sec)\n else: raise ConfigError(sec, \"not a file or directory\")\n try:\n while True:\n for logger in loggers:\n logger.run()\n except KeyboardInterrupt:\n print \"interrupt received. exiting...\"", "def do_config(rolename):\n if os.geteuid() != 0:\n logging.critical('Restart operation requires root privileges, re-run with \"su\"')\n return\n\n if rolename not in CONFIG['roles']:\n logging.critical('Does not know how to configure role: %s', CONFIG['role'])\n return\n\n hooks = CONFIG['roles'][rolename]['hooks']\n services = CONFIG['roles'][rolename]['services']\n\n if hasattr(hooks, 'before_config'):\n logging.debug('Executing role-specific perparation steps')\n hooks.before_config()\n\n logging.info('Updating configuration files')\n source_prefix = CONFIG['roles'][rolename]['root']\n for dirpath, dirs, files in os.walk(source_prefix):\n target_prefix = dirpath[len(source_prefix):]\n if not target_prefix:\n target_prefix = '/'\n for dname in dirs:\n target_dir = os.path.join(target_prefix, dname)\n if not os.path.isdir(target_dir):\n os.makedirs(target_dir)\n logging.debug(\"Creating missing configuration directory: %s\", target_dir)\n for fname in files:\n source_file = os.path.join(dirpath, fname)\n target_file = os.path.join(target_prefix, fname)\n logging.debug(\"Overwriting configuration file: %s\", target_file)\n with open(source_file, 'rb') as sf, open(target_file, 'wb') as tf:\n tf.write(sf.read())\n\n logging.info('Enabling services')\n for service_status, service_name in services:\n with open(os.devnull, 'wb') as hide_output:\n if service_status == '+':\n logging.debug('Enable service: %s', service_name)\n exit_code = subprocess.Popen(['systemctl', 'enable', service_name],\n stdout=hide_output, stderr=hide_output).wait()\n if exit_code != 0:\n logging.warning(\"Service %s cannot be enabled\", service_name)\n else:\n logging.debug('Disable service: %s', service_name)\n exit_code = subprocess.Popen(['systemctl', 'disable', service_name],\n stdout=hide_output, stderr=hide_output).wait()\n if exit_code != 0:\n logging.warning(\"Service %s cannot be disabled (should not be enabled)\", service_name)\n\n if hasattr(hooks, 'after_config'):\n logging.debug('Executing role-specific finishing steps')\n hooks.after_config()\n\n CONFIG['role'] = rolename\n with open(CURRENT_ROLE_PATH, 'w') as f_role:\n f_role.write(rolename)\n\n do_restart()", "def write_out_config():\n rdebug('about to write out the /etc/storpool.conf file')\n spstatus.npset('maintenance', 'updating the /etc/storpool.conf file')\n with tempfile.NamedTemporaryFile(dir='/tmp',\n mode='w+t',\n delete=True) as spconf:\n rdebug('about to write the contents to the temporary file {sp}'\n .format(sp=spconf.name))\n templating.render(source='storpool.conf',\n target=spconf.name,\n owner='root',\n perms=0o600,\n context={\n 'storpool_conf': spconfig.m()['storpool_conf'],\n },\n )\n rdebug('about to invoke txn install')\n txn.install('-o', 'root', '-g', 'root', '-m', '644', '--',\n spconf.name, '/etc/storpool.conf')\n rdebug('it seems that /etc/storpool.conf has been created')\n\n rdebug('trying to read it now')\n spconfig.drop_cache()\n cfg = spconfig.get_dict()\n oid = cfg['SP_OURID']\n spconfig.set_our_id(oid)\n rdebug('got {len} keys in the StorPool config, our id is {oid}'\n .format(len=len(cfg), oid=oid))\n\n rdebug('setting the config-written state')\n reactive.set_state('l-storpool-config.config-written')\n spstatus.npset('maintenance', '')", "def start_temp_run_script(configs, opts, run_dir, output_dir, input_fname):\n script = []\n \n script.append('# create directory structure')\n script.append('rundir={}'.format(run_dir))\n script.append('outdir={}'.format(output_dir))\n script.append('mkdir -p $rundir $rundir/Plots $rundir/Data $rundir/Scripts || {')\n script.append(' # failure')\n script.append(' echo \"ERROR: unable to create directory $rundir/ and subdirectories\"')\n script.append(' echo \"Do you have the correct permissions?\"')\n script.append(' echo \"\"')\n script.append(' exit 1')\n script.append('}')\n script.append('')\n \n script.append('# copy inputs and the program')\n script.append('rsync --progress -zvhL {} $rundir/ 2> /dev/null'.format(input_fname))\n script.append('rsync --progress -zvhL *_out.txt $rundir/ 2> /dev/null')\n if opts['prog_name'] == 'PB3D':\n script.append('rsync --progress -zvhL {} $rundir/'.format(opts['eq_fname']))\n if opts['prog_name'] == 'POST':\n script.append('ln -sf {} $rundir/'.format(opts['PB3D_out_fname']))\n script.append('rsync --progress -zvhL {} $rundir/'.format(os.path.join(configs['prog_dir'], opts['prog_name'])))\n script.append('chmod +x $rundir/{}'.format(opts['prog_name']))\n script.append('')\n \n script.append('# go to run directory')\n script.append('cd $rundir')\n script.append('')\n \n return script", "def updateConfig():\n if(os.path.isfile(os.path.join(os.getcwd(), \"riaps.conf\"))):\n put('riaps.conf')\n sudo('cp riaps.conf /etc/riaps/')\n sudo('chown root:root /etc/riaps/riaps.conf')\n sudo('rm riaps.conf')\n else:\n print(\"Local ./riaps.conf doesn't exist!\")", "def do_configure():\n if flag_do_fetch:\n fetch_in_volume()\n dochdir(ssdroot)\n targdir = flag_subvol\n if flag_snapshot:\n targdir = flag_snapshot\n do_configure_binutils(targdir)\n do_setup_cmake(targdir)", "def sosreport(opts):\n parse_options(opts)\n # check debug\n isDebug()\n\n config = ConfigParser.ConfigParser()\n if GlobalVars.__cmdLineOpts__.config_file:\n config_file = GlobalVars.__cmdLineOpts__.config_file\n else:\n config_file = '/etc/sos.conf'\n try:\n config.readfp(open(config_file))\n except IOError:\n pass\n\n GlobalVars.loadedplugins = deque() \n skippedplugins = deque() \n alloptions = deque() \n\n # perhaps we should automatically locate the policy module??\n GlobalVars.policy = sos.policyredhat.SosPolicy()\n\n # find the plugins path\n paths = sys.path\n for path in paths:\n if path.strip()[-len(\"site-packages\"):] == \"site-packages\" \\\n and os.path.isdir(path + \"/sos/plugins\"):\n pluginpath = path + \"/sos/plugins\"\n\n # Set up common info and create destinations\n\n GlobalVars.dstroot = GlobalVars.policy.getDstroot(GlobalVars.__cmdLineOpts__.tmp_dir)\n if not GlobalVars.dstroot:\n print _(\"Could not create temporary directory.\")\n doExit()\n\n cmddir = os.path.join(GlobalVars.dstroot, \"sos_commands\")\n logdir = os.path.join(GlobalVars.dstroot, \"sos_logs\")\n rptdir = os.path.join(GlobalVars.dstroot, \"sos_reports\")\n os.mkdir(cmddir, 0755)\n os.mkdir(logdir, 0755)\n os.mkdir(rptdir, 0755)\n\n # initialize logging\n soslog = logging.getLogger('sos')\n soslog.setLevel(logging.DEBUG)\n\n if GlobalVars.__cmdLineOpts__.profiler:\n proflog = logging.getLogger('sosprofile')\n proflog.setLevel(logging.DEBUG)\n else:\n proflog = None\n\n # limit verbosity to DEBUG\n if GlobalVars.__cmdLineOpts__.verbosity > 3:\n GlobalVars.__cmdLineOpts__.verbosity = 3 \n\n # if stdin is not a tty, disable colors and don't ask questions\n if not sys.stdin.isatty():\n GlobalVars.__cmdLineOpts__.nocolors = True\n GlobalVars.__cmdLineOpts__.batch = True\n\n # log to a file\n flog = logging.FileHandler(logdir + \"/sos.log\")\n flog.setFormatter(logging.Formatter('%(asctime)s %(levelname)s: %(message)s'))\n if GlobalVars.__cmdLineOpts__.verbosity > 0:\n # standard log levels have a step of 10\n flog.setLevel(logging.INFO - (GlobalVars.__cmdLineOpts__.verbosity * 10))\n else:\n flog.setLevel(logging.INFO)\n soslog.addHandler(flog)\n\n if GlobalVars.__cmdLineOpts__.profiler:\n # setup profile log\n plog = logging.FileHandler(logdir + \"/sosprofile.log\")\n plog.setFormatter(logging.Formatter('%(message)s'))\n plog.setLevel(logging.DEBUG)\n proflog.addHandler(plog)\n\n # define a Handler which writes INFO messages or higher to the sys.stderr\n console = logging.StreamHandler(sys.stderr)\n if GlobalVars.__cmdLineOpts__.verbosity > 0:\n # standard log levels have a step of 10\n console.setLevel(logging.WARNING - (GlobalVars.__cmdLineOpts__.verbosity * 10))\n else:\n console.setLevel(logging.WARNING)\n console.setFormatter(logging.Formatter('%(message)s'))\n soslog.addHandler(console)\n\n xmlrep = XmlReport()\n\n # set up dict so everyone can share the following\n commons = {'dstroot': GlobalVars.dstroot, 'cmddir': cmddir, 'logdir': logdir, 'rptdir': rptdir,\n 'soslog': soslog, 'proflog': proflog, 'policy': GlobalVars.policy, 'verbosity' : GlobalVars.__cmdLineOpts__.verbosity,\n 'xmlreport' : xmlrep, 'cmdlineopts':GlobalVars.__cmdLineOpts__, 'config':config }\n\n # Make policy aware of the commons\n GlobalVars.policy.setCommons(commons)\n\n print\n print _(\"sosreport (version %s)\" % (__version__,))\n print\n\n # disable plugins that we read from conf files\n conf_disable_plugins_list = deque() \n conf_disable_plugins = None\n if config.has_option(\"plugins\", \"disable\"):\n conf_disable_plugins = config.get(\"plugins\", \"disable\").split(',')\n for item in conf_disable_plugins:\n conf_disable_plugins_list.append(item.strip())\n\n # generate list of available plugins\n plugins = os.listdir(pluginpath)\n plugins.sort()\n plugin_names = deque()\n\n # validate and load plugins\n for plug in plugins:\n plugbase = plug[:-3]\n if not plug[-3:] == '.py' or plugbase == \"__init__\":\n continue\n try:\n if GlobalVars.policy.validatePlugin(pluginpath + plug):\n pluginClass = importPlugin(\"sos.plugins.\" + plugbase, plugbase)\n else:\n soslog.warning(_(\"plugin %s does not validate, skipping\") % plug)\n skippedplugins.append((plugbase, pluginClass(plugbase, commons)))\n continue\n # plug-in is valid, let's decide whether run it or not\n plugin_names.append(plugbase)\n if plugbase in GlobalVars.__cmdLineOpts__.noplugins or \\\n plugbase in conf_disable_plugins_list:\n # skipped\n skippedplugins.append((plugbase, pluginClass(plugbase, commons)))\n continue\n if not pluginClass(plugbase, commons).checkenabled() and \\\n not plugbase in GlobalVars.__cmdLineOpts__.enableplugins and \\\n not plugbase in GlobalVars.__cmdLineOpts__.onlyplugins:\n # inactive\n skippedplugins.append((plugbase, pluginClass(plugbase, commons)))\n continue\n if not pluginClass(plugbase, commons).defaultenabled() and \\\n not plugbase in GlobalVars.__cmdLineOpts__.enableplugins and \\\n not plugbase in GlobalVars.__cmdLineOpts__.onlyplugins:\n # not loaded by default\n skippedplugins.append((plugbase, pluginClass(plugbase, commons)))\n continue\n if GlobalVars.__cmdLineOpts__.onlyplugins and \\\n not plugbase in GlobalVars.__cmdLineOpts__.onlyplugins:\n # not specified\n skippedplugins.append((plugbase, pluginClass(plugbase, commons)))\n continue\n GlobalVars.loadedplugins.append((plugbase, pluginClass(plugbase, commons)))\n except:\n soslog.warning(_(\"plugin %s does not install, skipping\") % plug)\n if GlobalVars.__raisePlugins__:\n raise\n\n # First, gather and process options\n # using the options specified in the command line (if any)\n if GlobalVars.__cmdLineOpts__.usealloptions:\n for plugname, plug in GlobalVars.loadedplugins:\n for name, parms in zip(plug.optNames, plug.optParms):\n if type(parms[\"enabled\"])==bool:\n parms[\"enabled\"] = True\n del name\n\n # read plugin tunables from configuration file\n if config.has_section(\"tunables\"):\n if not GlobalVars.__cmdLineOpts__.plugopts:\n GlobalVars.__cmdLineOpts__.plugopts = deque() \n\n for opt, val in config.items(\"tunables\"):\n if not opt.split('.')[0] in conf_disable_plugins_list:\n GlobalVars.__cmdLineOpts__.plugopts.append(opt + \"=\" + val)\n\n if GlobalVars.__cmdLineOpts__.plugopts:\n opts = {}\n for opt in GlobalVars.__cmdLineOpts__.plugopts:\n # split up \"general.syslogsize=5\"\n try:\n opt, val = opt.split(\"=\")\n except:\n val = True\n else:\n if val.lower() in [\"off\", \"disable\", \"disabled\", \"false\"]:\n val = False\n else:\n # try to convert string \"val\" to int()\n try:\n val = int(val)\n except:\n pass\n\n # split up \"general.syslogsize\"\n try:\n plug, opt = opt.split(\".\")\n except:\n plug = opt\n opt = True\n\n try:\n opts[plug]\n except KeyError: \n opts[plug] = deque() \n opts[plug].append( (opt, val) )\n\n for plugname, plug in GlobalVars.loadedplugins:\n if plugname in opts:\n for opt, val in opts[plugname]:\n if not plug.setOption(opt, val):\n soslog.error('no such option \"%s\" for plugin ' \\\n '(%s)' % (opt,plugname))\n doExit(1)\n del opts[plugname]\n for plugname in opts.keys():\n soslog.error('unable to set option for disabled or non-existing ' \\\n 'plugin (%s)' % (plugname))\n # Do not want to exit on invalid opts due to a misconfiguration in sos.conf\n # doExit(1)\n del opt, opts, val\n\n # error if the user references a plugin which does not exist\n unk_plugs = [plugname.split(\".\")[0] for plugname in \\\n GlobalVars.__cmdLineOpts__.onlyplugins \\\n if not plugname.split(\".\")[0] in plugin_names]\n unk_plugs += [plugname.split(\".\")[0] for plugname in \\\n GlobalVars.__cmdLineOpts__.noplugins \\\n if not plugname.split(\".\")[0] in plugin_names]\n unk_plugs += [plugname.split(\".\")[0] for plugname in \\\n GlobalVars.__cmdLineOpts__.enableplugins \\\n if not plugname.split(\".\")[0] in plugin_names]\n if len(unk_plugs):\n for plugname in unk_plugs:\n soslog.error('a non-existing plugin (%s) was specified in the ' \\\n 'command line' % (plugname))\n doExit(1)\n del unk_plugs\n\n for plugname, plug in GlobalVars.loadedplugins:\n names, parms = plug.getAllOptions()\n for optname, optparm in zip(names, parms):\n alloptions.append((plug, plugname, optname, optparm))\n\n # when --listplugins is specified we do a dry-run\n # which tells the user which plugins are going to be enabled\n # and with what options.\n\n if GlobalVars.__cmdLineOpts__.listPlugins:\n if not len(GlobalVars.loadedplugins) and not len(skippedplugins):\n soslog.error(_(\"no valid plugins found\"))\n doExit(1)\n\n if len(GlobalVars.loadedplugins):\n print _(\"The following plugins are currently enabled:\")\n print\n for (plugname, plug) in GlobalVars.loadedplugins:\n print \" %-25s %s\" % (textcolor(plugname,\"lblue\"),\n plug.get_description())\n else:\n print _(\"No plugin enabled.\")\n print\n\n if len(skippedplugins):\n print _(\"The following plugins are currently disabled:\")\n print\n for (plugname, plugclass) in skippedplugins:\n print \" %-25s %s\" % (textcolor(plugname,\"cyan\"),\n plugclass.get_description())\n print\n\n if len(alloptions):\n print _(\"The following plugin options are available:\")\n print\n for (plug, plugname, optname, optparm) in alloptions:\n # format and colorize option value based on its type (int or bool)\n if type(optparm[\"enabled\"]) == bool:\n if optparm[\"enabled\"] == True:\n tmpopt = textcolor(\"on\",\"lred\")\n else:\n tmpopt = textcolor(\"off\",\"red\")\n elif type(optparm[\"enabled\"]) == int:\n if optparm[\"enabled\"] > 0:\n tmpopt = textcolor(optparm[\"enabled\"],\"lred\")\n else:\n tmpopt = textcolor(optparm[\"enabled\"],\"red\")\n else:\n tmpopt = optparm[\"enabled\"]\n\n print \" %-21s %-5s %s\" % (plugname + \".\" + optname,\n tmpopt, optparm[\"desc\"])\n del tmpopt\n else:\n print _(\"No plugin options available.\")\n\n print\n doExit()\n\n # to go anywhere further than listing the\n # plugins we will need root permissions.\n if os.getuid() != 0:\n print _('sosreport requires root permissions to run.')\n doExit(1)\n\n # we don't need to keep in memory plugins we are not going to use\n del skippedplugins\n\n if not len(GlobalVars.loadedplugins):\n soslog.error(_(\"no valid plugins were enabled\"))\n doExit(1)\n\n msg = _(\"\"\"This utility will collect some detailed information about the\nhardware and setup of your %(distroa)s system.\nThe information is collected and an archive is packaged under\n/tmp, which you can send to a support representative.\n%(distrob)s will use this information for diagnostic purposes ONLY\nand it will be considered confidential information.\n\nThis process may take a while to complete.\nNo changes will be made to your system.\n\n\"\"\" % {'distroa':__distro__, 'distrob':__distro__})\n\n if GlobalVars.__cmdLineOpts__.batch:\n print msg\n else:\n msg += _(\"\"\"Press ENTER to continue, or CTRL-C to quit.\\n\"\"\")\n try:\n raw_input(msg)\n except: \n print\n doExit()\n del msg\n\n if GlobalVars.__cmdLineOpts__.diagnose:\n # Call the diagnose() method for each plugin\n tmpcount = 0\n for plugname, plug in GlobalVars.loadedplugins:\n try:\n plug.diagnose()\n except:\n if GlobalVars.__raisePlugins__:\n raise\n else:\n error_log = open(logdir + \"/sosreport-plugin-errors.txt\", \"a\")\n etype, eval, etrace = sys.exc_info()\n traceback.print_exception(etype, eval, etrace, limit=2, file=sys.stdout)\n error_log.write(traceback.format_exc())\n error_log.close()\n\n tmpcount += len(plug.diagnose_msgs)\n if tmpcount > 0:\n print _(\"One or more plugins have detected a problem in your \" \\\n \"configuration.\")\n print _(\"Please review the following messages:\")\n print\n\n fp = open(rptdir + \"/diagnose.txt\", \"w\")\n for plugname, plug in GlobalVars.loadedplugins:\n for tmpcount2 in range(0, len(plug.diagnose_msgs)):\n if tmpcount2 == 0:\n soslog.warning( textcolor(\"%s:\" % plugname, \"red\") )\n soslog.warning(\" * %s\" % plug.diagnose_msgs[tmpcount2])\n fp.write(\"%s: %s\\n\" % (plugname, plug.diagnose_msgs[tmpcount2]))\n fp.close()\n\n print\n if not GlobalVars.__cmdLineOpts__.batch:\n try:\n while True:\n yorno = raw_input( _(\"Are you sure you would like to \" \\\n \"continue (y/n) ? \") )\n if yorno == _(\"y\") or yorno == _(\"Y\"):\n print\n break\n elif yorno == _(\"n\") or yorno == _(\"N\"):\n doExit(0)\n del yorno\n except KeyboardInterrupt:\n print\n doExit(0)\n\n GlobalVars.policy.preWork()\n\n # Call the setup() method for each plugin\n for plugname, plug in GlobalVars.loadedplugins:\n try:\n plug.setup()\n except KeyboardInterrupt:\n raise\n except:\n if GlobalVars.__raisePlugins__:\n raise\n else:\n error_log = open(logdir + \"/sosreport-plugin-errors.txt\", \"a\")\n etype, eval, etrace = sys.exc_info()\n traceback.print_exception(etype, eval, etrace, limit=2, file=sys.stdout)\n error_log.write(traceback.format_exc())\n error_log.close()\n\n print _(\" Running plugins. Please wait ...\")\n print\n plugruncount = 0\n for i in izip(GlobalVars.loadedplugins):\n plugruncount += 1\n sys.stdout.write(\"\\r Completed [%d/%d] ... \" % (plugruncount, \n len(GlobalVars.loadedplugins)))\n sys.stdout.flush()\n plugname, plug = i[0]\n try:\n plug.copyStuff()\n except KeyboardInterrupt:\n raise\n except:\n if GlobalVars.__raisePlugins__:\n raise\n else:\n error_log = open(logdir + \"/sosreport-plugin-errors.txt\", \"a\")\n etype, eval, etrace = sys.exc_info()\n traceback.print_exception(etype, eval, etrace, limit=2, file=sys.stdout)\n error_log.write(traceback.format_exc())\n error_log.close()\n\n print\n\n if GlobalVars.__cmdLineOpts__.report:\n for plugname, plug in GlobalVars.loadedplugins:\n for oneFile in plug.copiedFiles:\n try:\n xmlrep.add_file(oneFile[\"srcpath\"], os.stat(oneFile[\"srcpath\"]))\n except:\n pass\n\n xmlrep.serialize_to_file(rptdir + \"/sosreport.xml\")\n\n if GlobalVars.__cmdLineOpts__.analyze:\n # Call the analyze method for each plugin\n for plugname, plug in GlobalVars.loadedplugins:\n try:\n plug.analyze()\n except:\n # catch exceptions in analyze() and keep working\n pass\n\n if GlobalVars.__cmdLineOpts__.report:\n # Generate the header for the html output file\n rfd = open(rptdir + \"/\" + \"sosreport.html\", \"w\")\n rfd.write(\"\"\"\n <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n <html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\">\n <head>\n <link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" href=\"donot.css\" />\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n <title>Sos System Report</title>\n </head>\n\n <body>\n \"\"\")\n\n\n # Make a pass to gather Alerts and a list of module names\n allAlerts = deque() \n plugNames = deque() \n for plugname, plug in GlobalVars.loadedplugins:\n for alert in plug.alerts:\n allAlerts.append('<a href=\"#%s\">%s</a>: %s' % (plugname, plugname,\n alert))\n plugNames.append(plugname)\n\n # Create a table of links to the module info\n rfd.write(\"<hr/><h3>Loaded Plugins:</h3>\")\n rfd.write(\"<table><tr>\\n\")\n rr = 0\n for i in range(len(plugNames)):\n rfd.write('<td><a href=\"#%s\">%s</a></td>\\n' % (plugNames[i],\n plugNames[i]))\n rr = divmod(i, 4)[1]\n if (rr == 3):\n rfd.write('</tr>')\n if not (rr == 3):\n rfd.write('</tr>')\n rfd.write('</table>\\n')\n\n rfd.write('<hr/><h3>Alerts:</h3>')\n rfd.write('<ul>')\n for alert in allAlerts:\n rfd.write('<li>%s</li>' % alert)\n rfd.write('</ul>')\n\n\n # Call the report method for each plugin\n for plugname, plug in GlobalVars.loadedplugins:\n try:\n html = plug.report()\n except:\n if GlobalVars.__raisePlugins__:\n raise\n else:\n rfd.write(html)\n\n rfd.write(\"</body></html>\")\n\n rfd.close()\n\n # Call the postproc method for each plugin\n for plugname, plug in GlobalVars.loadedplugins:\n try:\n plug.postproc()\n except:\n if GlobalVars.__raisePlugins__:\n raise\n\n if GlobalVars.__cmdLineOpts__.build:\n print\n print _(\" sosreport build tree is located at : %s\" % (GlobalVars.dstroot,))\n print\n return GlobalVars.dstroot\n\n # package up the results for the support organization\n GlobalVars.policy.packageResults()\n\n # delete gathered files\n GlobalVars.policy.cleanDstroot()\n\n # let's encrypt the tar-ball\n #if GlobalVars.__cmdLineOpts__.encrypt:\n # policy.encryptResults()\n\n # automated submission will go here\n if not GlobalVars.__cmdLineOpts__.upload:\n GlobalVars.policy.displayResults()\n else:\n GlobalVars.policy.uploadResults()\n\n # Close all log files and perform any cleanup\n logging.shutdown()", "def get_main_conf(simfolder):\n conf = configparser.ConfigParser()\n try:\n assert(osp.exists('%s/stosim.conf' % simfolder))\n except AssertionError:\n print(\"[StoSim] Cannot find stosim.conf in the folder '%s' - Exiting ...\" % simfolder)\n sys.exit(2)\n conf.read(\"%s/stosim.conf\" % simfolder)\n\n if not conf.has_section('meta'):\n conf.add_section('meta')\n try:\n def_user = os.getlogin()\n except OSError as e:\n def_user = os.getenv('USER')\n for (sec, opt, default) in\\\n [('meta', 'name', 'A simulation run by StoSim'),\\\n ('meta', 'maintainer', def_user),\\\n ('control', 'scheduler', 'fjd'),\\\n ('control', 'runs', '1')]:\n if not conf.has_option(sec, opt):\n conf.set(sec, opt, default)\n\n # get simulations from arguments, if given\n args = read_args()\n if args.simulations:\n if not conf.has_section('simulations'):\n print(\"[StoSim] You cannot use the '--simulations' cmd line\"\\\n \" parameter if you do not have the [simulations] section\"\\\n \" in stosim.conf\")\n sys.exit(2)\n conf.set('simulations', 'configs', ','.join(args.simulations))\n # make sure all simulations end in .conf and do actually exist\n if conf.has_section('simulations'):\n checked = []\n for c in [cf.strip() for cf in conf.get('simulations', 'configs').split(',')]:\n if not c.endswith('.conf'):\n c = '{}.conf'.format(c)\n if not osp.exists(\"{}/{}\".format(simfolder, c)):\n print(\"[StoSim] Warning: The file {} does not exist!\".format(c))\n checked.append(c)\n conf.set('simulations', 'configs', ','.join(checked))\n\n return conf", "def run_config(\n *, cfg: Union[pathlib.Path, str], overrides: Sequence[str], tag: Optional[str] = None\n) -> None:\n cmd = [\"python\", \"run.py\", \"--cfg\", str(cfg), \"--mode\", \"restart\", \"--force\"]\n if tag is not None:\n cmd.extend(\"--exp_id_pattern_override\", tag)\n cmd.extend(overrides)\n\n print(\"Cmd:\")\n print(f\"HH_EXP_DIR={OUTPUT_ROOT}\", *cmd)\n\n env = os.environ.copy()\n env[\"HH_EXP_DIR\"] = str(OUTPUT_ROOT)\n if \"USER\" not in env:\n # Weird CI stuff.\n env[\"USER\"] = \"root\"\n\n return subprocess.check_call(cmd, env=env)", "def run(config, run_id, name):\n simulation_directory = config['simulations_directory']\n\n if simulation_directory == 'non_pseudo':\n non_pseudo_dir = os.path.dirname(os.path.dirname(non_pseudo.__file__))\n path = os.path.join(non_pseudo_dir, run_id, name)\n elif simulation_directory == 'scratch':\n path = os.environ['LOCAL']\n else:\n print('OUTPUT DIRECTORY NOT FOUND.')\n output_dir = os.path.join(path, 'output_%s_%s' % (name, uuid4()))\n\n print(\"Output directory :\\t%s\" % output_dir)\n os.makedirs(output_dir, exist_ok=True)\n filename = os.path.join(output_dir, \"SurfaceArea.input\")\n\n write_raspa_file(config, filename, name)\n force_field_path = os.path.join(non_pseudo_dir, 'non_pseudo', 'simulation', 'forcefield')\n shutil.copy(os.path.join(force_field_path, 'force_field_mixing_rules.def'), output_dir)\n shutil.copy(os.path.join(force_field_path, 'force_field.def'), output_dir)\n shutil.copy(os.path.join(force_field_path, 'pseudo_atoms.def'), output_dir)\n cif_path = os.path.join(non_pseudo_dir, 'cif_files')\n mat_path = os.path.join(cif_path, '%s.cif' % name)\n print(mat_path)\n shutil.copy(mat_path, output_dir)\n\n while True:\n try:\n print(\"Date :\\t%s\" % datetime.now().date().isoformat())\n print(\"Time :\\t%s\" % datetime.now().time().isoformat())\n print(\"Calculating surface area of %s...\" % (name))\n subprocess.run('simulate SurfaceArea.input', shell=True, check=True, cwd=output_dir)\n filename = \"output_%s_2.2.2_298.000000_0.data\" % (name)\n output_file = os.path.join(output_dir, 'Output', 'System_0', filename)\n results = parse_output(output_file)\n shutil.rmtree(path, ignore_errors=True)\n sys.stdout.flush()\n except (subprocess.CalledProcessError, FileNotFoundError, IndexError, KeyError) as err:\n print(err)\n print(err.args)\n continue\n break\n\n return results", "def cmsRun(cfgFile):\n if not os.path.exists(cfgFile):\n raise IOError(\"The file '%s' does not exist\" % cfgFile)\n return subprocess.Popen(['cmsRun',cfgFile], stdout=subprocess.PIPE,stderr=subprocess.PIPE).communicate()", "def run_batch_lst(\n foldername: str,\n glob_str: str = \"*.lst\",\n recursive: bool = False,\n cfg_file: str = \"\",\n) -> pd.DataFrame:\n from pysight.gui.gui_main import GuiAppLst\n\n path = pathlib.Path(foldername)\n num_of_files = 0\n if not path.exists():\n raise UserWarning(f\"Folder {foldername} doesn't exist.\")\n if recursive:\n all_lst_files = path.rglob(glob_str)\n logging.info(f\"Running PySight on the following files:\")\n for file in list(all_lst_files):\n logging.info(str(file))\n num_of_files += 1\n all_lst_files = path.rglob(glob_str)\n else:\n all_lst_files = path.glob(glob_str)\n logging.info(f\"Running PySight on the following files:\")\n for file in list(all_lst_files):\n logging.info(str(file))\n num_of_files += 1\n all_lst_files = path.glob(glob_str)\n\n data_columns = [\"fname\", \"done\", \"error\"]\n data_record = pd.DataFrame(\n np.zeros((num_of_files, 3)), columns=data_columns\n ) # store result of PySight\n try:\n with open(cfg_file, \"r\") as f:\n config = toml.load(f)\n config[\"outputs\"][\"data_filename\"] = \".lst\"\n except (TypeError, FileNotFoundError):\n gui = GuiAppLst()\n gui.root.mainloop()\n gui.filename.set(\".lst\") # no need to choose a list file\n config = Config.from_gui(gui).config_data\n verify_input(config)\n\n try:\n for idx, lst_file in enumerate(all_lst_files):\n config[\"outputs\"][\"data_filename\"] = str(lst_file)\n data_record.loc[idx, \"fname\"] = str(lst_file)\n try:\n main_data_readout(config)\n except BaseException as e:\n logging.warning(\n f\"File {str(lst_file)} returned an error. Moving onwards.\"\n )\n data_record.loc[idx, \"done\"] = False\n data_record.loc[idx, \"error\"] = repr(e)\n else:\n data_record.loc[idx, \"done\"] = True\n data_record.loc[idx, \"error\"] = None\n except TypeError as e:\n logging.error(repr(e))\n\n logging.info(f\"Summary of batch processing:\\n{data_record}\")\n return data_record", "def check_slim_conf():\n return run_with_sudo([\"test\", \"-w\", slim_config_file])", "def run_modules(cfg):\n cwd = os.getcwd()\n for steps in cfg:\n bin = cfg[steps]['cmd']\n args = cfg[steps]['args']\n if cfg[steps]['run']:\n res = sh_run(bin, args, cwd=cwd)\n else:\n print(\"Skip step: {}\".format(steps))\n res = True\n if not res:\n break", "def check_conf(simfolder):\n conf = configparser.ConfigParser()\n try:\n conf.read(\"%s/stosim.conf\" % simfolder)\n except configparser.ParsingError as e:\n print(\"[StoSim] %s\" % e)\n sys.exit(2)\n\n if not osp.exists(\"%s/stosim.conf\" % simfolder):\n print(\"[StoSim] I can not find stosim.conf in the folder '%s' - Exiting...\" % simfolder)\n sys.exit(2)\n\n if not conf.has_section('meta') or not conf.has_option('meta', 'name'):\n print(\"[StoSim] You need to tell me a name for this simulation. \\\n Please define an option called 'name' in a section called 'meta'.\")\n sys.exit(2)\n\n if not conf.has_section('control') or not conf.has_option('control', 'executable'):\n print(\"[StoSim] You need to tell me what script to execute. \\\n Please define an option called 'executable' in a section called 'control'.\")\n sys.exit(2)\n\n if not conf.has_section('params'):\n print(\"[StoSim] Warning: You have not defined a 'params' - section.\")", "def _sync(self):\n\n fd, tempcfg = tempfile.mkstemp()\n try:\n cache_dir = os.path.join(\n settings.YUM_CACHE_ROOT,\n self.scl.copr_username,\n self.scl.copr_name,\n self.name\n )\n if not os.path.exists(cache_dir):\n os.makedirs(cache_dir)\n\n cfg = os.fdopen(fd, \"w+\")\n cfg.write(\"\"\"[main]\nreposdir=\ncachedir={cache_dir}\n\n[{name}]\nname={name}\nbaseurl={url}\ngpgcheck=0\n\"\"\".format(cache_dir=cache_dir, name=self.name, url=self.copr_url))\n cfg.flush()\n cfg.close()\n\n definitions = ' '.join(['-D \"{} {}\"'.format(key, value) for key, value in {\n '_topdir': settings.RPMBUILD_TOPDIR,\n '_rpmdir': self.get_repo_root(),\n 'dist': self.distro_version,\n 'scl_name': self.scl.name,\n 'scl_title': self.scl.title,\n 'scl_description': self.scl.description,\n 'repo_name': self.name,\n 'repo_version': VERSION,\n 'repo_release': RELEASE,\n 'repo_distro': self.distro,\n 'repo_arch': self.arch,\n 'repo_baseurl': self.get_repo_url(),\n }.items()])\n command = \"reposync -c {cfg} -p {destdir} -r {repoid} && \" \\\n \"( test -e {rpmfile_path} || rpmbuild -ba {definitions} {specfile}; ) && \" \\\n \"createrepo_c --database --update {destdir}/{repoid}\" \\\n .format(cfg=tempcfg, destdir=self.scl.get_repos_root(), repoid=self.name,\n definitions=definitions, rpmfile_path=self.get_rpmfile_path(), specfile=SPECFILE)\n\n subprocess.check_call(command, shell=True)\n finally:\n os.remove(tempcfg)\n\n self.save()", "def copyRaws(self):\n #make a new dir\n path = 'tmp'\n try:\n os.mkdir(path)\n except:\n for d in glob.glob('./%s/*.*' % path):\n os.remove(d)\n\n for fle in glob.glob('./raw/*_raw.fits'):\n shutil.copy(fle, path)\n\n for fle in glob.glob('./support/*_spt.fits'):\n shutil.copy(fle, path)\n\n for fle in glob.glob('./asn/*_asn.fits'):\n shutil.copy(fle, path)\n\n #change the current working directory to tmp\n os.chdir(os.getcwd() + '/' + path)\n iraf.chdir(os.getcwd())", "def check_syscalc(self, args):\n\n scdir = self.options['syscalc_path']\n \n if not scdir:\n logger.info('Retry to read configuration file to find SysCalc')\n self.set_configuration()\n\n scdir = self.options['syscalc_path']\n \n if not scdir:\n error_msg = 'No valid SysCalc path set.\\n'\n error_msg += 'Please use the set command to define the path and retry.\\n'\n error_msg += 'You can also define it in the configuration file.\\n'\n error_msg += 'Please note that you need to compile SysCalc first.'\n raise self.InvalidCmd(error_msg) \n \n if len(args) == 0:\n if not hasattr(self, 'run_name') or not self.run_name:\n self.help_syscalc()\n raise self.InvalidCmd('No run name currently defined. Please add this information.') \n args.append('all')\n return\n\n #deal options\n tag = [a for a in args if a.startswith('--tag=')]\n if tag: \n args.remove(tag[0])\n tag = tag[0][6:]\n \n if args[0] not in self._syscalc_mode:\n self.set_run_name(args[0], tag=tag, level='syscalc')\n del args[0]\n if len(args) == 0:\n args.append('all')\n elif not self.run_name:\n self.help_syscalc()\n raise self.InvalidCmd('No run name currently defined. Please add this information.') \n elif tag and tag != self.run_tag:\n self.set_run_name(self.run_name, tag=tag, level='syscalc')\n \n for arg in args:\n if arg not in self._syscalc_mode and arg != self.run_name:\n self.help_syscalc()\n raise self.InvalidCmd('unknown options %s' % arg) \n\n if self.run_card['use_syst'] not in self.true:\n raise self.InvalidCmd('Run %s does not include ' % self.run_name + \\\n 'systematics information needed for syscalc.')" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read ClosedEnd Fund price and Net Asset Value (NAV) quotes from csv file format. Cef tickers and file names are taken from user defined dict CEF_DATA_SOURCES
def read_raw_cef_data(cef_symbol): cef = pd.read_csv(CEF_DATA_SOURCES[cef_symbol][0]) cef = cef[["timestamp", "close"]] cef.columns = [DATE_COL_NAME, PRICE_COL_NAME] cef[NAV_COL_NAME] = pd.read_csv(CEF_DATA_SOURCES[cef_symbol][1])["close"] cef[DATE_COL_NAME] = pd.to_datetime(cef[DATE_COL_NAME]) cef = cef.sort_values([DATE_COL_NAME]) return cef
[ "def _open_convert_csv_files(self):\n comb_index = None\n for e in self.feeds:\n self.symbol_data[e] = {}\n self.latest_symbol_data[e] = {}\n\n for s in self.feeds[e]:\n csv_filename = get_ohlcv_file(e, s, self.timeframe, self.start_date, self.end_date)\n csv_filepath = os.path.join(self.csv_dir, csv_filename)\n df = pd.read_csv(\n csv_filepath,\n parse_dates=True,\n date_parser=self._date_parse,\n header=0,\n sep=',',\n index_col=1,\n names=['time', 'timestamp', 'open', 'high', 'low', 'close', 'volume']\n )\n\n df.dropna(inplace=True)\n df['returns'] = df['close'].pct_change()\n df.index = df.index.tz_localize('UTC').tz_convert('US/Eastern')\n\n if self.start_date:\n self.symbol_data[e][s] = df.sort_index().ix[self.start_date:]\n\n if comb_index is None:\n comb_index = self.symbol_data[e][s].index\n else:\n comb_index.union(self.symbol_data[e][s].index)\n\n self.latest_symbol_data[e][s] = []\n self.symbol_data[e][s] = self.symbol_data[e][s].reindex(index=comb_index, method='pad').iterrows()\n\n for i in range(self.initial_bars):\n bar = next(self._get_new_bar(e, s))\n if bar is not None:\n self.latest_symbol_data[e][s].append(bar)", "def get_data(filename, company):\n dates = []\n prices = []\n with open(filename, 'r') as csvfile:\n csvFileReader = reader(csvfile)\n print(\"Company Label:\", company)\n next(csvFileReader)\t # skipping column names\n i = 1\n for row in csvFileReader:\n if row[1] == company:\n dates.append(row[0])\n i += 1\n prices.append(float(row[3]))\n # sort prices list by the actual date (clean data)\n prices = [x for (y, x) in sorted(\n zip(sorted(dates,\n key=lambda d: tuple(map(int, d.split('-')))), prices))]\n dates = range(0, len(dates)) # number of days\n predict_stock(dates, prices, len(dates) + 1, company)\n return", "def _open_convert_csv_files(self): # private method\n comb_index = None\n \n # Iterates through all the symbols we're storing in the dictionary of DataFrames\n for s in self.symbol_list:\n # Load the CSV file with no header information, indexed on date\n self.symbol_data[s] = pd.read_csv(\n os.path.join(self.csv_dir, '%.csv', '%s'),\n header=0, index_col=0, parse_dates=True,\n names=['datetime', 'open', 'low', 'high', 'close', 'volume', 'oi']\n ).sort()\n \n # Combine the index to pad forward values\n # Merges all the indexes with a union so that the index is completely filled\n if comb_index is None:\n comb_index = self.symbol_data[s].index\n else:\n comb_index.union(self.symbol_data[s].index)\n \n # Set the latest symbol_data to None\n self.latest_symbol_data[s] = []\n \n # Reindex the DataFrames for all symbols and pad missing values\n for s in self.symbol_list:\n self.symbol_data[s] = self.symbol_data[s].reindex(index=comb_index, method='pad').iterrows()", "def _open_convert_csv_files(self): # private method\n comb_index = None\n \n # Iterates through all the symbols we're storing in the dictionary of DataFrames\n for s in self.symbol_list:\n # Load the CSV file with no header information, indexed on date\n self.symbol_data[s] = pd.read_csv(\n os.path.join(self.csv_dir, '{}.csv'.format(s)),\n header=0, index_col=0, parse_dates=True,\n names=['datetime', 'open', 'high', 'low', 'close', 'adj_close', 'volume']\n ).sort_index()\n \n # Combine the index to pad forward values\n # Merges all the indexes with a union so that the index is completely filled\n if comb_index is None:\n comb_index = self.symbol_data[s].index\n else:\n comb_index.union(self.symbol_data[s].index)\n \n # Set the latest symbol_data to None\n self.latest_symbol_data[s] = []\n \n # Reindex the DataFrames for all symbols and pad missing values\n for s in self.symbol_list:\n self.symbol_data[s] = self.symbol_data[s].reindex(index=comb_index, method='pad').iterrows()", "def fromTrancheFundInfoFile(cls, fIn='J:/Data/TrancheFundInfo.csv', storePath='J:/Data/TrancheFundDataFull', includeFile=None, asc=True):\n df = pandas.read_csv(fIn, sep=',')\n baseTicker = df['baseTicker']\n aTicker = df['aTicker']\n bTicker = df['bTicker']\n startDate = df['foundDate']\n startDate = startDate.map(lambda x: datetime.date(*(time.strptime(x, \"%Y/%m/%d\")[0:3])))\n lenData = 2 * (len(baseTicker) + len(aTicker) + len(bTicker))\n allDates = pandas.concat([startDate, startDate, startDate, startDate, startDate, startDate])\n allTickers = pandas.concat([baseTicker, aTicker, bTicker, baseTicker, aTicker, bTicker]).map(lambda x: str(x))\n allTypes = pandas.concat([pandas.Series(['PRICE'] * (len(baseTicker) * 3)), pandas.Series(['VALUE'] * (len(baseTicker) * 3))])\n indexData = pandas.Series(xrange(lenData))\n allDates.index = indexData\n allTickers.index = indexData\n allTypes.index = indexData\n allDates.name = \"StartDate\"\n allTickers.name = \"Ticker\"\n allTypes.name = \"Type\"\n tickerList = pandas.concat([allTickers, allTypes, allDates], axis=1)\n tickerList['Source'] = '163'\n tickerList['EndDate'] = datetime.date.today()\n incList = None\n if includeFile != None:\n incList = pandas.read_csv(includeFile)['Ticker'].map(lambda x: str(x))\n else:\n incList = allTickers\n return cls(tickerList = tickerList, storePath = storePath, includeList=incList, asc=asc)", "def open_bom_csv(self, bom_tree):\n status, file_name = Application.my_bom.import_csv(bom_tree)\n if status:\n self.bom_file_name.set(file_name)", "def read_file(filename):\n\n debts = pd.read_csv(filename, encoding=\"utf-8\", skiprows=3, index_col=\"Name\")\n debts = debts.replace(r\"[^.0-9]\", \"\", regex=True).astype(float)\n debts[\"Adjusted Payment\"] = 0\n debts[\"Interest\"] = 0\n\n inputs = pd.read_csv(filename, encoding=\"utf-8\", nrows=1, skipinitialspace=True)\n inputs[\"Monthly Payment\"] = (\n inputs[\"Monthly Payment\"].replace(r\"[^.0-9]\", \"\", regex=True).astype(float)\n )\n\n totalfunds = inputs.loc[0, \"Monthly Payment\"]\n try:\n date = datetime.datetime.strptime(\n str(inputs.loc[0, \"Start Date (YYYY-MM)\"]).strip(), \"%Y-%m\"\n )\n except ValueError:\n date = datetime.date.today()\n print(\n \"Invalid date format entered for Start Date. Must be YYYY-MM format. Using today's date instead.\"\n )\n\n strategy = inputs.loc[0, \"Strategy (Avalanche or Snowball)\"].strip().lower()\n\n if strategy == \"snowball\":\n debts = debts.sort_values(\"Principal\", ascending=True)\n else:\n debts = debts.sort_values(\"Rate\", ascending=False)\n\n return debts, totalfunds, date", "def get_futures_info():\r\n df = pd.read_csv('https://raw.githubusercontent.com/haobruce/SysTrade/master/SysTrade_FuturesContracts.csv')\r\n return df", "def get_csv_data(self):\r\n encoding = self.options.get(\r\n 'encoding', self.state.document.settings.input_encoding)\r\n error_handler = self.state.document.settings.input_encoding_error_handler\r\n if self.content:\r\n # CSV data is from directive content.\r\n if 'file' in self.options or 'url' in self.options:\r\n error = self.state_machine.reporter.error(\r\n '\"%s\" directive may not both specify an external file and'\r\n ' have content.' % self.name, nodes.literal_block(\r\n self.block_text, self.block_text), line=self.lineno)\r\n raise SystemMessagePropagation(error)\r\n source = self.content.source(0)\r\n csv_data = self.content\r\n elif 'file' in self.options:\r\n # CSV data is from an external file.\r\n if 'url' in self.options:\r\n error = self.state_machine.reporter.error(\r\n 'The \"file\" and \"url\" options may not be simultaneously'\r\n ' specified for the \"%s\" directive.' % self.name,\r\n nodes.literal_block(self.block_text, self.block_text),\r\n line=self.lineno)\r\n raise SystemMessagePropagation(error)\r\n source_dir = os.path.dirname(\r\n os.path.abspath(self.state.document.current_source))\r\n source = os.path.normpath(os.path.join(source_dir,\r\n self.options['file']))\r\n source = utils.relative_path(None, source)\r\n try:\r\n self.state.document.settings.record_dependencies.add(source)\r\n csv_file = io.FileInput(source_path=source,\r\n encoding=encoding,\r\n error_handler=error_handler)\r\n csv_data = csv_file.read().splitlines()\r\n except IOError, error:\r\n severe = self.state_machine.reporter.severe(\r\n u'Problems with \"%s\" directive path:\\n%s.'\r\n % (self.name, SafeString(error)),\r\n nodes.literal_block(self.block_text, self.block_text),\r\n line=self.lineno)\r\n raise SystemMessagePropagation(severe)\r\n elif 'url' in self.options:\r\n # CSV data is from a URL.\r\n # Do not import urllib2 at the top of the module because\r\n # it may fail due to broken SSL dependencies, and it takes\r\n # about 0.15 seconds to load.\r\n import urllib2\r\n source = self.options['url']\r\n try:\r\n csv_text = urllib2.urlopen(source).read()\r\n except (urllib2.URLError, IOError, OSError, ValueError), error:\r\n severe = self.state_machine.reporter.severe(\r\n 'Problems with \"%s\" directive URL \"%s\":\\n%s.'\r\n % (self.name, self.options['url'], SafeString(error)),\r\n nodes.literal_block(self.block_text, self.block_text),\r\n line=self.lineno)\r\n raise SystemMessagePropagation(severe)\r\n csv_file = io.StringInput(\r\n source=csv_text, source_path=source, encoding=encoding,\r\n error_handler=(self.state.document.settings.\\\r\n input_encoding_error_handler))\r\n csv_data = csv_file.read().splitlines()\r\n else:\r\n error = self.state_machine.reporter.warning(\r\n 'The \"%s\" directive requires content; none supplied.'\r\n % self.name, nodes.literal_block(\r\n self.block_text, self.block_text), line=self.lineno)\r\n raise SystemMessagePropagation(error)\r\n return csv_data, source", "def process_csv(self, file_name: str):", "def load_price_data():\r\n return pd.read_csv(\"stock_data.csv\")", "def get_csv_data(self):\r\n encoding = self.options.get(\r\n 'encoding', self.state.document.settings.input_encoding)\r\n error_handler = self.state.document.settings.input_encoding_error_handler\r\n if self.content:\r\n # CSV data is from directive content.\r\n if 'file' in self.options or 'url' in self.options:\r\n error = self.state_machine.reporter.error(\r\n '\"%s\" directive may not both specify an external file and'\r\n ' have content.' % self.name, nodes.literal_block(\r\n self.block_text, self.block_text), line=self.lineno)\r\n raise SystemMessagePropagation(error)\r\n source = self.content.source(0)\r\n csv_data = self.content\r\n elif 'file' in self.options:\r\n # CSV data is from an external file.\r\n if 'url' in self.options:\r\n error = self.state_machine.reporter.error(\r\n 'The \"file\" and \"url\" options may not be simultaneously'\r\n ' specified for the \"%s\" directive.' % self.name,\r\n nodes.literal_block(self.block_text, self.block_text),\r\n line=self.lineno)\r\n raise SystemMessagePropagation(error)\r\n source_dir = os.path.dirname(\r\n os.path.abspath(self.state.document.current_source))\r\n source = os.path.normpath(os.path.join(source_dir,\r\n self.options['file']))\r\n source = utils.relative_path(None, source)\r\n try:\r\n self.state.document.settings.record_dependencies.add(source)\r\n csv_file = io.FileInput(source_path=source,\r\n encoding=encoding,\r\n error_handler=error_handler)\r\n csv_data = csv_file.read().splitlines()\r\n except IOError as error:\r\n severe = self.state_machine.reporter.severe(\r\n 'Problems with \"%s\" directive path:\\n%s.'\r\n % (self.name, SafeString(error)),\r\n nodes.literal_block(self.block_text, self.block_text),\r\n line=self.lineno)\r\n raise SystemMessagePropagation(severe)\r\n elif 'url' in self.options:\r\n # CSV data is from a URL.\r\n # Do not import urllib2 at the top of the module because\r\n # it may fail due to broken SSL dependencies, and it takes\r\n # about 0.15 seconds to load.\r\n import urllib.request, urllib.error, urllib.parse\r\n source = self.options['url']\r\n try:\r\n csv_text = urllib.request.urlopen(source).read()\r\n except (urllib.error.URLError, IOError, OSError, ValueError) as error:\r\n severe = self.state_machine.reporter.severe(\r\n 'Problems with \"%s\" directive URL \"%s\":\\n%s.'\r\n % (self.name, self.options['url'], SafeString(error)),\r\n nodes.literal_block(self.block_text, self.block_text),\r\n line=self.lineno)\r\n raise SystemMessagePropagation(severe)\r\n csv_file = io.StringInput(\r\n source=csv_text, source_path=source, encoding=encoding,\r\n error_handler=(self.state.document.settings.\\\r\n input_encoding_error_handler))\r\n csv_data = csv_file.read().splitlines()\r\n else:\r\n error = self.state_machine.reporter.warning(\r\n 'The \"%s\" directive requires content; none supplied.'\r\n % self.name, nodes.literal_block(\r\n self.block_text, self.block_text), line=self.lineno)\r\n raise SystemMessagePropagation(error)\r\n return csv_data, source", "def open_x4_csv():\r\n global X4_csv\r\n X4_csv = fd.askopenfilename(filetypes=((\"csv file\", \"*.csv\"), (\"All files\", \"*.*\")))", "def read_CSV(self):\n file = open(self.file_name, \"r\")\n self.data = {}\n self.header_adjustment(file)\n self.process_line_by_line(file)", "def load_data(f):\n import csv\n with open(f, newline='') as csvfile:\n ecgreader = csv.reader(csvfile, delimiter=' ')\n time, voltage, high_voltages = organize_data(ecgreader, f)\n return time, voltage, high_voltages", "def grabQuotes(quoteList):\n\n with open(\"quotes.csv\", mode='r', newline='') as file1:\n\n csv_reader = csv.reader(file1)\n for row in csv_reader:\n quoteList.append(row)", "def read_coupling_csv(path):\n with open(path) as csv:\n next(csv) # skip first line\n file_couplings = []\n for line in csv:\n entity, coupled, degree, avg_revs = line.split(',')\n fc = FileCoupling(entity, coupled, degree, avg_revs)\n file_couplings.append(fc)\n return file_couplings", "def read_trades_from_csv_file(filename):\n # \"Type\",\"Buy\",\"Cur.\",\"Buy value in USD\",\"Sell\",\"Cur.\",\"Sell value in USD\",\"Fee\",\"Cur.\",\"Exchange\",\"Trade Date\"\n # \"type\",\"buy_amount\",\"buy_currency\",\"buy_value_usd\",\"sell_amount\",\"sell_currency\",\"sell_value_usd\",\"fee_amount\",\"fee_currency\",\"exchange\",\"time\"\n # \"Type\",\"Buy\",\"Cur.\",\"Buy value in USD\",\"Sell\",\"Cur.\",\"Sell value in USD\",\"Fee\",\"Cur.\",\"Exchange\",\"Imported From\",\"Trade Group\",\"Comment\",\"Trade ID\",\"Add Date\",\"Trade Date\"\n # \"type\",\"buy_amount\",\"buy_currency\",\"buy_value_usd\",\"sell_amount\",\"sell_currency\",\"sell_value_usd\",\"fee_amount\",\"fee_currency\",\"exchange\",\"imported_from\",\"group\",\"comment\",\"trade_id\",\"imported_time\",\"time\"\n return csv.DictReader(open(filename, newline=''))", "def test_trade_csv(self):\n data = dict(csv_file='csv_file_example')\n response = self.client.open(\n '/v2/trade',\n method='POST',\n data=data,\n content_type='multipart/form-data')\n self.assert200(response,\n 'Response body is : ' + response.data.decode('utf-8'))" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculating Zscore of the value in the cell [df[DATE_COL_NAME]==period_end_date, col_name] from period_start_date to period_end_date. DataFrame should contain column DATE_COL_NAME and col_name.
def calculate_zscore(df, col_name, period_start_date, period_end_date): data = df.loc[ (df[DATE_COL_NAME] >= period_start_date) & (df[DATE_COL_NAME] <= period_end_date), col_name] curr_value = df.loc[df[DATE_COL_NAME] == period_end_date, col_name].values[0] average_value = data.mean() std = data.std() zscore = (curr_value - average_value) / std df.loc[df[DATE_COL_NAME] == period_end_date, col_name + Z_SCORE_POSTFIX] = zscore return df
[ "def calculate_trailing_residual_zscores(df_input, regressor_col_name, simulation_begin_date, calc_period):\n\tdf = df_input.copy()\n\tall_dates = df[DATE_COL_NAME]\n\tdates = df.loc[df[DATE_COL_NAME] >= simulation_begin_date, DATE_COL_NAME].reset_index(drop=True)\n\tfor date in dates:\n\t\tperiod_start_date = find_valid_period_start_date(all_dates, date, calc_period)\n\t\tdata = df[(df[DATE_COL_NAME] >= period_start_date) & (df[DATE_COL_NAME] <= date)].reset_index(drop=True)\n\t\tx = data[regressor_col_name].values.reshape(-1, 1)\n\t\ty = np.array(data[PRICE_RETURNS_COL_NAME].values)\n\t\t\n\t\tregress_model = LinearRegression().fit(x, y)\n\t\ty_predicted = regress_model.predict(x)\n\t\tresiduals = y - y_predicted\n\t\t\n\t\tcurr_val = residuals[len(residuals) - 1]\n\t\taverage_value = residuals.mean()\n\t\tstd = residuals.std()\n\t\tzscore = (curr_val - average_value) / std\n\t\tdf.loc[df[DATE_COL_NAME] == date, RESIDUAL_ZSCORE_COL_NAME] = zscore\n\t\n\tdf = df.loc[df[DATE_COL_NAME] >= simulation_begin_date].reset_index(drop=True)\n\treturn df", "def calculating_zscore(df, cols):\n try:\n df_dummy = df.copy()\n for col in cols:\n col_zscore = col + \"_zscore\"\n df_dummy[col_zscore] = (df_dummy[col] - df_dummy[col].mean()) / df_dummy[\n col\n ].std(ddof=0)\n \n col_zscore_outlier = col_zscore + \"_outlier\"\n \n df_dummy[col_zscore_outlier] = np.where(\n (\n (df_dummy[col_zscore] > 3)\n | (df_dummy[col_zscore] < -3)\n ),\n \"outlier\",\n \"non-outlier\",\n )\n\n\n return df_dummy\n\n except Exception as e:\n print(\"Error at df_first_look function: \", str(e))\n return df", "def z_score(df, axis):\n return pd.DataFrame(zscore(df,axis), index=df.index, columns=df.columns)", "def zscore_survival_function(\n df,\n output=\"multivariate\",\n method=\"zscore\",\n distribution=\"norm\",\n rolling_periods: int = 200,\n center: bool = True,\n):\n if method == \"zscore\":\n residual_score = np.abs((df - df.mean(axis=0))) / df.std(axis=0)\n elif method == \"rolling_zscore\":\n df_rolling = df.rolling(rolling_periods, min_periods=1, center=center)\n residual_score = np.abs((df - df_rolling.mean())) / df_rolling.std()\n elif method == \"mad\":\n median_diff = np.abs((df - df.median(axis=0)))\n residual_score = median_diff / median_diff.mean(axis=0)\n else:\n raise ValueError(\"zscore method not recognized\")\n\n if output == \"univariate\":\n dof = df.shape[1]\n residual_score = residual_score.sum(axis=1)\n columns = [\"p_values\"]\n elif output == \"multivariate\":\n dof = 1\n columns = df.columns\n else:\n raise ValueError(\"zscore sf `output` arg not recognized\")\n\n # chi2, nbinom, erlang, gamma, poisson, maxwell, [laplace, cosine, norm, arcsine, uniform]\n if distribution == \"norm\":\n return pd.DataFrame(\n norm.sf(residual_score, dof), index=df.index, columns=columns\n )\n elif distribution == \"gamma\":\n return pd.DataFrame(\n gamma.sf(residual_score, dof), index=df.index, columns=columns\n )\n elif distribution == \"chi2\":\n return pd.DataFrame(\n chi2.sf(residual_score, dof), index=df.index, columns=columns\n )\n elif distribution == \"uniform\":\n return pd.DataFrame(\n uniform.sf(residual_score, dof), index=df.index, columns=columns\n )\n else:\n raise ValueError(\"zscore sf `distribution` arg not recognized\")", "def z_score(candle, periods):\n df = app.bot.dfc.loc[candle['pair'], strtofreq[candle['freq']]]\n co, cf = candle['open_time'], candle['freq']\n\n if cf == '1m':\n end = co - delta(minutes=1)\n start = end - delta(minutes = periods)\n elif cf == '5m':\n end = co - delta(minutes=5)\n start = end - delta(minutes = 5 * periods)\n elif cf == '1h':\n end = co - delta(hours=1)\n start = end - delta(hours = periods)\n\n history = df.loc[slice(start, end)]\n\n # Smooth signal/noise ratio with EMA.\n ema = history.ewm(span=periods).mean()\n\n # Mean and SD\n stats = ema.describe()\n cols = ['close', 'volume', 'buy_ratio']\n\n # Calc Z-Scores\n data = [\n (candle['close'] - stats['close']['mean']) / stats['close']['std'],\n (candle['volume'] - stats['volume']['mean']) / stats['volume']['std'],\n (candle['buy_ratio'] - stats['buy_ratio']['mean']) / stats['buy_ratio']['std']\n ]\n\n return pd.Series(data, index=cols).astype('float64').round(8)", "def calculate_return(df, col_name, period_start_date, period_end_date):\n\tbase_value = df.loc[df[DATE_COL_NAME] == period_start_date, col_name].values[0]\n\tcurr_value = df.loc[df[DATE_COL_NAME] == period_end_date, col_name].values[0]\n\tprice_return = (curr_value - base_value) / base_value * 100\n\tdf.loc[df[DATE_COL_NAME] == period_end_date, RETURN_PREFIX + col_name] = price_return\n\treturn df", "def encode_zscore(df: pd.DataFrame, col: str) -> None:\r\n mean = df[col].mean()\r\n std = df[col].std()\r\n df[col] = (df[col] - mean) / std", "def computeOQZscore(data):\n data[\"oqScore_Zscore\"] = (data[\"oqScore\"] - data[\"oqScore\"].mean()) / data[\n \"oqScore\"\n ].std()", "def zscore(df, axis=0):\n def single_zscore(A):\n B = A.copy()\n nas = pd.isna(A)\n B[~nas] = sstats.zscore(A[~nas])\n return B\n #edef\n \n return df.apply(single_zscore, axis)", "def z_score_standardization(data_frame):\n columns = list(data_frame.select_dtypes('number').columns.values)\n for column_name in columns:\n data_frame[column_name] = (data_frame[column_name] - data_frame[column_name].mean()) / data_frame[\n column_name].std(ddof=0)\n return data_frame", "def normalize_z_score(df):\n # Z score normalization by column for the four original features\n for column in df.keys()[:-5]:\n\n # Get column test statistics\n mean = df[column].mean()\n standard_deviation = df[column].std()\n\n # Z score normalization\n for index in range(150):\n current_data = df.at[index, column]\n df.at[index, column] = (current_data - mean) / standard_deviation\n\n return df", "def computeAppraiserZscore(data):\n # Uncomment the following to experiment\n ## Z Values\n # print(np.array([-3,-2,-1,0,1,2,3]))\n ## Probabilities\n # print(norm.cdf(np.array([-3,-2,-1,0,1,2,3])))\n ## Inverse Probability to Z Value\n # print(norm.ppf(norm.cdf(np.array([-3,-2,-1,0,1,2,3]))))\n data[\"appraiserScore_Zscore\"] = (\n data[\"appraiserScore\"] - data[\"appraiserScore\"].mean()\n ) / data[\"appraiserScore\"].std()", "def zscore(time_series, axis=-1):\n time_series = np.asarray(time_series)\n et = time_series.mean(axis=axis)\n st = time_series.std(axis=axis)\n sl = [slice(None)] * len(time_series.shape)\n sl[axis] = np.newaxis\n zt = time_series - et[tuple(sl)]\n zt /= st[tuple(sl)]\n return zt", "def computeOverallZscore(data):\n data[\"overall_Zscore\"] = (\n APPRAISER_IMPRESSION_WEIGHT * data[\"appraiserScore_Zscore\"]\n + OQ_QUESTION_WEIGHT * data[\"oqScore_Zscore\"]\n )", "def zscore(s: Series) -> Series:\n return (s - s.mean()) / s.std()", "def value_factor_backtest_monthly(real_yields, price_data, zscore_lookback, z_score_smoothening, n_securities, long_short, sample_start, sample_end):\n #Calculate Z-Score of Real Yields\n ry_zscore = (real_yields - real_yields.rolling(260*zscore_lookback).mean())/real_yields.rolling(260*zscore_lookback).std(ddof=1)\n ry_zscore = ry_zscore.dropna().rolling(z_score_smoothening).mean()\n \n #Merge Z-Score & Total Return Indices Data\n data = ry_zscore.merge(price_data, on='DATE').dropna()\n \n #Convert Data Frequency to Rebalancing Frequency\n #data = data1.asfreq(\"\"+str(rebalancing_period)+\"D\")\n month1 = pd.Series(data.index.month)\n month2 = pd.Series(data.index.month).shift(-1)\n mask = (month1 != month2)\n data = data[mask.values]\n data = data[sample_start:sample_end]\n data.dropna(inplace=True)\n \n #Rename Columns for better understanding\n data.columns = ['IG 1-3 Yield', 'IG 3-5 Yield', 'IG 7-10 Yield', 'US HY Yield',\n 'Crossover Yield', 'EM High Yield', 'UST 1-3 Yield', 'UST Int Yield',\n 'UST 7-10 Yield', 'UST Long Yield', 'IG 1-3 YieldP', 'IG 3-5 YieldP', 'IG 7-10 YieldP', 'US HY YieldP',\n 'Crossover YieldP', 'EM High YieldP', 'UST 1-3 YieldP', 'UST Int YieldP',\n 'UST 7-10 YieldP', 'UST Long YieldP']\n \n #Calculate Backtest Returns based on Long/Short or Long/Only and the no. of securities\n rets = data['Crossover Yield'].copy()*0\n rets.name = 'Value Strategy'\n \n if long_short == 'No':\n for i in range(len(data)-1):\n if n_securities == 1:\n rets[i+1] = data[str(data.iloc[i,:10].idxmax())+'P'][i+1]/data[str(data.iloc[i,:10].idxmax())+'P'][i]-1\n elif n_securities == 2:\n rets[i+1] = (data[str(data.iloc[i,:10].idxmax())+'P'][i+1]/data[str(data.iloc[i,:10].idxmax())+'P'][i]-1 + data[str(data.iloc[i,:10].sort_values()[:9].idxmax())+'P'][i+1]/data[str(data.iloc[i,:10].sort_values()[:9].idxmax())+'P'][i]-1)/2\n elif n_securities == 3:\n rets[i+1] = (data[str(data.iloc[i,:10].idxmax())+'P'][i+1]/data[str(data.iloc[i,:10].idxmax())+'P'][i]-1 + data[str(data.iloc[i,:10].sort_values()[:9].idxmax())+'P'][i+1]/data[str(data.iloc[i,:10].sort_values()[:9].idxmax())+'P'][i]-1 + + data[str(data.iloc[i,:10].sort_values()[:8].idxmax())+'P'][i+1]/data[str(data.iloc[i,:10].sort_values()[:8].idxmax())+'P'][i]-1)/3\n \n if long_short == 'Yes':\n for i in range(len(data)-1):\n if n_securities == 1:\n rets[i+1] = data[str(data.iloc[i,:10].idxmax())+'P'][i+1]/data[str(data.iloc[i,:10].idxmax())+'P'][i]-1 - data[str(data.iloc[i,:10].sort_values()[0:].idxmin())+'P'][i+1]/data[str(data.iloc[i,:10].sort_values()[0:].idxmin())+'P'][i]-1\n elif n_securities == 2:\n rets[i+1] = (data[str(data.iloc[i,:10].idxmax())+'P'][i+1]/data[str(data.iloc[i,:10].idxmax())+'P'][i]-1 + data[str(data.iloc[i,:10].sort_values()[:9].idxmax())+'P'][i+1]/data[str(data.iloc[i,:10].sort_values()[:9].idxmax())+'P'][i]-1)/2 - (data[str(data.iloc[i,:10].sort_values()[0:].idxmin())+'P'][i+1]/data[str(data.iloc[i,:10].sort_values()[0:].idxmin())+'P'][i]-1 + data[str(data.iloc[i,:10].sort_values()[1:].idxmin())+'P'][i+1]/data[str(data.iloc[i,:10].sort_values()[1:].idxmin())+'P'][i]-1)/2\n elif n_securities == 3:\n rets[i+1] = (data[str(data.iloc[i,:10].idxmax())+'P'][i+1]/data[str(data.iloc[i,:10].idxmax())+'P'][i]-1 + data[str(data.iloc[i,:10].sort_values()[:9].idxmax())+'P'][i+1]/data[str(data.iloc[i,:10].sort_values()[:9].idxmax())+'P'][i]-1 + data[str(data.iloc[i,:10].sort_values()[:8].idxmax())+'P'][i+1]/data[str(data.iloc[i,:10].sort_values()[:8].idxmax())+'P'][i]-1)/3 - (data[str(data.iloc[i,:10].sort_values()[0:].idxmin())+'P'][i+1]/data[str(data.iloc[i,:10].sort_values()[0:].idxmin())+'P'][i]-1 + data[str(data.iloc[i,:10].sort_values()[1:].idxmin())+'P'][i+1]/data[str(data.iloc[i,:10].sort_values()[1:].idxmin())+'P'][i]-1 + data[str(data.iloc[i,:10].sort_values()[2:].idxmin())+'P'][i+1]/data[str(data.iloc[i,:10].sort_values()[2:].idxmin())+'P'][i]-1)/3\n \n \n #Merge Value Factor Returns Data with original data and other individual securities returns \n data = data.merge(rets, on='DATE')\n data.columns = ['IG 1-3 Yield', 'IG 3-5 Yield', 'IG 7-10 Yield', 'US HY Yield',\n 'Crossover Yield', 'EM High Yield', 'UST 1-3 Yield', 'UST Int Yield',\n 'UST 7-10 Yield', 'UST Long Yield', 'IG 1-3', 'IG 3-5', 'IG 7-10', 'US HY',\n 'Crossover', 'EM HY', 'UST 1-3', 'UST Int',\n 'UST 7-10', 'UST Long', 'Value Strategy']\n m_rets = data[['IG 1-3', 'IG 3-5', 'IG 7-10', 'US HY', 'Crossover', 'EM HY', 'UST 1-3', 'UST Int', 'UST 7-10', 'UST Long']].pct_change().dropna().merge(rets, on='DATE')\n \n #Add Equally Weighted Portfolio Returns for comparison as well\n m_rets['EW'] = m_rets[['IG 1-3', 'IG 3-5', 'IG 7-10', 'US HY', 'Crossover', 'EM HY', 'UST 1-3', 'UST Int', 'UST 7-10', 'UST Long']].mean(axis=1)\n \n return m_rets", "def encode_modified_zscore(df: pd.DataFrame, col: str) -> None:\r\n median = df[col].median()\r\n median_absolute_deviation = np.median(np.abs(df[col] - median))\r\n df[col] = 0.6745 * (df[col] - median) / median_absolute_deviation", "def get_results(df,dates):\n\n data_list = []\n for date in dates:\n data_per_day = {}\n timeStampMidNight = pd.Timestamp(date)\n timeStampMorning = pd.Timestamp(date + ' ' + '06:00:00')\n wholeday= df[df['Date']==date]\n overnight = wholeday[wholeday['TimeStamp']<timeStampMorning]\n daytime = wholeday[wholeday['TimeStamp']>=timeStampMorning]\n data_per_day['wholeday'] = wholeday\n data_per_day['overnight'] = overnight\n data_per_day['daytime'] = daytime\n data_list.append(data_per_day)\n\n res = np.zeros(18)\n for data in data_list:\n sample_count = len(data['wholeday'])\n res[:6]+=extractCases(data['daytime'],sample_count)\n res[6:12]+=extractCases(data['overnight'],sample_count)\n res[12:18]+=extractCases(data['wholeday'],sample_count)\n res/=len(data_list)\n return res", "def z_score(x, mean, sd):\n return (x-mean)/sd" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculating holding period return from period_start_date to period_end_date. DataFrame should contain column DATE_COL_NAME and col_name.
def calculate_return(df, col_name, period_start_date, period_end_date): base_value = df.loc[df[DATE_COL_NAME] == period_start_date, col_name].values[0] curr_value = df.loc[df[DATE_COL_NAME] == period_end_date, col_name].values[0] price_return = (curr_value - base_value) / base_value * 100 df.loc[df[DATE_COL_NAME] == period_end_date, RETURN_PREFIX + col_name] = price_return return df
[ "def compute_df(real_stock_data, period_utils):\n df = real_stock_data.df\n\n months = period_utils.months\n gross_returns = (1 + df['m_return']).rolling(months, 1).apply(np.prod) - 1\n gross_returns = gross_returns.shift(-months)\n\n returns = period_utils.annualized_returns(gross_returns)\n\n return pd.DataFrame({'gross_returns': gross_returns, 'returns': returns}, index=df.index)", "def get_slice_prices(self, start_date, end_date):\r\n return fill_missing_data_business(self.price, start_date, end_date,'B')\r\n # result = np.nan\r\n # if isinstance(end_date, int):\r\n # inter_dates = [datetime.strftime(item, '%Y-%m-%d') for item in\r\n # pd.date_range(start=start_date, freq='B', periods=end_date)]\r\n # result = pd.DataFrame(self.price.reindex(inter_dates, method='ffill').loc[:].astype(float))\r\n # elif isinstance(end_date, str):\r\n # inter_dates = [datetime.strftime(item, '%Y-%m-%d') for item in\r\n # pd.date_range(start=start_date, freq='B', end=end_date)]\r\n # result = pd.DataFrame(self.price.reindex(inter_dates, method='ffill').loc[:].astype(float))\r\n # else:\r\n # print(\"input end_date as string or window size as int\")\r\n # return\r\n #\r\n # return result\r", "def __compute_return(self, data, before, after):\n\n event_ret = pd.DataFrame()\n for date in self.__event_date:\n subset_range = pd.date_range(\n start=date - pd.Timedelta(\"{d} days\".format(d=before)),\n end=date + pd.Timedelta(\"{d} days\".format(d=after)))\n data_df = data.reindex(subset_range).dropna()\n if data_df.empty:\n break\n event_ret.loc[date, 'return'] = (data_df['return'] + 1).prod() - 1\n return event_ret.mean().values", "def create_all_dates_df():\n\n all_dates_df = df.drop(columns=date_columns[1:])\n stock_columns.append('SPY_return_Adj Close')\n i = 0\n all_dates_df = all_dates_df.rename(columns={\"XLY_return_Date\": \"Date\"})\n\n all_dates_df.iloc[:, 1:] = np.nan\n\n # create a row for each date starting from start date\n while i <= (last_date.date() - first_date.date()).days:\n all_dates_df.at[i, 'Date'] = first_date + datetime.timedelta(days=i)\n all_dates_df.at[i, 'Is Beginning of a Month'] = (first_date + datetime.timedelta(days=i)).day < 15\n all_dates_df.at[i, 'Is Beginning of a Year'] = (first_date + datetime.timedelta(days=i)).month < 6\n i += 1\n\n # copy the stock value from the orginal data frame to the new data frame\n for stock in stock_columns:\n stock_name = stock.split('_')[0]\n date = [col for col in date_columns if stock_name in col]\n i = 0\n while i < len(df[date]):\n if type(df[date[0]][i]) is str:\n temp_date = datetime.datetime.strptime(df[date[0]][i], '%Y-%m-%d').date()\n if first_date.date() <= temp_date:\n index = (datetime.datetime.strptime(df[date[0]][i], '%Y-%m-%d').date() - first_date.date()).days\n all_dates_df[stock][index] = df[stock][i]\n i += 1\n else:\n break\n\n print(all_dates_df.head())\n all_dates_df.to_csv('all_dates_df.csv')", "def preprocessing(df, start_date, end_date): \n\n #Filter dataframe by dates \n df = df[(df['Just Date'] >= start_date) & (df['Just Date'] <= end_date)]\n df = lc.CleanedFrame(df)\n\n return df", "def performance(data, timeframe, transactions, analysis):\n \n # First get todays date and the current month\n now_date = datetime.date.today().strftime(\"%Y-%m-%d\")\n now_month=now_date[5:7] # split out the month from the date\n start_date='' # set an empty string to hold the start date\n \n \n \n if timeframe == \"30d\":\n # For monthly queries we'll get the last 30days data\n start_date = str(datetime.datetime.now() - datetime.timedelta(days=30))[:10] # slice to get date only\n elif timeframe == \"90d\":\n # For quarterly we'll get the last 90days\n start_date = str(datetime.datetime.now() - datetime.timedelta(days=90))[:10]\n elif timeframe == \"portfolio\":\n start_date = transactions[transactions.name==\"vechain\"].iloc[0].date\n \n \n\n # Query the latest monthly data using today's date and the previous 30days\n monthly_data = data[data[\"date\"].between(start_date, now_date)]\n \n # set the open and close prices subject to the calculation\n open_monthly = monthly_data.price[0]\n close_monthly = monthly_data.price[-1]\n \n # Set a variable to hold the growth figure\n percent_chg = 0\n \n # Calculate the growth depending on whether we have -ve or +ve growth for the period\n if open_monthly > close_monthly:\n percent_chg = -round(100 - ((100/open_monthly) * close_monthly), 2)\n elif open_monthly < close_monthly:\n percent_chg = round(((100/open_monthly) * close_monthly)-100, 2)\n else: \n percent_chg = 0\n \n # Return the growth figure and a dataframe for the period\n return percent_chg, monthly_data", "def fi_vix_allocator(duration, high_yield, vix, lookback_period, vix_smooth_period, sample_start, sample_end):\n\n price_data = duration.merge(high_yield, on='Date')\n cols=list(price_data.columns)\n vix = vix\n vix.index.name='Date'\n vix.columns = ['VIX']\n data = vix\n #data = data[:sample_end]\n data.dropna(inplace=True)\n \n data = ((data.rolling(lookback_period*252).max()).merge(data['VIX'], on='Date')).dropna()\n data = (data['VIX_y']/data['VIX_x']).rolling(vix_smooth_period).mean().dropna()\n \n #data1 = pd.DataFrame(data).merge(price_data, on='DATE')\n data = pd.DataFrame(data).merge(price_data, on='Date')\n cols.insert(0, 'VIX')\n data.columns = cols \n \n month1 = pd.Series(vix.index.month)\n month2 = pd.Series(vix.index.month).shift(-1)\n\n \n mask = (month1 != month2)\n mask = mask.astype(int)\n mask.index = vix.index\n mask.name='Rebalance'\n \n indices_ret = price_data.pct_change().dropna()\n strat = price_data.join(data['VIX'], on='Date').join(mask, on='Date').dropna()\n #strat = strat[date(strat.index.year[1], strat.index.month[1], strat.index.day[:30].max()):]\n \n strat['Portfolio'] = strat['VIX']*0+100\n strat['HY Portfolio'] = strat['VIX']*0\n strat['Dur Portfolio'] = strat['VIX']*0\n \n for i in range (1,len(strat['Dur Portfolio'])):\n if strat['Rebalance'][i-1] == 1:\n strat['Dur Portfolio'][i] = strat['Portfolio'][i-1] * strat['VIX'][i] / strat[list(duration.columns)].mean(axis=1)[i-1]\n strat['HY Portfolio'][i] = strat['Portfolio'][i-1] * (1-strat['VIX'][i])/strat[list(high_yield.columns)].mean(axis=1)[i-1]\n strat['Portfolio'][i] = strat['Dur Portfolio'][i] * strat[list(duration.columns)].mean(axis=1)[i] + strat['HY Portfolio'][i] * strat[list(high_yield.columns)].mean(axis=1)[i] \n elif strat['Rebalance'][i-1] == 0:\n strat['Dur Portfolio'][i] = strat['Dur Portfolio'][i-1]\n strat['HY Portfolio'][i] = strat['HY Portfolio'][i-1]\n strat['Portfolio'][i] = strat['Dur Portfolio'][i] * strat[list(duration.columns)].mean(axis=1)[i] + strat['HY Portfolio'][i] * strat[list(high_yield.columns)].mean(axis=1)[i]\n \n return pd.DataFrame(strat['Portfolio'].pct_change()).merge(price_data.pct_change(), on='Date').dropna()[sample_start :sample_end]", "def _compute_start_end(\n df: pd.DataFrame, start: \"DateConfig\", end: \"DateConfig\"\n) -> Tuple[pd.DataFrame, pd.DataFrame]:\n result = {}\n time_dict = {\"start\": start, \"end\": end}\n totals = df.groupby(\"date\").agg({\"value\": sum}).reset_index()\n for time_name, time in time_dict.items():\n if not totals[totals[\"date\"] == time[\"id\"]].empty:\n value = totals.loc[totals[\"date\"] == time[\"id\"], \"value\"].values[0]\n else:\n value = 0\n result[time_name] = pd.DataFrame(\n [{\"value\": value, \"label\": time[\"label\"], \"groups\": time[\"label\"]}]\n )\n return result[\"start\"], result[\"end\"]", "def add_dates_part(all_dates_df: pd.DataFrame, aggregate_df: pd.DataFrame):\n\n # index over all_dates_df\n j = 0\n # index over aggregate_df\n index = 0\n while index < len(aggregate_df):\n\n counter = 1 # count every delta days\n month_arguments = []\n year_arguments = []\n\n while counter <= delta and j < len(all_dates_df):\n month_arguments.append(all_dates_df.loc[j, \"Is Beginning of a Month\"])\n year_arguments.append(all_dates_df.loc[j, \"Is Beginning of a Year\"])\n counter += 1\n j += 1\n\n month_avg = np.mean(month_arguments)\n year_avg = np.mean(year_arguments)\n\n k = index + 20\n\n while index < k:\n if month_avg < 0.5: # majority of the days are in the second half of the month\n aggregate_df.loc[index, 'Is Beginning of a Month'] = 0\n else:\n aggregate_df.loc[index, 'Is Beginning of a Month'] = 1\n\n if year_avg < 0.5: # the month is at the first half of the year\n aggregate_df.loc[index, 'Is Beginning of a Year'] = 0\n else:\n aggregate_df.loc[index, 'Is Beginning of a Year'] = 1\n index += 1\n\n return aggregate_df", "def hvol_regime(df, days, low, high):\r\n if(low>high):\r\n raise KeyError('Low bound argument must be inferior to high bound argument')\r\n daily_return = df/df.shift(1)-1\r\n vol = daily_return.rolling(days).std() * np.sqrt(252) * 100\r\n df_binary = (vol<high) & (vol>low)\r\n #df_binary = df_binary.shift(1).dropna()\r\n date = df_binary[df_binary==True].dropna().index\r\n return date", "def getEarningsDayPricing(earnDateRow, historical_stock_prices, yahooEarningsDF, daysAroundEarnings=10):\n\n # recreate index as the 'date' column for price\n historical_stock_prices['date'] = historical_stock_prices['formatted_date'].apply(dateUtils.getDateFromISO8601)\n\n historical_stock_prices = historical_stock_prices.set_index(\"date\", drop=False)\n # historical_stock_prices.index = pd.to_datetime(historical_stock_prices.index)\n\n # get current earningsdate in yahooEarningsDF / count\n earningsDate = yahooEarningsDF['Earnings_Date'][earnDateRow].date()\n yahooEarningsDF.at[earnDateRow, 'EDClosePrice'] = historical_stock_prices.close[earningsDate]\n\n # the day before earnings date\n theEDMinus1Date = dateUtils.goOutXWeekdays(earningsDate, -1)\n yahooEarningsDF.at[earnDateRow, 'EDMinus1ClosePrice'] = historical_stock_prices.close[theEDMinus1Date]\n\n # the day after earnings date\n theEDPlus1Date = dateUtils.goOutXWeekdays(earningsDate, 1)\n yahooEarningsDF.at[earnDateRow, 'EDPlus1ClosePrice'] = historical_stock_prices.close[theEDPlus1Date]\n\n yahooEarningsDF.at[earnDateRow, 'EDPlus1OpenPrice'] = historical_stock_prices.open[theEDPlus1Date]\n\n # plus 4 days after earnings date\n theEDplus4Date = dateUtils.goOutXWeekdays(earningsDate, 4)\n yahooEarningsDF.at[earnDateRow, 'EDPlus4ClosePrice'] = historical_stock_prices.close[theEDplus4Date]\n\n return yahooEarningsDF", "def get_annual_rental_fee_period(target_date):\n target_date_year = target_date.year\n\n # Calculate cron job period\n run_date = ApiaryAnnualRentalFeeRunDate.objects.get(name=ApiaryAnnualRentalFeeRunDate.NAME_CRON)\n run_date_month = run_date.date_run_cron.month\n run_date_day = run_date.date_run_cron.day\n\n # Calculate the run_date in the year where the target_date is in\n prev_run_date = datetime.date(year=target_date_year, month=run_date_month, day=run_date_day)\n if prev_run_date > target_date:\n # prev_run_date calculated above is in the future. Calculate one before that\n prev_run_date = datetime.date(year=prev_run_date.year-1, month=prev_run_date.month, day=prev_run_date.day)\n\n # Calculate annual site fee period\n # annual site fee start date must be between the prev_run_date and next_run_date\n start_date = ApiaryAnnualRentalFeePeriodStartDate.objects.get(name=ApiaryAnnualRentalFeePeriodStartDate.NAME_PERIOD_START)\n period_start_date_month = start_date.period_start_date.month\n period_start_date_day = start_date.period_start_date.day\n\n # Calculate the period start date in the year where the prev_run_date is in\n period_start_date = datetime.date(year=prev_run_date.year, month=period_start_date_month, day=period_start_date_day)\n if period_start_date < prev_run_date:\n # period_start_date calculated above is before the previous cron job run date. Calculate the next one\n period_start_date = datetime.date(year=period_start_date.year+1, month=period_start_date.month, day=period_start_date.day)\n\n period_end_date = datetime.date(year=period_start_date.year+1, month=period_start_date.month, day=period_start_date.day) - datetime.timedelta(days=1)\n\n return period_start_date, period_end_date", "def create_aggregate_df():\n all_dates_df = pd.read_csv(\"datasets/all_dates_without_nan_df.csv\")\n aggregate_df = pd.DataFrame()\n\n tmp_date = first_date\n\n i = 0\n\n while tmp_date.date() < last_date.date():\n\n # add 20 lines for each interval\n while i < 20:\n aggregate_df = aggregate_df.append(\n {'Date': str(tmp_date)[0:10] + \" - \" + str(tmp_date + datetime.timedelta(days=delta - 1))[0:10],\n 'Stock Name': stock_columns[i]}\n , ignore_index=True)\n i += 1\n\n tmp_date = tmp_date + datetime.timedelta(days=delta)\n i = 0\n\n\n # create dummies for the stock names\n df_dummies = pd.DataFrame(data=pd.get_dummies(aggregate_df['Stock Name']))\n aggregate_df = aggregate_df.join(df_dummies)\n\n day_counter = 1\n\n # create delta columns for each day in the interval\n for i in range(1, delta + 1):\n aggregate_df['Day ' + str(day_counter)] = np.nan\n day_counter += 1\n\n i = 0\n tmp_date = first_date\n j = 0\n\n # add the relevant value of stock for each day\n while i < len(aggregate_df) and 0 <= (last_date.date() - tmp_date.date()).days:\n print(i)\n for day_counter in range(1, delta + 1):\n j = 0\n while j < 20:\n if 0 <= (last_date.date() - tmp_date.date()).days:\n col = [col for col in aggregate_df.columns if aggregate_df.loc[j, col] == 1]\n index = (tmp_date.date() - first_date.date()).days\n aggregate_df['Day ' + str(day_counter)][i + j] = all_dates_df.loc[index, col]\n j += 1\n else:\n break\n tmp_date = tmp_date + datetime.timedelta(days=1)\n i += j\n aggregate_df.to_csv('aggregate_df.csv')", "def getDailyReturns(self, startDate, endDate):\n self.startDate = startDate\n self.endDate = endDate\n \n price = yf.download(stock,startDate,endDate)\n self.dReturns = pd.DataFrame(np.log(price)-np.log(price).shift(1),index=price.index)\n self.dReturns.columns = self.tickers\n self.dReturns.dropna(inplace = True)", "def calculate_zscore(df, col_name, period_start_date, period_end_date):\n\tdata = df.loc[\n\t\t(df[DATE_COL_NAME] >= period_start_date) & (df[DATE_COL_NAME] <= period_end_date), col_name]\n\tcurr_value = df.loc[df[DATE_COL_NAME] == period_end_date, col_name].values[0]\n\taverage_value = data.mean()\n\tstd = data.std()\n\tzscore = (curr_value - average_value) / std\n\tdf.loc[df[DATE_COL_NAME] == period_end_date, col_name + Z_SCORE_POSTFIX] = zscore\n\treturn df", "def end_period(self, date, period):", "def wage_change(self, frame_, state_code_column_name, start_month_column_name, end_month_column_name, convert=False):\n\n\t\tstate_code = frame_[state_code_column_name]\n\t\tstart_month = frame_[start_month_column_name]\n\t\tend_month = frame_[end_month_column_name]\n\n\t\t# check state codes\n\t\tall_state_codes = state_code.unique()\n\t\tunmerged_state_codes = set(all_state_codes).difference(set(utilities.Data.state_crosswalk.keys()))\n\t\tif len(unmerged_state_codes) > 0:\n\t\t\twarnings.warn(\"Series passed as argument state_code contains invalid values for state codes. Please refer to https://www.bls.gov/respondents/mwr/electronic-data-interchange/appendix-d-usps-state-abbreviations-and-fips-codes.htm for valid codes. Use utilities.State_To_FIPS_series() to convert postal codes to FIPS.\")\n\n\t\ttemp_frame = pd.DataFrame({'start_month':start_month,'end_month':end_month,'state_code':state_code})\n\n\t\t# employment merges\n\t\ttemp_frame['wage_start'] = temp_frame.merge(self.wage_series, left_on=['start_month','state_code'], right_on=['month_year','state_code'], how='left')['value']\n\t\ttemp_frame['wage_end'] = temp_frame.merge(self.wage_series, left_on=['end_month','state_code'], right_on=['month_year','state_code'], how='left')['value']\n\n\t\t# convert to current dollars\n\t\tif convert == True:\n\t\t\ttemp_frame['start_year'] = temp_frame['start_month'].str.split('-',expand=True)[0].astype(int)\n\t\t\ttemp_frame['end_year'] = temp_frame['end_month'].str.split('-',expand=True)[0].astype(int)\n\t\t\twage_start = self.adjust_to_current_dollars(temp_frame, 'start_year', 'wage_start')\n\t\t\twage_end = self.adjust_to_current_dollars(temp_frame, 'end_year', 'wage_end')\n\t\telse: # or not\n\t\t\twage_start = temp_frame['wage_start']\n\t\t\twage_end = temp_frame['wage_end']\n\n\t\twage_change = (wage_end - wage_start)*52 # convert to annual wage\n\t\treturn(wage_change)", "def stockvals(df,start_date,end_date):\r\n #convert pd dataframes to strings\r\n symbols, names = df.Symbol, df.Security\r\n symbols = symbols.to_numpy()\r\n symbols = symbols.astype(str)\r\n names = names.to_numpy()\r\n names = names.astype(str)\r\n start_date_int = datetime_to_integer(start_date)\r\n #Stocks under consideration (from S&P500)\r\n n_stocks = len(symbols)\r\n #Open - Closing value of stocks (as float)\r\n indices = []; open_val = []; close_val = []\r\n for j in tqdm(range(0,n_stocks),position=0,desc='Loading Stock Data'):\r\n if j == 91:\r\n continue\r\n date_string=(df.iloc[j][6]).replace('-',''); #print(date_string)\r\n date_added = int(date_string[:8])\r\n if(date_added <= start_date_int):\r\n index = j\r\n indices = np.append(indices,index)\r\n quotes = web.DataReader(symbols[j], 'yahoo', start_date, end_date)\r\n opening = quotes.Open\r\n closing = quotes.Close\r\n open_val = np.append(open_val,opening,axis=0)\r\n close_val = np.append(close_val,closing,axis=0)\r\n open_val = open_val.reshape(len(indices),-1)\r\n close_val = close_val.reshape(len(indices),-1)\r\n variation = open_val-close_val\r\n return names[indices.astype(int)],symbols[indices.astype(int)],variation,close_val,open_val", "def compute_monthly_returns(dbm: database_manager.DatabaseManager, tbl_name: str) -> \\\n Union[Tuple[pd.DataFrame, Tuple[str, str, str, str, str], datetime.datetime], Tuple[None, None]]:\n tbl, info = dbm.get_table(tbl_name)\n\n if tbl is None:\n return None, None\n\n tbl.dropna(axis=0, inplace=True)\n\n first_date = tbl.index[0]\n last_date = tbl.index[-1]\n prev_month = first_date.month\n\n row_idx = 0\n curr_date, prev_date = None, None\n\n monthly_returns = []\n daily_ret = 0\n monthly_ret = 0\n\n while curr_date != last_date:\n row_idx += 1\n\n curr_date = tbl.index[row_idx]\n\n curr_month = curr_date.month\n\n curr_price = tbl.iloc[row_idx]['PX_LAST']\n prev_price = tbl.iloc[row_idx - 1]['PX_LAST']\n\n if curr_price == 0:\n daily_ret = 0\n elif prev_price == 0:\n daily_ret = tbl.iloc[row_idx - 2]['PX_LAST']\n else:\n daily_ret = (curr_price / prev_price) - 1.0\n\n monthly_ret = monthly_ret * (daily_ret + 1) if monthly_ret != 0 else daily_ret + 1\n\n if curr_month != prev_month:\n # remove compounding of last daily return\n monthly_ret /= (daily_ret + 1)\n\n monthly_returns.append((prev_date, monthly_ret - 1))\n\n # reset for next month\n monthly_ret = daily_ret + 1\n\n prev_month = curr_month\n prev_date = curr_date\n\n df = pd.DataFrame(monthly_returns, columns=['Dates', 'Monthly_Return'])\n df.set_index('Dates', inplace=True)\n\n return df, info, first_date" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Select an existing period begin date in ordered list of dates
def find_valid_period_start_date(dates, date, period): period_start_date = date - period period_dates = dates[dates >= period_start_date] first_date = period_dates.iloc[0] return first_date
[ "def start_period(self, date, period):", "def starting_date(self) -> datetime:\n return min([x.starting_date for x in self.subaccounts])", "def get_dates(start, end):\n\n files = []\n\n while start <= end:\n p = start\n start += timedelta(days=1)\n files.append(p)\n\n return sorted(files)", "def produceDateList(startDate, endDate): \n dateList=[]\n delta = endDate - startDate\n for i in range(delta.days+1):\n day = startDate + dt.timedelta(days=i)\n dateList.append(dt.datetime.strftime(day,'%Y%-m%d'))\n return dateList", "def daterangelist(start_date, end_date, skip):\r\n l = np.array([])\r\n for n in range(0, int((end_date - start_date).days), skip):\r\n l = np.append(l, (start_date + datetime.timedelta(n)))\r\n return l.astype('datetime64')", "def options_date_iterator(chain, start_date, target_date):\n\n \tby_quote_date = sorted(chain, key=OptionsDay.quote_date)\n\treturn [(k, make_quote(list(g))) for (k,g) in itertools.groupby(by_quote_date, key=OptionsDay.quote_date) if start_date <= k <= target_date]", "def peak_begin_dates(start=\"01/01/1972\", end=datetime.now()):\n # Get quarterly recession dates from FRED\n rec_dates = DataReader(\"USRECQ\", \"fred\", start=start)\n one_vals = np.where(rec_dates == 1)[0]\n rec_start = [one_vals[0]]\n\n # Find the beginning of the recession dates (Don't include ones that\n # begin within three years of a previous one)\n for d in one_vals:\n if d > max(rec_start) + 12:\n rec_start.append(d)\n\n rec_startind = rec_dates.index[rec_start]\n\n return rec_startind", "def _date_range(start_date, end_date):\n\n for n in range(int((end_date - start_date).days)):\n yield start_date + timedelta(n)", "def generate_selected_dates(year_from=2000, year_to=2020, doy_start=1, doy_end=-1):\n import calendar, time\n dates = []\n for year in range(year_from, year_to+1):\n if doy_end == -1:\n if calendar.isleap(year):\n end_day = 367\n else:\n end_day = 366\n else:\n end_day = doy_end\n dates_this_yr = [time.strftime(\"%Y.%m.%d\", time.strptime(\"%d/%d\" % (i, year),\n \"%j/%Y\")) for i in\n range(doy_start, end_day)]\n dates.extend(dates_this_yr)\n return dates", "def construct_date_list():\n start = datetime.datetime.strptime(\"1989-04-16\", \"%Y-%m-%d\")\n end = datetime.datetime.strptime(datetime.datetime.strftime(datetime.datetime.now(), \"%Y-%m-%d\"), \"%Y-%m-%d\")\n \n date_generated = [start + datetime.timedelta(days=x) for x in range(0, (end-start).days + 1)]\n \n return date_generated", "def daterange(start_date, end_date):\n\n for n in range(int((end_date - start_date).days)):\n yield start_date + timedelta(n)", "def filter_by_date(self, cr, uid, lines, date_start=None,\\\n date_end=None, context={}):\n result = []\n \n for l in lines:\n if (date_start == None or l.period_id.date_start >= date_start)\\\n and (date_end == None or l.period_id.date_stop <= date_end):\n result.append(l) \n \n return result", "def next_period(self):\n\n # We can use this shortcut since dateranges are always normalized\n return self.from_date(self.upper, period=self.period)", "def period(self):\n\n start, end = None, None\n ranges = settings.OPENBUDGETS_PERIOD_RANGES\n\n # TODO: Support ranges other than yearly, including multiple ranges.\n if len(ranges) == 1 and 'yearly' in ranges:\n start = self.period_start.year\n if self.is_blueprint:\n objs = self.__class__.objects.filter(\n divisions__in=self.divisions.all())\n for obj in objs:\n if obj.period_start.year > self.period_start.year:\n end = obj.period_start.year\n else:\n end = datetime.datetime.now().year\n else:\n # We have 'implementation' templates that use a blueprint\n # as a model, and implement a variant structure based on it.\n # Such templates are used by single entities, and may be\n # employed by one or many sheets for that entity.\n objs = self.sheets.all()\n years = [obj.period_start.year for obj in objs].sort()\n if not years:\n end = start\n else:\n end = years[-1]\n\n return start, end", "def select_date_start_in_calendar(self, value):\n return self", "def getDateList(start, end=None):\n\n start_date_time = datetime.strptime(start, \"%Y%m%d\")\n if end is None:\n oneday = timedelta(days=1)\n end_date_time = start_date_time + oneday\n end = end_date_time.strftime(\"%Y%m%d\")\n return start, end\n else:\n end_date_time = datetime.strptime(end, \"%Y%m%d\")\n delta = (end_date_time - start_date_time).days\n return [(start_date_time + timedelta(days=ii)).strftime(\"%Y%m%d\") for ii in xrange(0, delta + 1)][:-1]", "def get_calendardate_index(start: pd.datetime, end: pd.datetime):\n calendardate_index = []\n m_d_list = [[3,31],[6,30],[9, 30],[12, 31]]\n month_of_first_filing = start.month\n for i, year in enumerate(range(start.year, end.year + 1)):\n if i == 0:\n index_of_first_filing_in_m_d_list = [3,6,9,12].index(month_of_first_filing)\n for month_day in m_d_list[index_of_first_filing_in_m_d_list:]:\n calendardate_index.append(datetime(year=year, month=month_day[0], day=month_day[1]))\n continue\n for month_day in m_d_list:\n calendardate_index.append(datetime(year=year, month=month_day[0], day=month_day[1]))\n\n # Need to drop dates after end\n for j, date in enumerate(calendardate_index):\n if date > end:\n del calendardate_index[j]\n\n return calendardate_index", "def get_search_list(start_date, end_date, min_date, max_date, \n prev_month_length, num_days, num_years):\n # import necessary modules\n import numpy as np\n import datetime as dt\n \n # create empty lists\n search_dates = []\n sorted_search_dates = []\n \n # iterate through dates and return complete list in dt format\n for i in np.arange(num_years):\n for j in np.arange(num_days + 1):\n if end_date.day - j <= 0:\n search_dates.append((dt.date(max_date.year - i, \n end_date.month - 1,\n prev_month_length - (abs(end_date.day - j)))))\n else:\n search_dates.append((dt.date(max_date.year - i, \n end_date.month,\n end_date.day - j)))\n \n # iterate through list and return list of lists with dt objects by day\n for i in np.arange(num_days + 1):\n temp_list = []\n for j in np.arange(num_years):\n if j == 0:\n temp_list.append(search_dates[i])\n else:\n temp_list.append(search_dates[i + (j * 7)])\n \n sorted_search_dates.append(temp_list)\n \n return sorted_search_dates;", "def test_intervals_date_input_start_stop(self):\n intervals = fleming.intervals(\n datetime.date(2013, 3, 1), datetime.timedelta(days=1), stop_dt=datetime.date(2013, 3, 11))\n self.assertEquals(\n list(intervals), [\n datetime.date(2013, 3, 1), datetime.date(2013, 3, 2),\n datetime.date(2013, 3, 3), datetime.date(2013, 3, 4),\n datetime.date(2013, 3, 5), datetime.date(2013, 3, 6),\n datetime.date(2013, 3, 7), datetime.date(2013, 3, 8),\n datetime.date(2013, 3, 9), datetime.date(2013, 3, 10),\n ])" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculating trailing calc_period zscores for residuals = y y_predicted from simulation_begin_date to last date, the regressand is always Price Returns.
def calculate_trailing_residual_zscores(df_input, regressor_col_name, simulation_begin_date, calc_period): df = df_input.copy() all_dates = df[DATE_COL_NAME] dates = df.loc[df[DATE_COL_NAME] >= simulation_begin_date, DATE_COL_NAME].reset_index(drop=True) for date in dates: period_start_date = find_valid_period_start_date(all_dates, date, calc_period) data = df[(df[DATE_COL_NAME] >= period_start_date) & (df[DATE_COL_NAME] <= date)].reset_index(drop=True) x = data[regressor_col_name].values.reshape(-1, 1) y = np.array(data[PRICE_RETURNS_COL_NAME].values) regress_model = LinearRegression().fit(x, y) y_predicted = regress_model.predict(x) residuals = y - y_predicted curr_val = residuals[len(residuals) - 1] average_value = residuals.mean() std = residuals.std() zscore = (curr_val - average_value) / std df.loc[df[DATE_COL_NAME] == date, RESIDUAL_ZSCORE_COL_NAME] = zscore df = df.loc[df[DATE_COL_NAME] >= simulation_begin_date].reset_index(drop=True) return df
[ "def value_factor_backtest_monthly(real_yields, price_data, zscore_lookback, z_score_smoothening, n_securities, long_short, sample_start, sample_end):\n #Calculate Z-Score of Real Yields\n ry_zscore = (real_yields - real_yields.rolling(260*zscore_lookback).mean())/real_yields.rolling(260*zscore_lookback).std(ddof=1)\n ry_zscore = ry_zscore.dropna().rolling(z_score_smoothening).mean()\n \n #Merge Z-Score & Total Return Indices Data\n data = ry_zscore.merge(price_data, on='DATE').dropna()\n \n #Convert Data Frequency to Rebalancing Frequency\n #data = data1.asfreq(\"\"+str(rebalancing_period)+\"D\")\n month1 = pd.Series(data.index.month)\n month2 = pd.Series(data.index.month).shift(-1)\n mask = (month1 != month2)\n data = data[mask.values]\n data = data[sample_start:sample_end]\n data.dropna(inplace=True)\n \n #Rename Columns for better understanding\n data.columns = ['IG 1-3 Yield', 'IG 3-5 Yield', 'IG 7-10 Yield', 'US HY Yield',\n 'Crossover Yield', 'EM High Yield', 'UST 1-3 Yield', 'UST Int Yield',\n 'UST 7-10 Yield', 'UST Long Yield', 'IG 1-3 YieldP', 'IG 3-5 YieldP', 'IG 7-10 YieldP', 'US HY YieldP',\n 'Crossover YieldP', 'EM High YieldP', 'UST 1-3 YieldP', 'UST Int YieldP',\n 'UST 7-10 YieldP', 'UST Long YieldP']\n \n #Calculate Backtest Returns based on Long/Short or Long/Only and the no. of securities\n rets = data['Crossover Yield'].copy()*0\n rets.name = 'Value Strategy'\n \n if long_short == 'No':\n for i in range(len(data)-1):\n if n_securities == 1:\n rets[i+1] = data[str(data.iloc[i,:10].idxmax())+'P'][i+1]/data[str(data.iloc[i,:10].idxmax())+'P'][i]-1\n elif n_securities == 2:\n rets[i+1] = (data[str(data.iloc[i,:10].idxmax())+'P'][i+1]/data[str(data.iloc[i,:10].idxmax())+'P'][i]-1 + data[str(data.iloc[i,:10].sort_values()[:9].idxmax())+'P'][i+1]/data[str(data.iloc[i,:10].sort_values()[:9].idxmax())+'P'][i]-1)/2\n elif n_securities == 3:\n rets[i+1] = (data[str(data.iloc[i,:10].idxmax())+'P'][i+1]/data[str(data.iloc[i,:10].idxmax())+'P'][i]-1 + data[str(data.iloc[i,:10].sort_values()[:9].idxmax())+'P'][i+1]/data[str(data.iloc[i,:10].sort_values()[:9].idxmax())+'P'][i]-1 + + data[str(data.iloc[i,:10].sort_values()[:8].idxmax())+'P'][i+1]/data[str(data.iloc[i,:10].sort_values()[:8].idxmax())+'P'][i]-1)/3\n \n if long_short == 'Yes':\n for i in range(len(data)-1):\n if n_securities == 1:\n rets[i+1] = data[str(data.iloc[i,:10].idxmax())+'P'][i+1]/data[str(data.iloc[i,:10].idxmax())+'P'][i]-1 - data[str(data.iloc[i,:10].sort_values()[0:].idxmin())+'P'][i+1]/data[str(data.iloc[i,:10].sort_values()[0:].idxmin())+'P'][i]-1\n elif n_securities == 2:\n rets[i+1] = (data[str(data.iloc[i,:10].idxmax())+'P'][i+1]/data[str(data.iloc[i,:10].idxmax())+'P'][i]-1 + data[str(data.iloc[i,:10].sort_values()[:9].idxmax())+'P'][i+1]/data[str(data.iloc[i,:10].sort_values()[:9].idxmax())+'P'][i]-1)/2 - (data[str(data.iloc[i,:10].sort_values()[0:].idxmin())+'P'][i+1]/data[str(data.iloc[i,:10].sort_values()[0:].idxmin())+'P'][i]-1 + data[str(data.iloc[i,:10].sort_values()[1:].idxmin())+'P'][i+1]/data[str(data.iloc[i,:10].sort_values()[1:].idxmin())+'P'][i]-1)/2\n elif n_securities == 3:\n rets[i+1] = (data[str(data.iloc[i,:10].idxmax())+'P'][i+1]/data[str(data.iloc[i,:10].idxmax())+'P'][i]-1 + data[str(data.iloc[i,:10].sort_values()[:9].idxmax())+'P'][i+1]/data[str(data.iloc[i,:10].sort_values()[:9].idxmax())+'P'][i]-1 + data[str(data.iloc[i,:10].sort_values()[:8].idxmax())+'P'][i+1]/data[str(data.iloc[i,:10].sort_values()[:8].idxmax())+'P'][i]-1)/3 - (data[str(data.iloc[i,:10].sort_values()[0:].idxmin())+'P'][i+1]/data[str(data.iloc[i,:10].sort_values()[0:].idxmin())+'P'][i]-1 + data[str(data.iloc[i,:10].sort_values()[1:].idxmin())+'P'][i+1]/data[str(data.iloc[i,:10].sort_values()[1:].idxmin())+'P'][i]-1 + data[str(data.iloc[i,:10].sort_values()[2:].idxmin())+'P'][i+1]/data[str(data.iloc[i,:10].sort_values()[2:].idxmin())+'P'][i]-1)/3\n \n \n #Merge Value Factor Returns Data with original data and other individual securities returns \n data = data.merge(rets, on='DATE')\n data.columns = ['IG 1-3 Yield', 'IG 3-5 Yield', 'IG 7-10 Yield', 'US HY Yield',\n 'Crossover Yield', 'EM High Yield', 'UST 1-3 Yield', 'UST Int Yield',\n 'UST 7-10 Yield', 'UST Long Yield', 'IG 1-3', 'IG 3-5', 'IG 7-10', 'US HY',\n 'Crossover', 'EM HY', 'UST 1-3', 'UST Int',\n 'UST 7-10', 'UST Long', 'Value Strategy']\n m_rets = data[['IG 1-3', 'IG 3-5', 'IG 7-10', 'US HY', 'Crossover', 'EM HY', 'UST 1-3', 'UST Int', 'UST 7-10', 'UST Long']].pct_change().dropna().merge(rets, on='DATE')\n \n #Add Equally Weighted Portfolio Returns for comparison as well\n m_rets['EW'] = m_rets[['IG 1-3', 'IG 3-5', 'IG 7-10', 'US HY', 'Crossover', 'EM HY', 'UST 1-3', 'UST Int', 'UST 7-10', 'UST Long']].mean(axis=1)\n \n return m_rets", "def test_predict_residuals():\n from sktime.forecasting.base import ForecastingHorizon\n from sktime.forecasting.model_selection import temporal_train_test_split\n from sktime.forecasting.theta import ThetaForecaster\n\n y = _make_series(n_columns=1)\n y_train, y_test = temporal_train_test_split(y)\n fh = ForecastingHorizon(y_test.index, is_relative=False)\n forecaster = ThetaForecaster(sp=12)\n forecaster.fit(y_train, fh=fh)\n\n y_pred_1 = forecaster.predict()\n y_resid = forecaster.predict_residuals()\n y_pred_2 = forecaster.predict()\n assert_series_equal(y_pred_1, y_pred_2)\n assert y_resid.index.equals(y_train.index)", "def run_residual_trade_simulation(trade_simul_data, zscore_buy_long=-1.5, zscore_cover_long=-0.5, zscore_sell_short=1.5,\n zscore_cover_short=0.5):\n\tdata = trade_simul_data[[DATE_COL_NAME, PRICE_COL_NAME, RESIDUAL_ZSCORE_COL_NAME]]\n\ttrades = pd.DataFrame(\n\t\tcolumns=[DATE_COL_NAME, PRICE_COL_NAME, RESIDUAL_ZSCORE_COL_NAME, ACTION_COL_NAME, HOLDING_PERIOD_COL_NAME,\n\t\t PROFIT_DELTA_COL_NAME, CUMULATIVE_PROFIT_COL_NAME])\n\tdates = trade_simul_data[DATE_COL_NAME]\n\tcontinuos_profits = pd.DataFrame(\n\t\tcolumns=[DATE_COL_NAME, PRICE_COL_NAME, PROFIT_DELTA_COL_NAME, CUMULATIVE_PROFIT_COL_NAME])\n\tcontinuos_profits[DATE_COL_NAME] = dates\n\tcontinuos_profits[PRICE_COL_NAME] = trade_simul_data[PRICE_COL_NAME]\n\t\n\ttrade_position = TradePosition.NO_POSITION\n\tcum_realized_profit = 0\n\tcum_continous_profit = 0\n\tfor i in data.index.values:\n\t\trow = data.iloc[i]\n\t\tcurr_date = row[DATE_COL_NAME]\n\t\tcurr_price = row[PRICE_COL_NAME]\n\t\tresidual_zscore = row[RESIDUAL_ZSCORE_COL_NAME]\n\t\tdaily_profit_delta = 0\n\t\t\n\t\tif trade_position == TradePosition.NO_POSITION:\n\t\t\tholding_period = 0\n\t\t\trealized_profit_delta = 0\n\t\t\tif residual_zscore <= zscore_buy_long:\n\t\t\t\taction = TradeAction.BUY_LONG\n\t\t\t\ttrade_row = list(\n\t\t\t\t\tnp.concatenate([row.values,\n\t\t\t\t\t [action, holding_period, realized_profit_delta,\n\t\t\t\t\t cum_realized_profit]]))\n\t\t\t\ttrades = append_row(trades, trade_row)\n\t\t\t\ttrade_position = TradePosition.LONG\n\t\t\telif residual_zscore >= zscore_sell_short:\n\t\t\t\taction = TradeAction.SELL_SHORT\n\t\t\t\ttrade_row = list(\n\t\t\t\t\tnp.concatenate([row.values,\n\t\t\t\t\t [action, holding_period, realized_profit_delta,\n\t\t\t\t\t cum_realized_profit]]))\n\t\t\t\ttrades = append_row(trades, trade_row)\n\t\t\t\ttrade_position = TradePosition.SHORT\n\t\telse:\n\t\t\tprevious_day_price = data.iloc[i - 1, 1]\n\t\t\tentry_date = trades.iloc[-1, 0]\n\t\t\tholding_period = (curr_date - entry_date).days\n\t\t\tentry_price = trades.iloc[-1, 1]\n\t\t\tif trade_position == TradePosition.LONG:\n\t\t\t\tdaily_profit_delta = curr_price - previous_day_price\n\t\t\t\tif residual_zscore >= zscore_cover_long:\n\t\t\t\t\taction = TradeAction.COVER_LONG\n\t\t\t\t\trealized_profit_delta = curr_price - entry_price\n\t\t\t\t\tcum_realized_profit += realized_profit_delta\n\t\t\t\t\ttrade_row = list(\n\t\t\t\t\t\tnp.concatenate([row.values,\n\t\t\t\t\t\t [action, holding_period, realized_profit_delta,\n\t\t\t\t\t\t cum_realized_profit]]))\n\t\t\t\t\ttrades = append_row(trades, trade_row)\n\t\t\t\t\ttrade_position = TradePosition.NO_POSITION\n\t\t\telif trade_position == TradePosition.SHORT:\n\t\t\t\tdaily_profit_delta = previous_day_price - curr_price\n\t\t\t\tif residual_zscore <= zscore_cover_short:\n\t\t\t\t\taction = TradeAction.COVER_SHORT\n\t\t\t\t\trealized_profit_delta = entry_price - curr_price\n\t\t\t\t\tcum_realized_profit += realized_profit_delta\n\t\t\t\t\ttrade_row = list(\n\t\t\t\t\t\tnp.concatenate([row.values,\n\t\t\t\t\t\t [action, holding_period, realized_profit_delta,\n\t\t\t\t\t\t cum_realized_profit]]))\n\t\t\t\t\ttrades = append_row(trades, trade_row)\n\t\t\t\t\ttrade_position = TradePosition.NO_POSITION\n\t\t\tcum_continous_profit += daily_profit_delta\n\t\t\n\t\tcontinuos_profits.iloc[i, 2] = daily_profit_delta\n\t\tcontinuos_profits.iloc[i, 3] = cum_continous_profit\n\t\n\treturn trades, continuos_profits", "def fit_predict(self, test_time_range):\n\t\t#Date boundaries for test\n\t\tfirst_date = test_time_range[0].date()\n\t\tlast_date = test_time_range[-1].date()\n\t\tn_days = (last_date - first_date).days + 1 #retrive days attribute from timedelta\n\t\t#Empty arrays to store forecast\n\t\tforecast_length = n_days * self._cycle_length #Length of forecast vectors\n\t\tdaily_seasonal_forecast = empty(forecast_length)\n\t\tweekly_seasonal_forecast = empty(forecast_length)\n\t\tdeseasonalized_forecast = empty(forecast_length)\n\t\t#Align linked list with beginning of test\n\t\ttrav = self._patterns._tail \n\t\twhile trav._date != first_date:\n\t\t\ttrav = trav._prev \n\t\t#Forecast routine\n\t\tk = 0 #Forecast day counter\n\t\twhile trav and trav._date != last_date + self._cycle_length * Timedelta(1, 'H'): #Traverse patterns day by day\n\t\t\tprint(\"Forecasting day \", k+1, \" of \", n_days) #Progress\n\t\t\t#deseasonalized component forecast\n\t\t\tdeseasonalized_comp = empty(self._cycle_length) #Empty vector to store values\n\t\t\tfor t in range(self._cycle_length):\n\t\t\t\telement = self._point_deseasonalized_forecast(trav, t)\n\t\t\t\tdeseasonalized_forecast[k*self._cycle_length + t] = element\t\n\t\t\tdaily_seasonal_forecast[k * self._cycle_length: (k+1) * self._cycle_length] = self._season_forecast(trav, 24) #First seasonal\tcomponent\n\t\t\tweekly_seasonal_forecast[k * self._cycle_length: (k+1) * self._cycle_length] = self._season_forecast(trav, 168) #Second seasonalcomponent\t\n\t\t\ttrav = trav._next #Move to next day\n\t\t\tk = k + 1 #Increase forecast day counter\n\t\t#Store predicitions in model - convert to pandas Series\n\t\tself._full_forecast = Series(deseasonalized_forecast + weekly_seasonal_forecast + daily_seasonal_forecast, index=test_time_range)\n\t\tself._deseasonalized_forecast = Series(deseasonalized_forecast, index=test_time_range)\n\t\tself._daily_seasonal_forecast = Series(daily_seasonal_forecast, index=test_time_range)\n\t\tself._weekly_seasonal_forecast = Series(weekly_seasonal_forecast, index=test_time_range)\n\n\t\treturn self._full_forecast", "def avg_predictions(df_grp_2, cal_df, fisc_calender, pred_start, fpg, res_all_sp):\r\n pivot_var = \"MM\"\r\n agg_col = \"LINE_ORDERS\"\r\n var_list = ['prev_5wk_avg_4wk_hld']\r\n level_list = list(df_grp_2[pivot_var].unique())\r\n \r\n tt = df_grp_2.copy()\r\n level = \"wk\"\r\n # Rearrange date by fiscal weeks\r\n tt = cu.merge_cal_tt(tt, cal_df.drop('FISC_EOW_DT', axis = 1), level)\r\n tt[agg_col+\"_ACT\"] = tt[agg_col]\r\n tt[agg_col].replace(np.nan, 0, inplace=True)\r\n \r\n model_data_pivot = pd.pivot_table(tt,\r\n index=['FISC_YR_NBR', 'FISC_MTH_NBR','FISC_WK_OF_MTH_ID', 'FISC_WK_OF_YR_NBR', 'FISC_QTR_NBR'],\r\n columns=pivot_var,\r\n values=agg_col).reset_index()\r\n model_data_pivot = cu.merge_cal_tt(model_data_pivot, cal_df, level)\r\n\r\n model_data_pivot = cu.fillna_values(model_data_pivot, pred_start)\r\n for i in level_list:\r\n if str(i) not in model_data_pivot.columns:\r\n model_data_pivot[str(i)] = 0\r\n tt = model_data_pivot.copy()\r\n train = tt[(tt.FISC_WK_OF_MTH_ID < pred_start) ]\r\n test = tt[(tt.FISC_WK_OF_MTH_ID >= pred_start) ]\r\n for i in level_list:\r\n if str(i) not in train.columns:\r\n train[str(i)] = 0\r\n if str(i) not in test.columns:\r\n test[str(i)] = 0\r\n \r\n model_data_orders_df = prev_avg_sparsity_scoring(level_list, train, test, \"_salesMAPP_prev_5wk_avg_4wk_hld\")\r\n model_data_orders_melt_df = cu.lag_variable_melt(agg_col, model_data_orders_df, var_list)\r\n model_data_orders_melt_df.columns = model_data_orders_melt_df.columns.str.replace(\"variable\", pivot_var)\r\n model_data_orders_melt_df[\"RSS\"] = fpg\r\n model_data_orders_melt_df[\"RSS_MM\"] = model_data_orders_melt_df[\"RSS\"]+\"_\"+model_data_orders_melt_df[pivot_var]\r\n model_data_orders_melt_df = pd.merge(model_data_orders_melt_df, \r\n df_grp_2[[\"FISC_WK_OF_MTH_ID\", pivot_var, agg_col, \"SPARSITY\"]], how =\"left\")\r\n \r\n model_data_orders_melt_df.columns = model_data_orders_melt_df.columns.str.replace(\"LINE_ORDERS_VALUE\", \"Prediction_Trf\")\r\n model_data_orders_melt_df = model_data_orders_melt_df[['FISC_YR_NBR', 'FISC_MTH_NBR', 'FISC_WK_OF_MTH_ID',\r\n pivot_var, 'Prediction_Trf', 'RSS', 'RSS_MM']]\r\n res_all_sp.append(model_data_orders_melt_df)\r\n \r\n return res_all_sp", "def get_final_df(model, data):\n # if predicted future price is higher than the current,\n # then calculate the true future price minus the current price, to get the buy profit\n buy_profit = lambda current, true_future, pred_future: true_future - current if pred_future > current else 0\n # if the predicted future price is lower than the current price,\n # then subtract the true future price from the current price\n sell_profit = lambda current, true_future, pred_future: current - true_future if pred_future < current else 0\n X_test = data[\"X_test\"]\n y_test = data[\"y_test\"]\n # perform prediction and get prices\n y_pred = model.predict(X_test)\n print(\"Y_PRED\")\n print(y_pred.shape)\n if SCALE:\n y_test = np.squeeze(data[\"column_scaler\"][\"adjclose\"].inverse_transform(np.expand_dims(y_test, axis=0)))\n y_pred = np.squeeze(data[\"column_scaler\"][\"adjclose\"].inverse_transform(y_pred))\n\n print(y_pred)\n test_df = data[\"test_df\"]\n # add predicted future prices to the dataframe\n test_df[f\"adjclose_{LOOKUP_STEP}\"] = y_pred\n # add true future prices to the dataframe\n test_df[f\"true_adjclose_{LOOKUP_STEP}\"] = y_test\n # sort the dataframe by date\n test_df.sort_index(inplace=True)\n final_df = test_df\n # add the buy profit column\n final_df[\"buy_profit\"] = list(map(buy_profit,\n final_df[\"adjclose\"],\n final_df[f\"adjclose_{LOOKUP_STEP}\"],\n final_df[f\"true_adjclose_{LOOKUP_STEP}\"])\n # since we don't have profit for last sequence, add 0's\n )\n # add the sell profit column\n final_df[\"sell_profit\"] = list(map(sell_profit,\n final_df[\"adjclose\"],\n final_df[f\"adjclose_{LOOKUP_STEP}\"],\n final_df[f\"true_adjclose_{LOOKUP_STEP}\"])\n # since we don't have profit for last sequence, add 0's\n )\n return final_df", "def iterative_forecast(\n predictor: Predictor,\n train: pd.DataFrame,\n lags: int,\n exog: pd.DataFrame = None,\n periods: int = 1,\n against_baseline = False\n ):\n\n add_exog = exog is not None\n \n variables = train.columns.tolist()\n \n # Define first period to forecast\n last_day = train.index[-1]\n append_period = last_day - relativedelta(months=lags - 1)\n\n endog_X = train[append_period:last_day].to_numpy()\n\n if add_exog:\n exog_X = exog[append_period:last_day].to_numpy()\n iter_day = last_day\n \n y_hat = []\n \n for _ in range(periods):\n\n if add_exog:\n X = fit_into_row(endog_X, exog_X)\n\n # Update the exogenous variable\n exog_X[:-1] = exog_X[1:]\n iter_day = last_day + relativedelta(months=1)\n exog_X[-1] = exog.loc[iter_day]\n\n else:\n X = endog_X.reshape(-1, 1)\n\n forecast = predictor(X)\n \n endog_X[:-1] = endog_X[1:]\n endog_X[-1] = forecast[\"mean\"]\n \n y_hat.append(forecast)\n\n \n end_date = last_day + relativedelta(months=periods - 1) \n index = pd.date_range(start=last_day, end=end_date, freq=\"MS\")\n compact_forecast = pd.DataFrame(y_hat, index = index)\n \n df = pd.DataFrame(index = index)\n \n # Expand columns\n for column in compact_forecast.columns:\n \n expanded_column = compact_forecast[column].apply(pd.Series)\n expanded_column = expanded_column.rename(columns = lambda i: f\"{variables[i]}_{column}\")\n \n df = pd.concat([df[:], expanded_column[:]], axis=1)\n\n if against_baseline:\n baseline_model = AR1(train)\n baseline_forecast = baseline_model(periods - 1)\n\n df = pd.concat((df, baseline_forecast), axis = 1)\n\n \n return df", "def momentum_factor_backtest_monthly(price_data, rebal, lookback_period, n_securities, long_short, sample_start, sample_end):\n mom = price_data.pct_change(lookback_period).dropna()\n \n mom.columns= ['IG 1-3Y', 'IG 3-5Y', 'IG 7-10Y', 'US HY', 'Crossover', 'EM HY',\n '1-3Y UST', 'Intermediate UST', '7-10Y UST', 'Long Term UST']\n price_data.columns = ['IG 1-3YM', 'IG 3-5YM', 'IG 7-10YM', 'US HYM', 'CrossoverM', 'EM HYM',\n '1-3Y USTM', 'Intermediate USTM', '7-10Y USTM', 'Long Term USTM']\n\n data = mom.merge(price_data, on='DATE')\n \n #Convert Data Frequency to Rebalancing Frequency\n #data = data.asfreq(\"\"+str(rebalancing_period)+\"D\")\n if rebal =='Monthly':\n month1 = pd.Series(data.index.month)\n month2 = pd.Series(data.index.month).shift(-1)\n elif rebal =='Quarterly':\n month1 = pd.Series(data.index.quarter)\n month2 = pd.Series(data.index.quarter).shift(-1)\n mask = (month1 != month2)\n data = data[mask.values]\n data = data[sample_start:sample_end]\n data.dropna(inplace=True)\n \n rets = data['Crossover'].copy()*0\n rets.name = 'Momentum Strategy'\n \n if long_short == 'No':\n for i in range(len(data)-1):\n if n_securities == 1:\n rets[i+1] = data[str(data.iloc[i,:10].idxmax())+'M'][i+1]/data[str(data.iloc[i,:10].idxmax())+'M'][i]-1\n elif n_securities == 2:\n rets[i+1] = (data[str(data.iloc[i,:10].idxmax())+'M'][i+1]/data[str(data.iloc[i,:10].idxmax())+'M'][i]-1 + data[str(data.iloc[i,:10].sort_values()[:9].idxmax())+'M'][i+1]/data[str(data.iloc[i,:10].sort_values()[:9].idxmax())+'M'][i]-1)/2\n elif n_securities == 3:\n rets[i+1] = (data[str(data.iloc[i,:10].idxmax())+'M'][i+1]/data[str(data.iloc[i,:10].idxmax())+'M'][i]-1 + data[str(data.iloc[i,:10].sort_values()[:9].idxmax())+'M'][i+1]/data[str(data.iloc[i,:10].sort_values()[:9].idxmax())+'M'][i]-1 + data[str(data.iloc[i,:10].sort_values()[:8].idxmax())+'M'][i+1]/data[str(data.iloc[i,:10].sort_values()[:8].idxmax())+'M'][i]-1)/3\n \n if long_short == 'Yes':\n for i in range(len(data)-1):\n if n_securities == 1:\n rets[i+1] = data[str(data.iloc[i,:10].idxmax())+'M'][i+1]/data[str(data.iloc[i,:10].idxmax())+'M'][i]-1 - data[str(data.iloc[i,:10].sort_values()[0:].idxmin())+'M'][i+1]/data[str(data.iloc[i,:10].sort_values()[0:].idxmin())+'M'][i]-1\n elif n_securities == 2:\n rets[i+1] = (data[str(data.iloc[i,:10].idxmax())+'M'][i+1]/data[str(data.iloc[i,:10].idxmax())+'M'][i]-1 + data[str(data.iloc[i,:10].sort_values()[:9].idxmax())+'M'][i+1]/data[str(data.iloc[i,:10].sort_values()[:9].idxmax())+'M'][i]-1)/2 - (data[str(data.iloc[i,:10].sort_values()[0:].idxmin())+'M'][i+1]/data[str(data.iloc[i,:10].sort_values()[0:].idxmin())+'M'][i]-1 + data[str(data.iloc[i,:10].sort_values()[1:].idxmin())+'M'][i+1]/data[str(data.iloc[i,:10].sort_values()[1:].idxmin())+'M'][i]-1)/2\n elif n_securities == 3:\n rets[i+1] = (data[str(data.iloc[i,:10].idxmax())+'M'][i+1]/data[str(data.iloc[i,:10].idxmax())+'M'][i]-1 + data[str(data.iloc[i,:10].sort_values()[:9].idxmax())+'M'][i+1]/data[str(data.iloc[i,:10].sort_values()[:9].idxmax())+'M'][i]-1 + data[str(data.iloc[i,:10].sort_values()[:8].idxmax())+'M'][i+1]/data[str(data.iloc[i,:10].sort_values()[:8].idxmax())+'M'][i]-1)/3 - (data[str(data.iloc[i,:10].sort_values()[0:].idxmin())+'M'][i+1]/data[str(data.iloc[i,:10].sort_values()[0:].idxmin())+'M'][i]-1 + data[str(data.iloc[i,:10].sort_values()[1:].idxmin())+'M'][i+1]/data[str(data.iloc[i,:10].sort_values()[1:].idxmin())+'M'][i]-1 + data[str(data.iloc[i,:10].sort_values()[2:].idxmin())+'M'][i+1]/data[str(data.iloc[i,:10].sort_values()[2:].idxmin())+'M'][i]-1)/3\n \n \n #Merge Value Factor Returns Data with original data and other individual securities returns \n data = data.merge(rets, on='DATE')\n data.columns = ['IG 1-3 Yield', 'IG 3-5 Yield', 'IG 7-10 Yield', 'US HY Yield',\n 'Crossover Yield', 'EM High Yield', 'UST 1-3 Yield', 'UST Int Yield',\n 'UST 7-10 Yield', 'UST Long Yield', 'IG 1-3', 'IG 3-5', 'IG 7-10', 'US HY',\n 'Crossover', 'EM HY', 'UST 1-3', 'UST Int',\n 'UST 7-10', 'UST Long', 'Momentum Strategy']\n m_rets = data[['IG 1-3', 'IG 3-5', 'IG 7-10', 'US HY', 'Crossover', 'EM HY', 'UST 1-3', 'UST Int', 'UST 7-10', 'UST Long']].pct_change().dropna().merge(rets, on='DATE')\n \n #Add Equally Weighted Portfolio Returns for comparison as well\n m_rets['EW'] = m_rets[['IG 1-3', 'IG 3-5', 'IG 7-10', 'US HY', 'Crossover', 'EM HY', 'UST 1-3', 'UST Int', 'UST 7-10', 'UST Long']].mean(axis=1)\n \n return m_rets", "def calcResiduals(self, params):\n self.rr.reset() # Put back to time zero\n # Update the simulation parameters\n for name, value in params.valuesdict().items():\n self.rr[name] = value\n fittedArr = self.rr.simulate(0, self.observedTS.end,\n len(self.observedTS))\n self._fittedArr = fittedArr.copy()\n fittedArr = fittedArr[:, 1:] # Delete time column\n observedArr = self.observedTS[self.colnames]\n self._residualsArr = observedArr - fittedArr\n residualsArr = self._residualsArr.flatten()\n return residualsArr", "def recursive(self, y, model):\n \n # get the dates to forecast\n last_date = y.index[-1] + pd.Timedelta(hours=1)\n fcast_range = pd.date_range(last_date, periods=self.n_steps, freq=self.step)\n\n fcasted_values = []\n target = y.copy()\n\n for date in fcast_range:\n\n new_point = fcasted_values[-1] if len(fcasted_values) > 0 else 0.0 \n target = target.append(pd.Series(index=[date], data=new_point))\n\n # forecast\n ts_features = create_ts_features(target)\n if len(self.lags) > 0:\n lags_features = create_lag_features(target, lags=self.lags)\n features = ts_features.join(lags_features, how=\"outer\").dropna()\n else:\n features = ts_features\n \n predictions = model.predict(features)\n fcasted_values.append(predictions[-1])\n\n return pd.Series(index=fcast_range, data=fcasted_values)", "def assess_portfolio(\n sd = dt.datetime(2008,1,1), ed = dt.datetime(2009,1,1), \\\n syms = ['GOOG','AAPL','GLD','XOM'], \\\n allocs=[0.1,0.2,0.3,0.4], \\\n sv=1000000, rfr=0.0, sf=252.0, \\\n gen_plot=False):\n \n # read in adjusted closing prices for given symbols, date range\n # adding SPY to allocation for calulations and trading days\n dates = pd.date_range(sd.date(), ed.date())\n df_all = get_data(syms, dates) # automatically adds SPY\n df = df_all[syms] \n \n # get daily portfolio value \n df_nrm = df / df.ix[0,:] \n allocated = df_nrm * allocs\n position_values = allocated * sv\n port_value = position_values.sum(axis = 1)\n # daily returns (y_{t} = x_{t}/x_{t-1} - 1\n d_returns = port_value.copy() \n d_returns = (port_value/port_value.shift(1) - 1)\n d_returns = d_returns[1:]\n \n # Below are desired output values\n \n # cumulative return (final - initial) - 1\n cr = port_value[-1] / port_value[0] - 1\n # average daily return\n adr = d_returns.mean()\n # standard deviation of daily return\n sddr = d_returns.std()\n # sharpe ratio ((Mean - Risk free rate)/Std_dev)\n daily_rfr = (1.0 - rfr)**(1/252) - 1 #Should this be sampling freq instead of 252? \n sr = (d_returns - daily_rfr).mean() / sddr\n sr_annualized = sr * (sf**0.5)\n \n # compare daily portfolio value with SPY using a normalized plot\n if gen_plot:\n df_nrm_SPY = df_all['SPY'] / df_all['SPY'].ix[0,:]\n \n port_value_norm = port_value / port_value.ix[0,:]\n port_vs_SPY = df_nrm_SPY.copy()\n port_vs_SPY = port_vs_SPY.to_frame().join(port_value_norm.to_frame('Portfolio'))\n \n ax_portfolio = port_vs_SPY.plot(title = 'Daily Returns against SPY', grid = True, legend = 'reverse')\n ax_portfolio.set_xlabel('Date')\n ax_portfolio.set_ylabel('Normalized Price')\n plt.show()\n \n # end value\n ev = port_value[-1]\n \n return cr, adr, sddr, sr_annualized, ev", "def prepare_inputs(self, RES, prediction_horizon=1, error_bar='cumulative'):\n assert prediction_horizon !=0, 'Error: prediction_horizon must be between 15 and 1.'\n\n #Add nb_lookback_days ??\n\n if error_bar=='cumulative':\n #Past inputs\n past_cases = RES['train_fit']\n past_derivative_true = np.concatenate((np.zeros(1).reshape(1,), np.diff(RES['train_data'], 1)), axis=0)\n past_derivative = np.concatenate((np.zeros(1).reshape(1,), np.diff(past_cases, 1)), axis=0)\n past_error = np.abs(RES['train_data'] - RES['train_fit'])\n past_error2 = past_error**2\n past_error_relative = np.abs(past_derivative_true - past_derivative)/(past_derivative_true+0.001)\n past_error_relative[0] = 0.0 #Remove NaN\n past_error_relative2 = past_error_relative**2\n past_stringency = RES['stringency_data'].ravel()[:self.training_window]\n\n if self._predict:\n bias_param = RES['result'].params['b'].value\n coeff_param = RES['result'].params['w1'].value\n #Compute beta rate\n past_beta = coeff_param*past_stringency + bias_param\n\n elif not self._predict:\n past_beta = RES['beta'].ravel()[:self.training_window]\n\n #Second derivative\n past2nd_derivative = np.concatenate((RES['train_fit'][1:] , np.zeros(1).reshape(1,)), axis=0) -2*RES['train_fit'] + np.concatenate((np.zeros(1).reshape(1,), RES['train_fit'][:-1] ), axis=0)\n past2nd_derivative_true = np.concatenate((RES['train_data'][1:] , np.zeros(1).reshape(1,)), axis=0) -2*RES['train_data'] + np.concatenate((np.zeros(1).reshape(1,), RES['train_data'][:-1] ), axis=0)\n\n self.deriv2_true.append(past2nd_derivative_true)\n self.deriv2.append(past2nd_derivative)\n\n #Target at different horizons\n targets = np.abs(RES['test_data'] - RES['test_predicted'])\n\n #Get target at horizon i\n target = np.abs(targets[prediction_horizon-1])\n\n #if prediction_horizon ==1:\n\n inputs = np.stack((past_cases, past_derivative, past_derivative_true, past_error, past_error2, past_error_relative, past_error_relative2, past2nd_derivative, past2nd_derivative_true,\n past_stringency, past_beta), axis=0)\n #print(past_derivative)\n #print(past_derivative_true)\n #print(past_error_relative)\n #print(past2nd_derivative)\n #print(past2nd_derivative_true)\n #return (target, inputs0)\n\n elif error_bar=='derivative':\n #Past inputs\n past_cases = RES['train_fit']\n past_cases_true = RES['train_data']\n past_derivative_fit = np.concatenate((np.zeros(1).reshape(1,), np.diff(past_cases, 1)), axis=0)\n past_derivative_true = np.concatenate((np.zeros(1).reshape(1,), np.diff(past_cases_true, 1)), axis=0)\n\n past_error = np.abs(past_derivative_true - past_derivative_fit)\n past_error2 = past_error**2\n\n past_stringency = RES['stringency_data'].ravel()[:self.training_window]\n past_beta = RES['beta'].ravel()[:self.training_window]\n\n #Target at different horizons\n test_cases_true = RES['test_data']\n test_cases_preds = RES['test_predicted']\n test_derivative_preds = np.concatenate((past_derivative_fit[-1].reshape(1,), np.diff(test_cases_preds, 1)), axis=0)\n test_derivative_true = np.concatenate((past_derivative_true[-1].reshape(1,), np.diff(test_cases_true, 1)), axis=0)\n\n targets = np.abs(test_derivative_true - test_derivative_preds)\n\n #Get target at horizon i\n target = np.abs(targets[prediction_horizon-1])\n\n #if prediction_horizon ==1:\n inputs = np.stack((past_cases, past_derivative_fit, past_error, past_error2, past_stringency, past_beta), axis=0)\n\n elif error_bar =='relative':\n #Past inputs\n past_cases = RES['train_fit'][1:]\n past_derivative_true = np.diff(RES['train_data'], 1)\n past_derivative_fit = np.diff(RES['train_fit'], 1)\n past_error = np.abs(RES['train_data'][1:] - RES['train_fit'][1:])/past_derivative_true\n past_error2 = past_error**2\n past_stringency = RES['stringency_data'].ravel()[1:self.training_window]\n past_beta = RES['beta'].ravel()[1:self.training_window]\n\n #Target at different horizons\n test_derivative_true = np.concatenate(( past_derivative_true[-1].reshape(1,) , np.diff(RES['test_data'], 1)), axis=0)\n targets = np.abs(RES['test_data'] - RES['test_predicted'])/test_derivative_true\n\n #Get target at horizon i\n target = np.abs(targets[prediction_horizon-1])\n\n #if prediction_horizon ==1:\n inputs = np.stack((past_cases, past_derivative_fit, past_error, past_error2, past_stringency, past_beta), axis=0)\n\n #elif prediction_horizon >1:\n #Stack inputs\n #past_cases = np.stack((past_cases, RES['test_data'][:prediction_horizon-2]), axis=0)\n #past_derivative = np.stack((past_cases), 1)\n #past_error = np.stack((past_error, targets[:prediction_horizon-2]))\n #past_error2 = np.stack((past_error2, targets[:prediction_horizon-2]**2))\n\n #past_stringency = RES['stringency_data'][:250+prediction_horizon-1]\n #past_beta = RES['beta'][:250+prediction_horizon-1]\n\n #inputs = np.stack((past_cases, past_derivative, past_error, past_error2, past_stringency, past_beta), axis=0)\n return (target, inputs)", "def compute_df(real_stock_data, period_utils):\n df = real_stock_data.df\n\n months = period_utils.months\n gross_returns = (1 + df['m_return']).rolling(months, 1).apply(np.prod) - 1\n gross_returns = gross_returns.shift(-months)\n\n returns = period_utils.annualized_returns(gross_returns)\n\n return pd.DataFrame({'gross_returns': gross_returns, 'returns': returns}, index=df.index)", "def run_simple_backtest(symbol, rule_variant=['EWMAC', '2,8'], start_date=dt.date(2017, 1, 1), end_year=dt.date.today().year,\r\n starting_capital=1000000.0, volatility_target=0.25):\r\n auth_token = 'g1CWzGxxg2WxNVbV5n9y'\r\n\r\n # set scalar variables\r\n start_year = start_date.year\r\n instrument_weight = 1.0\r\n instrument_diversifier_multiplier = 1.0\r\n position_inertia = 0.1\r\n\r\n # determine which rule for which to run forecast\r\n forecast_inputs = get_forecast_inputs(symbol, start_year, end_year)\r\n if rule_variant[0] == 'CARRY':\r\n df = calc_carry_forecasts(forecast_inputs)\r\n elif rule_variant[0] == 'EWMAC':\r\n fast = int(rule_variant[1].split(',')[0])\r\n slow = int(rule_variant[1].split(',')[1])\r\n df = calc_ewmac_forecasts(forecast_inputs, fast, slow)\r\n elif rule_variant[0] == 'RSI':\r\n span = int(rule_variant[1])\r\n df = calc_rsi_forecasts(forecast_inputs, span)\r\n df['InstrumentForecast'] = df['ForecastCapped']\r\n\r\n # calculate instrument value vol\r\n futures_info = get_futures_info()\r\n df['BlockSize'] = futures_info.loc[futures_info['Symbol'] == symbol, 'BlockSize'].values[0]\r\n df['BlockValue'] = df['SettleRaw'] * df['BlockSize'] * 0.01\r\n df['InstrumentCurVol'] = df['BlockValue'] * df['PriceVolatilityPct'] * 100\r\n # incorporate historical fx rates\r\n fx_symbol = futures_info.loc[futures_info['Symbol'] == symbol, 'FX'].values[0]\r\n if fx_symbol != 'USD':\r\n fx_symbol = 'CURRFX/' + futures_info.loc[futures_info['Symbol'] == symbol, 'FX'].values[0]\r\n fx_rates = quandl.get(fx_symbol, authtoken=auth_token)\r\n # fx_rates.columns = ['Rate']\r\n df = df.merge(fx_rates, how='left', left_index=True, right_index=True)\r\n df = df.fillna(method='ffill') # fill in missing FX rates\r\n else:\r\n df['Rate'] = 1.0\r\n df['InstrumentValueVol'] = df['InstrumentCurVol'] / df['Rate']\r\n\r\n # begin backtest\r\n # cutoff first 90 trading days of data\r\n df = df.iloc[90:]\r\n # placeholders below\r\n df['PortfolioValue'] = starting_capital\r\n df['DailyCashTargetVol'] = starting_capital * volatility_target / (256 ** 0.5)\r\n df['VolatilityScalar'] = 0.0\r\n df['SubsystemPosition'] = 0.0\r\n df['SystemPosition'] = 0.0\r\n df['StartingPosition'] = 0.0\r\n df['EndingPosition'] = 0.0\r\n df['PositionChange'] = 0.0\r\n df['PositionCost'] = 0.0\r\n df['PositionValue'] = 0.0\r\n df['GainLossCum'] = 0.0\r\n\r\n # iterate through each date in df to retrieve ForecastCapped and InstrumentValueVol\r\n for i in list(range(0, len(df))):\r\n active_date = df.index[i]\r\n\r\n # update capital balance and volatility targets based on gain loss in backtest_df\r\n if i != 0: # skip first day\r\n df.loc[active_date, 'PositionCost'] += df['PositionCost'][prev_date]\r\n df.loc[active_date, 'PositionValue'] += df['PositionValue'][prev_date]\r\n df.loc[active_date, 'GainLossCum'] += df['GainLossCum'][prev_date]\r\n df.loc[active_date, 'PortfolioValue'] = starting_capital + df['GainLossCum'][active_date]\r\n df.loc[active_date, 'DailyCashTargetVol'] = df['PortfolioValue'][active_date] * \\\r\n volatility_target / (256 ** 0.5)\r\n df.loc[active_date, 'VolatilityScalar'] = df['DailyCashTargetVol'][active_date] / df['InstrumentValueVol'][active_date]\r\n df.loc[active_date, 'SubsystemPosition'] = df['InstrumentForecast'][active_date] / 10.0 * df['VolatilityScalar'][active_date]\r\n df.loc[active_date, 'SystemPosition'] = df['SubsystemPosition'][active_date] * instrument_weight * \\\r\n instrument_diversifier_multiplier\r\n if i != 0: # skip first day\r\n df.loc[active_date, 'StartingPosition'] = df['EndingPosition'].loc[prev_date]\r\n\r\n # determine trade based on starting_position, ending_position and system_position\r\n # define variable to minimize space\r\n starting_position = df['StartingPosition'][active_date]\r\n ending_position = starting_position\r\n system_position = df['SystemPosition'][active_date]\r\n block_size = df['BlockSize'][active_date]\r\n block_price = df['SettleRaw'][active_date]\r\n fx_rate = df['Rate'][active_date]\r\n\r\n if starting_position == 0 or (np.abs((system_position - starting_position) / starting_position) >\r\n position_inertia):\r\n ending_position = np.round(system_position, 0)\r\n df.loc[active_date, 'EndingPosition'] = ending_position\r\n df.loc[active_date, 'PositionChange'] = ending_position - starting_position\r\n if i != 0: # skip first day; else set PositionCost equal to previous value\r\n df.loc[active_date, 'PositionCost'] = df['PositionCost'].loc[prev_date]\r\n df.loc[active_date, 'PositionCost'] += (ending_position - starting_position) * block_size * block_price\r\n # reset PositionCost when contracts roll\r\n if i != 0 and df.loc[active_date, 'Contract'] != df['Contract'][prev_date]:\r\n df.loc[active_date, 'PositionCost'] = ending_position * block_price * block_size - \\\r\n (df['GainLossCum'][prev_date] * fx_rate)\r\n df.loc[active_date, 'PositionValue'] = ending_position * block_size * block_price\r\n df.loc[active_date, 'GainLossCum'] = (df['PositionValue'][active_date] - df['PositionCost'][active_date]) / fx_rate\r\n prev_date = active_date\r\n\r\n # calculate backtest summary statistics\r\n df['PortfolioReturnDayPct'] = df['PortfolioValue'] / df['PortfolioValue'].shift(1) - 1.0\r\n rule = rule_variant[0]\r\n variant = rule_variant[1] if rule == 'EWMAC' else ''\r\n trading_days = df.shape[0]\r\n annualized_return = np.exp(np.nansum(np.log(1 + df['PortfolioReturnDayPct']))) ** (256.0 / trading_days) - 1.0\r\n annualized_volatility = np.std(df['PortfolioReturnDayPct']) * np.sqrt(256.0)\r\n sharpe_ratio = annualized_return / annualized_volatility\r\n blocks_traded = np.sum(np.abs(df['PositionChange']))\r\n avg_position = np.average(np.abs(df['EndingPosition']))\r\n annualized_turnover = blocks_traded / (2 * avg_position) * 256.0 / trading_days\r\n results_df = pd.DataFrame({'Symbol': symbol, 'Rule': rule, 'Variant': variant, 'AnnReturn': annualized_return,\r\n 'AnnVol': annualized_volatility, 'Sharpe': sharpe_ratio, 'Trades': blocks_traded,\r\n 'AvgPosition': avg_position, 'AnnTurnover': annualized_turnover,\r\n 'StartingCapital': starting_capital, 'TargetVolatility': volatility_target,\r\n 'TradingDays': trading_days}, index=[0])\r\n return results_df[['Symbol', 'Rule', 'Variant', 'AnnReturn', 'AnnVol', 'Sharpe', 'Trades', 'AvgPosition',\r\n 'AnnTurnover', 'TradingDays']], df", "def calculate_zscore(df, col_name, period_start_date, period_end_date):\n\tdata = df.loc[\n\t\t(df[DATE_COL_NAME] >= period_start_date) & (df[DATE_COL_NAME] <= period_end_date), col_name]\n\tcurr_value = df.loc[df[DATE_COL_NAME] == period_end_date, col_name].values[0]\n\taverage_value = data.mean()\n\tstd = data.std()\n\tzscore = (curr_value - average_value) / std\n\tdf.loc[df[DATE_COL_NAME] == period_end_date, col_name + Z_SCORE_POSTFIX] = zscore\n\treturn df", "def mlBacktest(clf, df, exfeat, startdate=None, todate=None):\n\n # Setting up the output - designed as a pandas data panel (3D)\n startdate = dt.datetime(2013, 12, 31) if startdate is None else startdate\n todate = dt.datetime(2016, 12, 31) if todate is None else todate\n dframe = df.resample('W').sum()\n dt_range = pd.date_range(start=startdate, end=todate, freq='W')\n cols = ['Pred', 'P1', 'P2', 'P3', 'P4', 'P5', 'Act', 'ActLabel', 'PrevMean', 'PrevSD',\n 'RF', 'SF', 'CumAccRF', 'CumAccSF']\n\n output = pd.Panel(items=dt_range, major_axis=cols, minor_axis=dframe.columns)\n forwards = dframe.shift(-1)\n\n # running the backtest at weekly intervals for specified date range\n for count, wdate in enumerate(dt_range):\n # calling the classify function and getting the required results\n pDate, pPred, pProbs, pScore = classify(clf, dframe=dframe, exfeat=exfeat, todate=wdate)\n dfPreds = pd.DataFrame(pPred, index=dframe.columns)\n dfProbs = pd.DataFrame(pProbs, index=dframe.columns, columns=['P1', 'P2', 'P3', 'P4', 'P5'])\n\n # recording the outputs in the output panel\n output.loc[wdate].ix['Pred'] = dfPreds.values.flatten()\n output.loc[wdate].iloc[1:6] = dfProbs.values.reshape(5, len(dfProbs))\n output.loc[wdate].ix['Act'] = forwards.loc[wdate]\n\n prev_mean = dframe.ix[:wdate][:-1].mean()\n prev_std = dframe.ix[:wdate][:-1].std()\n\n for name in dframe.columns:\n output.loc[wdate][name].ix['PrevMean'] = prev_mean[name]\n output.loc[wdate][name].ix['PrevSD'] = prev_std[name]\n output.loc[wdate][name].ix['ActLabel'] = cLabel(output.loc[wdate][name].ix['Act'],\n prev_mean[name], prev_std[name])\n if output.loc[wdate][name].ix['ActLabel']==\\\n output.loc[wdate][name].ix['Pred']:\n output.loc[wdate][name].ix['RF'] = 1\n else:\n output.loc[wdate][name].ix['RF'] = 0\n if np.sign(output.loc[wdate][name].ix['Pred'])==\\\n np.sign(output.loc[wdate][name].ix['ActLabel']):\n output.loc[wdate][name].ix['SF'] = 1\n else:\n output.loc[wdate][name].ix['SF'] = 0\n output.loc[wdate].ix['CumAccRF'] = (output.loc[:wdate].ix[:, 'RF'].sum(axis=1) /\n output.loc[:wdate].ix[:, 'RF'].count(axis=1))\n output.loc[wdate].ix['CumAccSF'] = (output.loc[:wdate].ix[:, 'SF'].sum(axis=1) /\n output.loc[:wdate].ix[:, 'SF'].count(axis=1))\n return output", "def momentum_factor_backtest(price_data, rebal, lookback_period, duration_adj, n_securities, long_short, sample_start, sample_end, cost, spread=0, lev_factor=1, trans_cost=0.00):\n if duration_adj== 'Yes':\n mom = price_data.pct_change(lookback_period).dropna()/[1,2,4,8,25,10,10,8,3,2,5,24,10,5,4,9,6,6,6,4,8,4]\n else:\n mom = price_data.pct_change(lookback_period).dropna()\n \n cols = list(price_data.columns)\n mom.columns= price_data.columns\n price_data.columns = price_data.columns + str('M')\n\n data = mom.merge(price_data, on='Date')\n \n #Convert Data Frequency to Rebalancing Frequency\n #data = data.asfreq(\"\"+str(rebalancing_period)+\"D\")\n if rebal =='Monthly':\n month1 = pd.Series(data.index.month)\n month2 = pd.Series(data.index.month).shift(-1)\n elif rebal =='Quarterly':\n month1 = pd.Series(data.index.quarter)\n month2 = pd.Series(data.index.quarter).shift(-1)\n mask = (month1 != month2)\n data = data[mask.values]\n #data = data[sample_start:sample_end]\n data.dropna(inplace=True)\n \n transcost = pd.DataFrame(index = data.index)\n transcost['TransCost'] = (trans_cost/10000)*lev_factor\n transcost.index.name='Date' \n \n rets = pd.DataFrame(columns=['Long1', 'Long2', 'Long3', 'Short1', 'Short2', 'Short3'], index=data.index)\n rets.name = 'Momentum Strategy'\n \n for i in range(len(rets)):\n rets['Long1'][i] = str(data.iloc[i,:len(price_data.columns)].idxmax()) + 'M'\n rets['Long2'][i] = str(data.iloc[i,:len(price_data.columns)].sort_values()[:len(price_data.columns)-1].idxmax())+'M'\n rets['Long3'][i] = str(data.iloc[i,:len(price_data.columns)].sort_values()[:len(price_data.columns)-2].idxmax())+'M'\n rets['Short1'][i] = str(data.iloc[i,:len(price_data.columns)].sort_values()[0:].idxmin())+'M'\n rets['Short2'][i] = str(data.iloc[i,:len(price_data.columns)].sort_values()[1:].idxmin())+'M'\n rets['Short3'][i] = str(data.iloc[i,:len(price_data.columns)].sort_values()[2:].idxmin())+'M'\n \n data_new = data.merge(rets[['Long1', 'Long2', 'Long3', 'Short1', 'Short2', 'Short3']], on='Date')\n #new_data.dropna(inplace=True)\n new_data = price_data.join(data_new[['Long1', 'Long2', 'Long3', 'Short1', 'Short2', 'Short3']], on='Date')[rets.index[0]:].ffill()\n \n new_data['Returns'] = new_data.iloc[:,1].copy()*0\n \n if long_short == 'No':\n for i in range(len(new_data)-1):\n if n_securities == 1:\n new_data['Returns'][i+1] = new_data[new_data['Long1'][i]][i+1] / new_data[new_data['Long1'][i]][i] - 1\n elif n_securities == 2:\n new_data['Returns'][i+1] = ((new_data[new_data['Long1'][i]][i+1] / new_data[new_data['Long1'][i]][i] - 1) + \n (new_data[new_data['Long2'][i]][i+1] / new_data[new_data['Long2'][i]][i] - 1))/2\n elif n_securities == 3:\n new_data['Returns'][i+1] = ((new_data[new_data['Long1'][i]][i+1] / new_data[new_data['Long1'][i]][i] - 1) + \n (new_data[new_data['Long2'][i]][i+1] / new_data[new_data['Long2'][i]][i] - 1) + \n (new_data[new_data['Long3'][i]][i+1] / new_data[new_data['Long3'][i]][i] - 1))/3\n \n if long_short == 'Yes':\n for i in range(len(new_data)-1):\n if n_securities == 1:\n new_data['Returns'][i+1] = (new_data[new_data['Long1'][i]][i+1] / new_data[new_data['Long1'][i]][i] - 1)-(new_data[new_data['Short1'][i]][i+1] / new_data[new_data['Short1'][i]][i] - 1) \n elif n_securities == 2:\n new_data['Returns'][i+1] = ((new_data[new_data['Long1'][i]][i+1] / new_data[new_data['Long1'][i]][i] - 1) + \n (new_data[new_data['Long2'][i]][i+1] / new_data[new_data['Long2'][i]][i] - 1))/2 - ((new_data[new_data['Short1'][i]][i+1] / new_data[new_data['Short1'][i]][i] - 1) + \n (new_data[new_data['Short2'][i]][i+1] / new_data[new_data['Short2'][i]][i] - 1))/2\n elif n_securities == 3:\n new_data['Returns'][i+1] = ((new_data[new_data['Long1'][i]][i+1] / new_data[new_data['Long1'][i]][i] - 1) + \n (new_data[new_data['Long2'][i]][i+1] / new_data[new_data['Long2'][i]][i] - 1) + \n (new_data[new_data['Long3'][i]][i+1] / new_data[new_data['Long3'][i]][i] - 1))/3 - ((new_data[new_data['Short1'][i]][i+1] / new_data[new_data['Short1'][i]][i] - 1) + \n (new_data[new_data['Short2'][i]][i+1] / new_data[new_data['Short2'][i]][i] - 1) + \n (new_data[new_data['Short3'][i]][i+1] / new_data[new_data['Short3'][i]][i] - 1))/3\n \n #Merge Value Factor Returns Data with original data and other individual securities returns \n final_rets = new_data.iloc[:,:len(price_data.columns)].pct_change().dropna().merge(new_data['Returns'], on='Date')\n cols.append('Momentum Factor')\n final_rets.columns = cols\n \n #Add Equally Weighted Portfolio Returns for comparison as well\n final_rets['EW'] = final_rets.iloc[:, :len(final_rets.columns)-1].mean(axis=1)\n \n final_rets = final_rets.merge(cost['EFFR']+spread/(10000*252), on='Date')\n\n final_rets = (final_rets.drop('EFFR',axis=1) * lev_factor).subtract(final_rets['EFFR']*(lev_factor-1), axis='rows')\n \n final_rets = final_rets.join(transcost['TransCost'], on='Date')\n final_rets['TransCost'] = final_rets['TransCost'].fillna('0')\n final_rets['TransCost'] = final_rets['TransCost'].astype('float64')\n final_rets['Momentum Factor'] = (final_rets['Momentum Factor']).subtract(final_rets['TransCost']*lev_factor, axis='rows')\n final_rets = final_rets.drop('TransCost', axis=1) \n \n return final_rets[sample_start:sample_end]", "def backcalculate_predictions(df, predictions, num_hist_bars, num_predict_bars):\n rs_preds = predictions.reshape(-1, num_predict_bars, 5)\n\n all_preds = []\n print('backcalculating values...')\n for i in tqdm(range(rs_preds.shape[0])):\n # get the point just before the predictions for\n # calculating actual value from pct_chg\n point = df.iloc[i + num_hist_bars - 1]\n pr = back_calc_one_point_pct(point, rs_preds[i])\n all_preds.append(pr)\n\n return all_preds", "def calculate_expected_beta(self, spy_df: pd.DataFrame) -> None:\n df = pd.merge(pd.DataFrame(self.portfolio_daily_returns), spy_df, on = 'date', how = 'inner')\n self.expected_beta = df['weighted_ret'].cov(df['spy_dailyret']) / df['spy_dailyret'].var()" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Processing raw input Cef data which may take some time. Calculating factors for conducting analysis and saving data to new csv file. This method should be called only if we made changes to TRAIN_DATA_RATIO, AVERAGES_CALC_PERIOD, START_DATE etc.
def calculate_cef_data(symbol, analysis_data_period, calc_period): print("Processing data ... Please wait ... for 'Data processing finished!' indication below!") df = read_raw_cef_data(symbol) dates = df[DATE_COL_NAME].reset_index(drop=True) end_date = str(dates.values[-1]).split("T")[0] end_date = datetime.strptime(end_date, "%Y-%m-%d") start_date = find_valid_period_start_date(dates, end_date, analysis_data_period) df = calculate_factors(df, start_date, calc_period).reset_index(drop=True) df = df.loc[df[DATE_COL_NAME] >= start_date].reset_index(drop=True) file_name = symbol.lower() + DATA_FILE_POSTFIX path = DATA_PATH_PREFIX + file_name df.to_csv(path) print("Data processing finished!")
[ "def process(self):\n\n print(\n f\"Transit processing all lightcurves data product: {self.all_lightcurves_dataproduct}\"\n )\n\n self.extract_and_save_lightcurves()\n\n self.create_best_light_curve_and_fit_image()", "def _common_read(csv_file, raters):\n \n # Import a csv file as a dataframe \n df = pd.read_csv(csv_file)\n\n # Name of studies with an evaluation and its associated score\n indices_name_studies = df.loc[ (df['Time'] == \"pre\")\n & (df['Raters'] == raters),\n ['Mean', 'Std']\n ].isnull().sum(axis=1).index\n name_studies = df.loc[indices_name_studies, 'Author']\n score_name = df.loc[indices_name_studies, 'Score Name']\n\n\n # Extract treatment values \n treatment_indices_pre = df[ \n (df['Time'] == \"pre\") \n & (df['Raters'] == raters)\n ].index\n n_treatment = df.loc[treatment_indices_pre, 'Number of patients']\n mean_pre_test_treatment = df.loc[treatment_indices_pre, 'Mean']\n std_pre_test_treatment = df.loc[treatment_indices_pre, 'Std']\n \n treatment_indices_post = df[\n (df['Time'] == \"post\") \n & (df['Raters'] == raters)\n ].index\n mean_post_test_treatment = df.loc[treatment_indices_post, 'Mean']\n std_post_test_treatment = df.loc[treatment_indices_post, 'Std']\n \n\n # Extract factors\n pblind = df.loc[treatment_indices_pre, 'Probably Blind']\n number_of_sessions = df.loc[treatment_indices_pre, 'Number of sessions']\n SMR = df.loc[treatment_indices_pre, 'SMR']\n theta_up = df.loc[treatment_indices_pre, 'Theta up']\n beta_up_central = df.loc[treatment_indices_pre, 'Beta up central']\n theta_down = df.loc[treatment_indices_pre, 'Theta down']\n beta_up_frontal = df.loc[treatment_indices_pre, 'Beta up frontal']\n SCP = df.loc[treatment_indices_pre, 'SCP']\n on_drugs = df.loc[treatment_indices_pre, 'On drugs during treatment assessments']\n age_min = df.loc[treatment_indices_pre, 'Age min']\n age_max = df.loc[treatment_indices_pre, 'Age max']\n randomization = df.loc[treatment_indices_pre, 'Randomization']\n IRB = df.loc[treatment_indices_pre, 'Institutional Review Board']\n transfer_phase = df.loc[treatment_indices_pre, 'Transfer phase']\n transfer_card = df.loc[treatment_indices_pre, 'Transfer card']\n EOG_correction_or_rejection = df.loc[treatment_indices_pre, 'EOG correction or rejection']\n amplitude_based_artifact_rejection = df.loc[treatment_indices_pre, 'Amplitude based artifact rejection']\n thresholding = df.loc[treatment_indices_pre, 'Thresholding']\n session_pace = df.loc[treatment_indices_pre, 'Session pace (per week)']\n session_length = df.loc[treatment_indices_pre, 'Session length (min)']\n treatment_length = df.loc[treatment_indices_pre, 'Treatment length (weeks)']\n more_than_one_active_electrode = df.loc[treatment_indices_pre, '>1 active electrode']\n EEG_quality = df.loc[treatment_indices_pre, 'EEG quality']\n control_group = df.loc[treatment_indices_pre, 'Control group']\n individualisation_iapf = df.loc[treatment_indices_pre, 'Indivualisation (iAPF)']\n EMG_biofeedback = df.loc[treatment_indices_pre, 'EMG biofeedback']\n engagement_with_treatment = df.loc[treatment_indices_pre, 'Engagement with treatment']\n maximum_on_clinical_scale = df.loc[treatment_indices_pre, 'Maximum on clinical scale']\n \n # Creation of the data frame containing the results\n df_values = pd.DataFrame({'n_treatment': n_treatment.tolist(),\n 'score_name': score_name.tolist(),\n 'mean_pre_test_treatment': mean_pre_test_treatment.tolist(),\n 'mean_post_test_treatment': mean_post_test_treatment.tolist(),\n 'std_pre_test_treatment': std_pre_test_treatment.tolist(),\n 'std_post_test_treatment': std_post_test_treatment.tolist(),\n 'raters': raters,\n 'pblind': pblind.tolist(),\n 'number_of_sessions': number_of_sessions.tolist(),\n 'SMR': SMR.tolist(),\n 'theta_up': theta_up.tolist(),\n 'theta_down': theta_down.tolist(),\n 'beta_up_central': beta_up_central.tolist(),\n 'beta_up_frontal': beta_up_frontal.tolist(),\n 'SCP': SCP.tolist(), \n 'on_drugs': on_drugs.tolist(),\n 'age_min': age_min.tolist(),\n 'age_max': age_max.tolist(),\n 'randomization': randomization.tolist(),\n 'IRB': IRB.tolist(),\n 'transfer_phase': transfer_phase.tolist(),\n 'transfer_card': transfer_card.tolist(),\n 'EOG_correction_or_rejection': EOG_correction_or_rejection.tolist(),\n 'amplitude_based_artifact_rejection': amplitude_based_artifact_rejection.tolist(), \n 'thresholding': thresholding.tolist(),\n 'session_pace': session_pace.tolist(),\n 'session_length': session_length.tolist(),\n 'treatment_length': treatment_length.tolist(),\n 'more_than_one_active_electrode': more_than_one_active_electrode.tolist(),\n 'EEG_quality': EEG_quality.tolist(),\n 'control_group': control_group.tolist(),\n 'individualisation_iapf': individualisation_iapf.tolist(),\n 'EMG_biofeedback': EMG_biofeedback.tolist(),\n 'engagement_with_treatment': engagement_with_treatment.tolist(),\n 'maximum_on_clinical_scale': maximum_on_clinical_scale.tolist()},\n index=[name_studies])\n \n return df_values", "def train():\n files = os.listdir(os.getcwd())\n for filename in files:\n if fnmatch.fnmatch(filename, '555*.csv'):\n cid = filename.split('.')[0]\n df = pd.read_csv(filename)\n time = df['MeasTimestampRF']\n df = df[cols]\n process(df, cid)", "def data_process(data_point_dict, line, oldline, thedate, error_dir, qc_dir, bad_data_val=6999) :\n # current data types for processing:\n # num = normal float\n # therm = thermistor... specify the coefficients in the coefficient table.\n # poly = polynomial... specify the coefficients in the coefficient table.\n # net = net radiation... specify in the coefficients table the windspeed column so net can be corrected if needed\n # precip = Could do a totalize down the road but for present, maybe check the air temperature (column specified in the coefficients table again)\n \n\n\n \n old_line_str = oldline.split(',')\n line_str = line.split(',')\n ### Okay, before ramping up... need to account for \"NAN\" of Table based loggers right here.\n temp_de = line_str[ int( data_point_dict[ 'Input_Array_Pos' ] ) ]\n temp_ode = old_line_str[ int( data_point_dict[ 'Input_Array_Pos' ] ) ] \n # .isdigit() was failing testing the whole floating point number so now we're just looking at the last character / digit.\n if temp_de[-1].isdigit() :\n data_element = float( temp_de )\n else :\n data_element = float(bad_data_val)\n \n if len(temp_ode)>1:\n if temp_ode[-1].isdigit() :\n old_data_element = float( temp_ode)\n else :\n old_data_element = float(bad_data_val)\n else:\n old_data_element = float(bad_data_val)\n\n if data_point_dict['Data_Type'] == 'num' or data_point_dict['Data_Type'] == 'net' or data_point_dict['Data_Type'] == 'precip':\n # process as a number, no number crunching to do.\n processed_value = qc_check(data_element, \\\n old_data_element, \\\n thedate, \\\n qc_dir, \\\n data_point_dict['d_element'], \\\n data_point_dict['Qc_Param_High'], \\\n data_point_dict['Qc_Param_Low'], \\\n data_point_dict['QC_Param_Step'], \\\n float(bad_data_val) )\n\n elif data_point_dict['Data_Type'] == 'therm' :\n processed_value = thermistor(data_element, \\\n float(data_point_dict['Coef_1']), \\\n float(data_point_dict['Coef_2']), \\\n float(data_point_dict['Coef_3']), \\\n float(data_point_dict['Coef_4']), \\\n bad_data_val)\n old_processed_value = thermistor(old_data_element, \\\n float(data_point_dict['Coef_1']), \\\n float(data_point_dict['Coef_2']), \\\n float(data_point_dict['Coef_3']), \\\n float(data_point_dict['Coef_4']), \\\n float(bad_data_val))\n processed_value = qc_check(processed_value, \\\n old_processed_value, \\\n thedate, \\\n qc_dir, \\\n data_point_dict['d_element'], \\\n data_point_dict['Qc_Param_High'], \\\n data_point_dict['Qc_Param_Low'], \\\n data_point_dict['QC_Param_Step'], \\\n float(bad_data_val) )\n \n elif data_point_dict['Data_Type'] == 'thermF' :\n processed_value = thermistor(data_element, \\\n float(data_point_dict['Coef_1']), \\\n float(data_point_dict['Coef_2']), \\\n float(data_point_dict['Coef_3']), \\\n float(data_point_dict['Coef_4']), \\\n bad_data_val)\n old_processed_value = thermistor(old_data_element, \\\n float(data_point_dict['Coef_1']), \\\n float(data_point_dict['Coef_2']), \\\n float(data_point_dict['Coef_3']), \\\n float(data_point_dict['Coef_4']), \\\n float(bad_data_val))\n processed_value = qc_check(processed_value, \\\n old_processed_value, \\\n thedate, \\\n qc_dir, \\\n data_point_dict['d_element'], \\\n data_point_dict['Qc_Param_High'], \\\n data_point_dict['Qc_Param_Low'], \\\n data_point_dict['QC_Param_Step'], \\\n float(bad_data_val) )\n if processed_value != float(bad_data_val) :\n processed_value = processed_value * 9 / 5 + 32\n\n elif data_point_dict['Data_Type'] == 'poly' :\n processed_value = poly(data_element, \\\n float(data_point_dict['Coef_1']), \\\n float(data_point_dict['Coef_2']), \\\n float(data_point_dict['Coef_3']), \\\n float(data_point_dict['Coef_4']), \\\n float(data_point_dict['Coef_5']), \\\n float(data_point_dict['Coef_6']), \\\n float(data_point_dict['Coef_7']), \\\n bad_data_val)\n old_processed_value = poly(old_data_element, \\\n float(data_point_dict['Coef_1']), \\\n float(data_point_dict['Coef_2']), \\\n float(data_point_dict['Coef_3']), \\\n float(data_point_dict['Coef_4']), \\\n float(data_point_dict['Coef_5']), \\\n float(data_point_dict['Coef_6']), \\\n float(data_point_dict['Coef_7']), \\\n bad_data_val)\n processed_value = qc_check(processed_value, \\\n old_processed_value, \\\n thedate, \\\n qc_dir, \\\n data_point_dict['d_element'], \\\n data_point_dict['Qc_Param_High'], \\\n data_point_dict['Qc_Param_Low'], \\\n data_point_dict['QC_Param_Step'], \\\n float(bad_data_val) )\n elif data_point_dict['Data_Type'] == 'flux':\n \n \n processed_value = flux(data_element, \\\n float(data_point_dict['Coef_1']), \\\n float(data_point_dict['Coef_2']), \\\n bad_data_val)\n old_processed_value = flux(old_data_element, \\\n float(data_point_dict['Coef_1']), \\\n float(data_point_dict['Coef_2']), \\\n bad_data_val)\n processed_value = qc_check(processed_value, \\\n old_processed_value, \\\n thedate, \\\n qc_dir, \\\n data_point_dict['d_element'], \\\n data_point_dict['Qc_Param_High'], \\\n data_point_dict['Qc_Param_Low'], \\\n data_point_dict['QC_Param_Step'], \\\n float(bad_data_val) )\n elif data_point_dict['Data_Type'] == 'netrad':\n #data_point_dict['Coef_3'] indicates the column of the windspeed in the input data\n #NOTE: windspeed is considered to be zero if speed is less than .3 m/s\n if data_point_dict['Coef_3']!=0:\n\n wind_speed = line_str[int(data_point_dict['Coef_3'])]\n\n processed_value = netrad(data_element,\\\n float(wind_speed), \\\n float(data_point_dict['Coef_1']), \\\n float(data_point_dict['Coef_2']), \\\n bad_data_val)\n old_processed_value = netrad(old_data_element,\\\n float(wind_speed), \\\n float(data_point_dict['Coef_1']), \\\n float(data_point_dict['Coef_2']), \\\n bad_data_val)\n processed_value = qc_check(processed_value, \\\n old_processed_value, \\\n thedate, \\\n qc_dir, \\\n data_point_dict['d_element'], \\\n data_point_dict['Qc_Param_High'], \\\n data_point_dict['Qc_Param_Low'], \\\n data_point_dict['QC_Param_Step'], \\\n float(bad_data_val) )\n else:\n processed_value = flux(data_element, \\\n float(data_point_dict['Coef_1']), \\\n float(data_point_dict['Coef_2']), \\\n bad_data_val)\n old_processed_value = flux(old_data_element, \\\n float(data_point_dict['Coef_1']), \\\n float(data_point_dict['Coef_2']), \\\n bad_data_val)\n processed_value = qc_check(processed_value, \\\n old_processed_value, \\\n thedate, \\\n qc_dir, \\\n data_point_dict['d_element'], \\\n data_point_dict['Qc_Param_High'], \\\n data_point_dict['Qc_Param_Low'], \\\n data_point_dict['QC_Param_Step'], \\\n float(bad_data_val) )\n \n elif data_point_dict['Data_Type'] == 'rt_sensor' :\n\n processed_value = rt_sensor(data_element, \\\n float(data_point_dict['Coef_1']), \\\n float(data_point_dict['Coef_2']), \\\n float(data_point_dict['Coef_3']), \\\n bad_data_val)\n old_processed_value = rt_sensor(old_data_element, \\\n float(data_point_dict['Coef_1']), \\\n float(data_point_dict['Coef_2']), \\\n float(data_point_dict['Coef_3']), \\\n bad_data_val)\n processed_value = qc_check(processed_value, \\\n old_processed_value, \\\n thedate, \\\n qc_dir, \\\n data_point_dict['d_element'], \\\n data_point_dict['Qc_Param_High'], \\\n data_point_dict['Qc_Param_Low'], \\\n data_point_dict['QC_Param_Step'], \\\n float(bad_data_val) ) \n else:\n processed_value = bad_data_val\n return (processed_value)\n # end of data_process function", "def process(self):\n processed_directory = self.directory / \"processed\"\n os.makedirs(processed_directory, exist_ok=True) # create directory if it doesn't exist\n\n # Import general election results & polling data\n results_dict = self.load_results_data()\n polls_full = self.load_polling_data()\n\n # Calculate poll of polls\n polls = self.get_regional_and_national_poll_of_polls(polls=polls_full)\n\n # Merge polls into previous election results dataframe\n results_dict[self.last] = self.combine_results_and_polls(\n results=results_dict[self.last], polls=polls\n )\n\n # Add into previous election results: national voteshare, national swing (vs current polling),\n # national swing forecast (per party per seat) and national swing forecast winner (per seat).\n results_dict[self.last] = self.calculate_national_swing(results_dict[self.last])\n\n # If we have geo-polling for previous election, also calculate a geo-level swing forecast.\n if \"geo_polls\" in results_dict[self.last].columns:\n results_dict[self.last] = self.calculate_geo_swing(results_dict[self.last])\n\n # Create ML-ready dataframe and export\n model_df = self.export_model_ready_dataframe(results_dict=results_dict)\n\n print(f\"Exporting {self.last}->{self.now} model dataset to {processed_directory.resolve()}\")\n model_df.to_csv(\n processed_directory / f\"general_election-uk-{self.now}-model.csv\", index=False\n )", "def read_and_preprocess_crime_data():\n\n df_train = pd.read_csv(CrimeParams.PATH_TRAIN, delimiter=\",\")\n df_validation = pd.read_csv(CrimeParams.PATH_VALIDATION, delimiter=\",\")\n df_test = pd.read_csv(CrimeParams.PATH_TEST, delimiter=\",\")\n \"\"\"\n # Load the data itself.\n with gfile.Open(CrimeParams.CNS_PATH_TRAIN) as f:\n df_train = pd.read_csv(f)\n with gfile.Open(CrimeParams.CNS_PATH_VALIDATION) as f:\n df_validation = pd.read_csv(f)\n with gfile.Open(CrimeParams.CNS_PATH_TEST) as f:\n df_test = pd.read_csv(f)\"\"\"\n\n # Get names of columns that should be used as features.\n feature_names = [\n c\n for c in df_train.keys() # pylint: disable=g-complex-comprehension\n if c\n not in list(CrimeParams.EXCLUDED_COLUMNS)\n + [CrimeParams.LABEL_COLUMN, CrimeParams.REGRESSION_TARGET_COLUMN]\n ]\n\n # Replace missing feature values with per-column training set means.\n for column in feature_names:\n train_mean = df_train[column].mean()\n df_train[column].fillna(train_mean, inplace=True)\n df_validation[column].fillna(train_mean, inplace=True)\n df_test[column].fillna(train_mean, inplace=True)\n\n # Just use the validation data for training.\n df_train = pd.concat([df_train, df_validation])\n\n # All done!\n return df_train, df_test, feature_names", "def run_analytics(self):\n print()\n print(\"CLASSIFIER ANALYSIS: \")\n print()\n self.calculate_precision()\n print()\n self.calculate_recall()\n print()\n self.calculate_fbeta_score()\n print()\n print(\"=== Accuracy ===\")\n print(\"Model Accuracy:\", self.calculate_accuracy())", "def load_and_preprocesss():\n #####################################\n # 1. Load Dataset #\n #####################################\n loadDataset = LoadDataset()\n review_list, rating_list, gender_list, location_list, age_list = loadDataset.load_file(dataset_dir + file_path)\n\n\n #####################################\n # 2. Data Pre-processing #\n #####################################\n dataPreprocessing = DataPreprocessing()\n\n labeled_gender_list = dataPreprocessing.label_gender(gender_list)\n labeled_age_list = dataPreprocessing.label_age(age_list)\n assert len(review_list) == len(rating_list) == len(labeled_age_list) == len(labeled_gender_list) == len(\n location_list)\n\n # Check if there exists a directory to save processed files\n if not os.path.exists(processed_langid_dir):\n os.mkdir(processed_langid_dir)\n\n # Form csv files and save\n form_csv(review_list, rating_list, labeled_gender_list, labeled_age_list, location_list,\n processed_langid_dir + csv_filename)\n\n print(\"Write to csv successfully!\\n\")\n\n\n #####################################\n # 3. Language Double Check #\n #####################################\n # Check if there exists a directory to save fasttext processed files\n if not os.path.exists(processed_fasttext_dir):\n os.mkdir(processed_fasttext_dir)\n\n for file in sorted(os.listdir(processed_langid_dir)):\n if file.endswith(\".csv\"):\n fasttext_language_detection(filename=os.path.join(processed_langid_dir, file),\n new_filename=os.path.join(processed_fasttext_dir, file))", "def process_case_detection(self):\n\n self.time_variant_parameters['program_prop_detect'] \\\n = {i: j / 1e2 for i, j in self.original_data['tb']['c_cdr'].items()}\n self.time_variant_parameters['program_prop_detect'][1950] = 0.", "def updateCalibrationCoefs(inputCsvFile, outputCsvFile):\n\n d = pd.read_csv(inputCsvFile)\n # select participants with good spread of stationary values for calibration\n goodCal = d.loc[(d['quality-calibratedOnOwnData'] == 1) & (d['quality-goodCalibration'] == 1)]\n # now only select participants whose data was NOT calibrated on a good spread of stationary values\n badCal = d.loc[(d['quality-calibratedOnOwnData'] == 1) & (d['quality-goodCalibration'] == 0)]\n\n # sort files by start time, which makes selection of most recent value easier\n goodCal = goodCal.sort_values(['file-startTime'])\n badCal = badCal.sort_values(['file-startTime'])\n\n calCols = ['calibration-xOffset(g)', 'calibration-yOffset(g)', 'calibration-zOffset(g)',\n 'calibration-xSlope(g)', 'calibration-ySlope(g)', 'calibration-zSlope(g)',\n 'calibration-xTemp(C)', 'calibration-yTemp(C)', 'calibration-zTemp(C)',\n 'calibration-meanDeviceTemp(C)']\n\n # print output CSV file with suggested calibration parameters\n noOtherUses = 0\n nextUses = 0\n previousUses = 0\n f = open(outputCsvFile, 'w')\n f.write('fileName,calOffset,calSlope,calTemp,meanTemp\\n')\n for ix, row in badCal.iterrows():\n # first get current 'bad' file\n participant, device, startTime = row[['file-name', 'file-deviceID', 'file-startTime']]\n device = int(device)\n # get calibration values from most recent previous use of this device\n # (when it had a 'good' calibration)\n prevUse = goodCal[calCols][(goodCal['file-deviceID'] == device) &\n (goodCal['file-startTime'] < startTime)].tail(1)\n try:\n ofX, ofY, ofZ, slpX, slpY, slpZ, tmpX, tmpY, tmpZ, calTempAvg = prevUse.iloc[0]\n previousUses += 1\n except Exception:\n nextUse = goodCal[calCols][(goodCal['file-deviceID'] == device) &\n (goodCal['file-startTime'] > startTime)].head(1)\n if len(nextUse) < 1:\n print('no other uses for this device at all: ', str(device),\n str(participant))\n noOtherUses += 1\n continue\n nextUses += 1\n ofX, ofY, ofZ, slpX, slpY, slpZ, tmpX, tmpY, tmpZ, calTempAvg = nextUse.iloc[0]\n\n # now construct output\n out = participant + ','\n out += str(ofX) + ' ' + str(ofY) + ' ' + str(ofZ) + ','\n out += str(slpX) + ' ' + str(slpY) + ' ' + str(slpZ) + ','\n out += str(tmpX) + ' ' + str(tmpY) + ' ' + str(tmpZ) + ','\n out += str(calTempAvg)\n f.write(out + '\\n')\n f.close()\n print('previousUses', previousUses)\n print('nextUses', nextUses)\n print('noOtherUses', noOtherUses)\n\n print('Reprocessing for ', str(previousUses + nextUses),\n 'participants written to:', outputCsvFile)", "def process_data():\n\t# 1. read in all csv files in the path\n\tcsv_loader = csv_data_loader(file_path=file_path)\n\ttrans_data = csv_loader.load_data()\n\n\t# 2. filter data\n\tfilter_data = trans_data[(trans_data['main use']==\"住家用\") & (trans_data['building state']==\"住宅大樓(11層含以上有電梯)\") \\\n\t& (trans_data['total floor number']>=13)]\n\n\t# 3. save filter result to a csv file\n\tfilter_data.to_csv(os.path.join(file_path, \"result.csv\"), encoding=\"utf-8-sig\")", "def raw2processed(self):\n # start logger\n logger = logging.getLogger(__name__)\n logger.info('Splitting raw data into time series and ancillary part.')\n\n file_dir = os.path.join(self.raw_dir_csse, \"US\")\n # process\n for file in os.listdir(file_dir):\n # read csv\n file_path = os.path.join(file_dir, file)\n ts_raw = pd.read_csv(file_path, infer_datetime_format=True)\n ts_raw = ts_raw.convert_dtypes()\n\n # drop all cols apart from Province_States and the time series data\n ancillary_cols = ['Unnamed: 0', 'UID', 'iso2', 'iso3', 'code3',\n 'Admin2', 'Country_Region', 'Lat',\n 'Long_', 'Province_State', 'Combined_Key']\n if 'Population' in ts_raw.columns:\n ancillary_cols.append('Population')\n\n # split into time series and ancillary data per state\n ts_clean = (ts_raw.drop(columns=ancillary_cols)\n .set_index('FIPS')\n .transpose())\n # to datetime index\n ts_clean.index = pd.to_datetime(ts_clean.index, format='%m/%d/%y')\n\n # ancillary data\n ancillary_cols.append('FIPS')\n ancillary_clean = (ts_raw[ancillary_cols]\n .drop(columns=['Unnamed: 0']))\n\n # save to csv\n ts_clean.to_csv(\n os.path.join(self.project_dir, self.processed_dir_csse, \"US\",\n file.split('.')[0] + '_timeseries.csv'))\n ancillary_clean.to_csv(\n os.path.join(self.project_dir, self.processed_dir_csse, \"US\",\n file.split('.')[0] + '_ancillary.csv'))\n return None", "def driver(self):\n counter = 0\n with open('../input/Border_Crossing_Entry_Data.csv', mode='r') as entry_data:\n for line in entry_data:\n if counter == 0:\n counter += 1\n continue\n port_name, state, port_code, border, date, measure, value, location = line.split(',')\n timestamp = datetime.strptime(date, \"%d/%m/%Y %I:%M:%S %p\")\n border_measure = (border, measure)\n if timestamp not in self.report_dict:\n self.report_dict[timestamp] = dict()\n if border_measure not in self.report_dict[timestamp]:\n self.report_dict[timestamp][border_measure] = dict()\n self.report_dict[timestamp][border_measure]['val_list'] = []\n self.report_dict[timestamp][border_measure]['val_list'].append(value)\n counter += 1\n if counter % 100000 == 0:\n print(counter)\n self.sum_items()\n self.compute_average()\n self.sort_items()\n self.write_to_file()", "def preprocess(data_dir:str):\n train_identity = pd.read_csv(data_dir + '/train_identity.csv')\n train_transaction = pd.read_csv(data_dir + '/train_transaction.csv')\n test_identity = pd.read_csv(data_dir + '/test_identity.csv')\n test_transaction = pd.read_csv(data_dir + '/test_transaction.csv')\n\n df_train = pd.merge(train_transaction, train_identity, on='TransactionID', how='left')\n df_test = pd.merge(test_transaction, test_identity, on='TransactionID', how='left')\n\n engineer_features(df_train)\n engineer_features(df_test)\n\n # Some fixes to remove NaNs\n df_train = df_train.replace(np.nan, '', regex=True)\n df_test = df_test.replace(np.nan, '', regex=True)\n\n # Target encode some of the categorical\n cols_to_target_encode = ['P_emaildomain_bin', 'card1', 'card2', 'card3', 'card4', 'addr1', 'addr2']\n encoder = KFoldTargetEncoderTrain(cols_to_target_encode, 'isFraud', n_fold=5)\n df_train_enc = encoder.fit_transform(df_train)\n\n encoder_test = KFoldTargetEncoderTest(df_train_enc, cols_to_target_encode)\n df_test_enc = encoder_test.fit_transform(df_test)\n return df_train_enc, df_test_enc", "def get_prepared_data_set():\n df = pd.read_csv('FIFA2019.csv')\n dont_need = [\"Photo\", \"Flag\", \"ID\", \"Club Logo\",\n \"Special\", \"International Reputation\",\n \"Preferred Foot\", \"Body Type\",\n \"Real Face\", \"Jersey Number\",\n \"Joined\", \"Loaned From\",\n \"Contract Valid Until\", \"Release Clause\",\n \"Weak Foot\"]\n do_need = df.drop(columns=dont_need)\n do_need = do_need.dropna()\n num_list = list()\n for val in do_need[\"Value\"]:\n num_list.append(_convert_to_numeric(str(val)))\n do_need[\"Numerical Value\"] = num_list\n\n weight_list = list()\n for weight in do_need[\"Weight\"]:\n weight_list.append(_convert_weight(str(weight)))\n do_need[\"Numerical Weight\"] = weight_list\n height_list = list()\n for height in do_need[\"Height\"]:\n height_list.append(_convert_height(str(height)))\n do_need[\"Numerical Height\"] = height_list\n # For dribblers and dribbling\n dribble_list = [\"Dribbling\", \"BallControl\", \"Acceleration\", \"Agility\",\n \"Reactions\", \"Balance\", \"Positioning\", \"FKAccuracy\",\n \"Vision\"]\n do_need[\"Overall Skill\"] = do_need.loc[:, dribble_list].sum(axis=1) /\\\n len(dribble_list)\n\n # For shooters\n shooting_list = [\"Finishing\", \"Volleys\", \"Curve\", \"ShotPower\",\n \"LongShots\", \"Composure\", \"Penalties\"]\n do_need[\"Shooting Overall\"] = do_need.loc[:, shooting_list].sum(axis=1) /\\\n len(shooting_list)\n\n # For passing\n passing_list = [\"Crossing\", \"ShortPassing\", \"Curve\", \"LongPassing\",\n \"Vision\", \"FKAccuracy\"]\n do_need[\"Passing Overall\"] = do_need.loc[:, passing_list].sum(axis=1) /\\\n len(passing_list)\n\n # For defending\n defending_list = [\"HeadingAccuracy\", \"Jumping\", \"Strength\",\n \"Aggression\", \"Interceptions\", \"Marking\",\n \"StandingTackle\", \"SlidingTackle\"]\n do_need[\"Defending Overall\"] = do_need.loc[:, defending_list].sum(axis=1)\\\n / len(defending_list)\n\n return do_need", "def process_origin_data(config):\n data_dir, intermediate_path = config.origin_data_path, config.intermediate_path\n origin_data_time = os.path.getmtime(os.path.join(data_dir, \"factor_data.dat\"))\n clean_data_path = os.path.join(intermediate_path, \"factor_data.dat\")\n\n if os.path.exists(clean_data_path):\n if origin_data_time > os.path.getmtime(clean_data_path):\n print('Processed data are obsolete, deleting them')\n del_list = os.listdir(intermediate_path)\n for f in del_list:\n file_path = os.path.join(intermediate_path, f)\n os.remove(file_path)\n if not os.path.exists(os.path.join(config.intermediate_path, 'datetime_ref.csv')):\n print('Processed data not existed, processing origin data')\n drop_label_names = ['ret_origin_window_10', 'ret_alpha_window_10', 'ret_standard_window_10']\n drop_label_names.extend(['ret_origin_window_15', 'ret_alpha_window_15', 'ret_standard_window_15'])\n drop_label_names.extend(['ret_origin_window_20', 'ret_alpha_window_20', 'ret_standard_window_20'])\n drop_label_names.append('universe')\n label_name = 'ret_alpha_window_10'\n drop_label_names.remove(label_name)\n\n columns = pd.read_csv(os.path.join(data_dir, \"factor_name_all.csv\"))\n columns_all = columns[\"factor_name\"].values.reshape([-1, ])\n indices = pd.read_csv(os.path.join(data_dir, \"datetime.csv\"))\n indices = pd.to_datetime(indices[\"datetime\"])\n date_time_all = indices.values.reshape([-1, ])\n\n num_factor = len(columns_all) # 1274 include universe\n num_sample = len(date_time_all) # 12995140\n\n num_chunk = 3\n chunk_load = num_sample // num_chunk\n\n data = np.fromfile(os.path.join(data_dir, \"factor_data.dat\"))\n data = data.reshape(num_factor, num_sample).T\n\n for i in range(num_chunk):\n if i == num_chunk - 1: # the last chunk might be larger\n arr = data[i * chunk_load:]\n else:\n arr = data[i * chunk_load: (i + 1) * chunk_load]\n file_path = gen_path(intermediate_path, filename=str(i).join(['samples', '.npy']))\n np.save(file_path, arr)\n del arr, data\n\n valid_rows = np.zeros(num_sample, dtype=np.bool)\n uni_col = np.where(columns_all == \"universe\")[0][0]\n npy_file_list = sorted(os.listdir(intermediate_path))\n with open(os.path.join(intermediate_path, 'factor_data.dat'), 'wb') as _file:\n for i, npy_file in enumerate(npy_file_list):\n data_np = np.load(gen_path(intermediate_path, filename=npy_file))\n data_np_uni = data_np[:, uni_col]\n na_cond_col = (np.isnan(data_np)).sum(axis=0) < data_np.shape[0]\n nan_factors = np.where(na_cond_col == False)[0]\n assert len(nan_factors) == 0, 'Factor {} all nan'.format(columns_all[nan_factors])\n na_cond_col = np.logical_and(na_cond_col, [each not in drop_label_names for each in columns_all])\n choose_cols = np.where(na_cond_col)[0]\n data_np = data_np[:, choose_cols]\n choose_rows = np.where(((np.isnan(data_np)).sum(axis=1) == 0) & (data_np_uni != 0.))[0]\n data_np = data_np[choose_rows, :]\n choose_rows += i * chunk_load\n valid_rows[choose_rows] = True\n data_np[:, -1] = np.clip(data_np[:, -1], -0.3, 0.3)\n _file.write(data_np.reshape(-1, ).astype(np.float32))\n os.remove(gen_path(intermediate_path, filename=npy_file))\n del data_np\n\n factor_name = pd.DataFrame({'factor_name': columns_all[choose_cols]})\n datetime_index = pd.DataFrame({'datetime': date_time_all[valid_rows]})\n factor_name.to_csv(os.path.join(intermediate_path, 'factor_name_list.csv'), index=False)\n datetime_index.to_csv(os.path.join(intermediate_path, 'datetime_index.csv'), index=False)\n all_datetime = pd.read_csv(os.path.join(data_dir, 'datetime.csv'))\n all_symbol = pd.read_csv(os.path.join(data_dir, 'symbol.csv'), dtype={'symbol': str})\n all_date = pd.read_csv(os.path.join(data_dir, 'date.csv'))\n datetime_ref = pd.concat([all_datetime, all_symbol, all_date], axis=1, sort=False)\n datetime_ref.to_csv(os.path.join(intermediate_path, 'datetime_ref.csv'), index=False)", "def _data_preprocessing(self, tmp_dir, outlier_dir):\r\n if not os.path.exists(tmp_dir):\r\n os.makedirs(tmp_dir)\r\n if not os.path.exists(outlier_dir):\r\n os.makedirs(outlier_dir)\r\n for src_file in os.listdir(self._traces_dir):\r\n src_path = os.path.join(self._traces_dir, src_file)\r\n shutil.copy(src_path, tmp_dir)\r\n self._handle_outlier(tmp_dir, outlier_dir)", "def process_csv_files( set_up_env, \\\n log_outcomes, \\\n write_info, \\\n skip_rows_no = 0, \\\n stop_row_no = 120, \\\n result_type = 'rates', \\\n logging_dir = 'logging_rates', \\\n absdist_tuple = None, \\\n test_run = True ):\n HEADERS_CSV = [ 'page_no', 'obj_no', 'x0', 'y0', 'x1', 'y1', 'text' ]\n for csv_filename, issuer, extract_data in set_up_env:\n kwargs = dict( filename = csv_filename, headers = HEADERS_CSV, skip_rows_no = skip_rows_no, stop_row_no = stop_row_no )\n with handle_newline_error( ):\n rows_list = get_csvrows( **kwargs )\n with log_outcomes( dir_to_log = issuer, content = csv_filename, test_run = test_run ):\n if absdist_tuple is None:\n pl_info = extract_data( rows_list, csv_filename )\n else:\n pl_info = extract_data( rows_list, csv_filename, absdist_tuple = absdist_tuple )\n write_info( dir_to_log = issuer, content = pl_info )", "def benchmark(self, data: pd.DataFrame):\n\n new_ests = []\n new_lo = []\n new_hi = []\n observed_covariate_e_values = []\n backdoor_vars = self.estimand.get_backdoor_variables()\n for drop_var in backdoor_vars:\n\n # new estimator\n new_backdoor_vars = [var for var in backdoor_vars if var != drop_var]\n new_estimand = copy.deepcopy(self.estimand)\n new_estimand.set_backdoor_variables(new_backdoor_vars)\n new_estimator = self.estimate.estimator.get_new_estimator_object(new_estimand)\n new_estimator.fit(\n self.data,\n self.estimate.estimator._effect_modifier_names,\n **new_estimator._econml_fit_params if isinstance(new_estimator, Econml) else {},\n )\n\n # new effect estimate\n new_effect = new_estimator.estimate_effect(\n self.data,\n control_value=self.estimate.control_value,\n treatment_value=self.estimate.treatment_value,\n target_units=self.estimate.estimator._target_units,\n )\n if isinstance(self.estimate.estimator, LinearRegressionEstimator):\n coef_est = new_effect.value\n coef_se = new_effect.get_standard_error()[0]\n elif isinstance(self.estimate.estimator, GeneralizedLinearModelEstimator):\n coef_est = new_effect.estimator.model.params[1:2].to_numpy()[0]\n coef_se = new_effect.estimator.model.bse[1:2].to_numpy()[0]\n new_stats = self.get_evalue(coef_est, coef_se)\n\n # observed covariate E-value\n if self.stats[\"evalue_lower_ci\"] is None:\n ci = self.stats[\"converted_upper_ci\"]\n new_ci = new_stats[\"converted_upper_ci\"]\n else:\n ci = self.stats[\"converted_lower_ci\"]\n new_ci = new_stats[\"converted_lower_ci\"]\n covariate_e_value = self._observed_covariate_e_value(ci, new_ci)\n\n new_ests.append(new_stats[\"converted_estimate\"])\n new_lo.append(new_stats[\"converted_lower_ci\"])\n new_hi.append(new_stats[\"converted_upper_ci\"])\n observed_covariate_e_values.append(covariate_e_value)\n\n self.benchmarking_results = pd.DataFrame(\n {\n \"dropped_covariate\": backdoor_vars,\n \"converted_est\": new_ests,\n \"converted_lower_ci\": new_lo,\n \"converted_upper_ci\": new_hi,\n \"observed_covariate_e_value\": observed_covariate_e_values,\n }\n ).sort_values(by=\"observed_covariate_e_value\", ascending=False)\n self.benchmarking_results = self.benchmarking_results.set_index(\"dropped_covariate\")" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Running trade simulation on the given time series based on residual zscore. Simulation takes long and short positions. One position at a time.
def run_residual_trade_simulation(trade_simul_data, zscore_buy_long=-1.5, zscore_cover_long=-0.5, zscore_sell_short=1.5, zscore_cover_short=0.5): data = trade_simul_data[[DATE_COL_NAME, PRICE_COL_NAME, RESIDUAL_ZSCORE_COL_NAME]] trades = pd.DataFrame( columns=[DATE_COL_NAME, PRICE_COL_NAME, RESIDUAL_ZSCORE_COL_NAME, ACTION_COL_NAME, HOLDING_PERIOD_COL_NAME, PROFIT_DELTA_COL_NAME, CUMULATIVE_PROFIT_COL_NAME]) dates = trade_simul_data[DATE_COL_NAME] continuos_profits = pd.DataFrame( columns=[DATE_COL_NAME, PRICE_COL_NAME, PROFIT_DELTA_COL_NAME, CUMULATIVE_PROFIT_COL_NAME]) continuos_profits[DATE_COL_NAME] = dates continuos_profits[PRICE_COL_NAME] = trade_simul_data[PRICE_COL_NAME] trade_position = TradePosition.NO_POSITION cum_realized_profit = 0 cum_continous_profit = 0 for i in data.index.values: row = data.iloc[i] curr_date = row[DATE_COL_NAME] curr_price = row[PRICE_COL_NAME] residual_zscore = row[RESIDUAL_ZSCORE_COL_NAME] daily_profit_delta = 0 if trade_position == TradePosition.NO_POSITION: holding_period = 0 realized_profit_delta = 0 if residual_zscore <= zscore_buy_long: action = TradeAction.BUY_LONG trade_row = list( np.concatenate([row.values, [action, holding_period, realized_profit_delta, cum_realized_profit]])) trades = append_row(trades, trade_row) trade_position = TradePosition.LONG elif residual_zscore >= zscore_sell_short: action = TradeAction.SELL_SHORT trade_row = list( np.concatenate([row.values, [action, holding_period, realized_profit_delta, cum_realized_profit]])) trades = append_row(trades, trade_row) trade_position = TradePosition.SHORT else: previous_day_price = data.iloc[i - 1, 1] entry_date = trades.iloc[-1, 0] holding_period = (curr_date - entry_date).days entry_price = trades.iloc[-1, 1] if trade_position == TradePosition.LONG: daily_profit_delta = curr_price - previous_day_price if residual_zscore >= zscore_cover_long: action = TradeAction.COVER_LONG realized_profit_delta = curr_price - entry_price cum_realized_profit += realized_profit_delta trade_row = list( np.concatenate([row.values, [action, holding_period, realized_profit_delta, cum_realized_profit]])) trades = append_row(trades, trade_row) trade_position = TradePosition.NO_POSITION elif trade_position == TradePosition.SHORT: daily_profit_delta = previous_day_price - curr_price if residual_zscore <= zscore_cover_short: action = TradeAction.COVER_SHORT realized_profit_delta = entry_price - curr_price cum_realized_profit += realized_profit_delta trade_row = list( np.concatenate([row.values, [action, holding_period, realized_profit_delta, cum_realized_profit]])) trades = append_row(trades, trade_row) trade_position = TradePosition.NO_POSITION cum_continous_profit += daily_profit_delta continuos_profits.iloc[i, 2] = daily_profit_delta continuos_profits.iloc[i, 3] = cum_continous_profit return trades, continuos_profits
[ "def _run(prices, options, verbose=True, get_invested_value=None):\n # For each stock, calculate the running yearly volatility:\n sigmas = Simulation._calculate_sigmas_wrapper(prices)\n\n if verbose:\n print(\"Finished calculating the yearly sigmas.\")\n\n # Then extract the values and call the ROI-calculation for investing one given day:\n payouts = np.empty_like(prices.values)\n payouts[:] = np.nan\n\n for stock_idx, stock in tqdm(enumerate(prices.columns), total=len(prices.columns)):\n # We do not want to start trading right away, when a stock becomes available. So we need to find out\n # the \"date of birth\" for a stock (which is the minimum index where an isna-comparison changes from\n # True to False) and then add our minimum maturity.\n # Alternative for date_of_stock_trading_start: np.argmin(prices[stock].isna().values), which is a bit less\n # readable.\n #date_of_stock_trading_start = prices[stock].isna().idxmin()\n date_of_stock_trading_start = np.argmin(prices[stock].isna().values)\n #trading_start_idx = prices.index.get_loc(date_of_stock_trading_start) + options.minimum_maturity\n trading_start_idx = date_of_stock_trading_start + options.minimum_maturity\n\n for k in range(trading_start_idx, len(sigmas)):\n try:\n payouts[k, stock_idx] = get_invested_value(\n prices=prices[stock].values.squeeze(),\n sigmas=sigmas[stock].values.squeeze(),\n index=k,\n horizon=options.horizon,\n out_of_money_factor=options.out_of_money_factor,\n r=options.r,\n bet_long=options.bet_long,\n )\n except AssertionError as a:\n # Raise and enhanced assertion error with info that was not available within the\n # get_invested_value-function:\n s = f'Encountered AssertionError for improper shape of vectors ' \\\n f'prices/sigmas for {stock} (idx: {stock_idx}) in step {k}: {a}\\n'\n s += f'Shapes passed were: {prices[stock].values.squeeze().shape} for prices ' \\\n f'and {sigmas[stock].values.squeeze().shape} for sigmas.\\n'\n raise AssertionError(s)\n except ValueError as v:\n # Raise an enhanced value error with info that was not available within the get_invested_value-function:\n s = f'Encountered ValueError \"{v}\" for {stock} (idx: {stock_idx}) in step {k}.\\n'\n s += f'Stock price at index {k} was {prices[stock].values.squeeze()[k]}.\\n'\n s += f'Sigma at index {k} was {sigmas[stock].values.squeeze()[k]}.\\n'\n s += f'Passed parameters were:\\n{options}\\n'\n raise ValueError(s)\n except Exception as e:\n raise Exception(\"Unknown exception raised.\")\n\n pay_outs = pd.DataFrame(payouts, index=sigmas.index, columns=sigmas.columns)\n\n # Store the results in a separate dataframe, where entries are nan where we could not calculate the ROI.\n return pay_outs, sigmas", "def run_simple_backtest(symbol, rule_variant=['EWMAC', '2,8'], start_date=dt.date(2017, 1, 1), end_year=dt.date.today().year,\r\n starting_capital=1000000.0, volatility_target=0.25):\r\n auth_token = 'g1CWzGxxg2WxNVbV5n9y'\r\n\r\n # set scalar variables\r\n start_year = start_date.year\r\n instrument_weight = 1.0\r\n instrument_diversifier_multiplier = 1.0\r\n position_inertia = 0.1\r\n\r\n # determine which rule for which to run forecast\r\n forecast_inputs = get_forecast_inputs(symbol, start_year, end_year)\r\n if rule_variant[0] == 'CARRY':\r\n df = calc_carry_forecasts(forecast_inputs)\r\n elif rule_variant[0] == 'EWMAC':\r\n fast = int(rule_variant[1].split(',')[0])\r\n slow = int(rule_variant[1].split(',')[1])\r\n df = calc_ewmac_forecasts(forecast_inputs, fast, slow)\r\n elif rule_variant[0] == 'RSI':\r\n span = int(rule_variant[1])\r\n df = calc_rsi_forecasts(forecast_inputs, span)\r\n df['InstrumentForecast'] = df['ForecastCapped']\r\n\r\n # calculate instrument value vol\r\n futures_info = get_futures_info()\r\n df['BlockSize'] = futures_info.loc[futures_info['Symbol'] == symbol, 'BlockSize'].values[0]\r\n df['BlockValue'] = df['SettleRaw'] * df['BlockSize'] * 0.01\r\n df['InstrumentCurVol'] = df['BlockValue'] * df['PriceVolatilityPct'] * 100\r\n # incorporate historical fx rates\r\n fx_symbol = futures_info.loc[futures_info['Symbol'] == symbol, 'FX'].values[0]\r\n if fx_symbol != 'USD':\r\n fx_symbol = 'CURRFX/' + futures_info.loc[futures_info['Symbol'] == symbol, 'FX'].values[0]\r\n fx_rates = quandl.get(fx_symbol, authtoken=auth_token)\r\n # fx_rates.columns = ['Rate']\r\n df = df.merge(fx_rates, how='left', left_index=True, right_index=True)\r\n df = df.fillna(method='ffill') # fill in missing FX rates\r\n else:\r\n df['Rate'] = 1.0\r\n df['InstrumentValueVol'] = df['InstrumentCurVol'] / df['Rate']\r\n\r\n # begin backtest\r\n # cutoff first 90 trading days of data\r\n df = df.iloc[90:]\r\n # placeholders below\r\n df['PortfolioValue'] = starting_capital\r\n df['DailyCashTargetVol'] = starting_capital * volatility_target / (256 ** 0.5)\r\n df['VolatilityScalar'] = 0.0\r\n df['SubsystemPosition'] = 0.0\r\n df['SystemPosition'] = 0.0\r\n df['StartingPosition'] = 0.0\r\n df['EndingPosition'] = 0.0\r\n df['PositionChange'] = 0.0\r\n df['PositionCost'] = 0.0\r\n df['PositionValue'] = 0.0\r\n df['GainLossCum'] = 0.0\r\n\r\n # iterate through each date in df to retrieve ForecastCapped and InstrumentValueVol\r\n for i in list(range(0, len(df))):\r\n active_date = df.index[i]\r\n\r\n # update capital balance and volatility targets based on gain loss in backtest_df\r\n if i != 0: # skip first day\r\n df.loc[active_date, 'PositionCost'] += df['PositionCost'][prev_date]\r\n df.loc[active_date, 'PositionValue'] += df['PositionValue'][prev_date]\r\n df.loc[active_date, 'GainLossCum'] += df['GainLossCum'][prev_date]\r\n df.loc[active_date, 'PortfolioValue'] = starting_capital + df['GainLossCum'][active_date]\r\n df.loc[active_date, 'DailyCashTargetVol'] = df['PortfolioValue'][active_date] * \\\r\n volatility_target / (256 ** 0.5)\r\n df.loc[active_date, 'VolatilityScalar'] = df['DailyCashTargetVol'][active_date] / df['InstrumentValueVol'][active_date]\r\n df.loc[active_date, 'SubsystemPosition'] = df['InstrumentForecast'][active_date] / 10.0 * df['VolatilityScalar'][active_date]\r\n df.loc[active_date, 'SystemPosition'] = df['SubsystemPosition'][active_date] * instrument_weight * \\\r\n instrument_diversifier_multiplier\r\n if i != 0: # skip first day\r\n df.loc[active_date, 'StartingPosition'] = df['EndingPosition'].loc[prev_date]\r\n\r\n # determine trade based on starting_position, ending_position and system_position\r\n # define variable to minimize space\r\n starting_position = df['StartingPosition'][active_date]\r\n ending_position = starting_position\r\n system_position = df['SystemPosition'][active_date]\r\n block_size = df['BlockSize'][active_date]\r\n block_price = df['SettleRaw'][active_date]\r\n fx_rate = df['Rate'][active_date]\r\n\r\n if starting_position == 0 or (np.abs((system_position - starting_position) / starting_position) >\r\n position_inertia):\r\n ending_position = np.round(system_position, 0)\r\n df.loc[active_date, 'EndingPosition'] = ending_position\r\n df.loc[active_date, 'PositionChange'] = ending_position - starting_position\r\n if i != 0: # skip first day; else set PositionCost equal to previous value\r\n df.loc[active_date, 'PositionCost'] = df['PositionCost'].loc[prev_date]\r\n df.loc[active_date, 'PositionCost'] += (ending_position - starting_position) * block_size * block_price\r\n # reset PositionCost when contracts roll\r\n if i != 0 and df.loc[active_date, 'Contract'] != df['Contract'][prev_date]:\r\n df.loc[active_date, 'PositionCost'] = ending_position * block_price * block_size - \\\r\n (df['GainLossCum'][prev_date] * fx_rate)\r\n df.loc[active_date, 'PositionValue'] = ending_position * block_size * block_price\r\n df.loc[active_date, 'GainLossCum'] = (df['PositionValue'][active_date] - df['PositionCost'][active_date]) / fx_rate\r\n prev_date = active_date\r\n\r\n # calculate backtest summary statistics\r\n df['PortfolioReturnDayPct'] = df['PortfolioValue'] / df['PortfolioValue'].shift(1) - 1.0\r\n rule = rule_variant[0]\r\n variant = rule_variant[1] if rule == 'EWMAC' else ''\r\n trading_days = df.shape[0]\r\n annualized_return = np.exp(np.nansum(np.log(1 + df['PortfolioReturnDayPct']))) ** (256.0 / trading_days) - 1.0\r\n annualized_volatility = np.std(df['PortfolioReturnDayPct']) * np.sqrt(256.0)\r\n sharpe_ratio = annualized_return / annualized_volatility\r\n blocks_traded = np.sum(np.abs(df['PositionChange']))\r\n avg_position = np.average(np.abs(df['EndingPosition']))\r\n annualized_turnover = blocks_traded / (2 * avg_position) * 256.0 / trading_days\r\n results_df = pd.DataFrame({'Symbol': symbol, 'Rule': rule, 'Variant': variant, 'AnnReturn': annualized_return,\r\n 'AnnVol': annualized_volatility, 'Sharpe': sharpe_ratio, 'Trades': blocks_traded,\r\n 'AvgPosition': avg_position, 'AnnTurnover': annualized_turnover,\r\n 'StartingCapital': starting_capital, 'TargetVolatility': volatility_target,\r\n 'TradingDays': trading_days}, index=[0])\r\n return results_df[['Symbol', 'Rule', 'Variant', 'AnnReturn', 'AnnVol', 'Sharpe', 'Trades', 'AvgPosition',\r\n 'AnnTurnover', 'TradingDays']], df", "def backtest(self):\n # Cut off most recent history closing price since it is not complete and would effect the calculations\n #kline_array = self.client.get_historical_klines(symbol=pair, interval=Client.KLINE_INTERVAL_5MINUTE, start_str= '1' + ' month ago UTC')\n kline_array = self.client.get_historical_klines(symbol=self.pair, interval=self.asset_interval, start_str= self.time_look_back)\n self.closing_times = [dt.datetime.utcfromtimestamp(x[6]/1000) for x in kline_array][0:-1]\n self.closing_price_array = [float(x[4]) for x in kline_array][0:-1]\n self.checked_prices = []\n\n gain, loss = 0, 0\n for x in range(0, len(self.closing_price_array)-1):\n change = self.closing_price_array[x+1] - self.closing_price_array[x]\n self.checked_prices.append(self.closing_price_array[x+1])\n self.checked_times.append(self.closing_times[x+1])\n if change > 0:\n gain += change\n elif change < 0:\n loss += abs(change)\n\n #Get first rsi simple moving average\n if x == self.rsi_period:\n self.avg_gain = self.simple_moving_average(gain, self.rsi_period)\n self.avg_loss = self.simple_moving_average(loss, self.rsi_period)\n self.rsi = self.rsi_calc(self.avg_gain, self.avg_loss)\n self.rsi_array.append(self.rsi)\n gain, loss = 0, 0\n\n #Use wilders moving average to continue calculating rsi values\n elif x > self.rsi_period:\n self.avg_gain = self.wilders_moving_average(self.rsi_period, gain, self.avg_gain)\n self.avg_loss = self.wilders_moving_average(self.rsi_period, loss, self.avg_loss)\n self.rsi = self.rsi_calc(self.avg_gain, self.avg_loss)\n self.rsi_array.append(self.rsi)\n gain, loss = 0, 0\n\n # When there are enough rsi values begin to calculate stoch_rsi\n if len(self.rsi_array) >= self.stoch_period:\n k_fast = self.k_fast_stoch(self.rsi_array[len(self.rsi_array) - self.stoch_period:])\n self.k_fast_array['k_fast'].append(k_fast)\n self.k_fast_array['time'].append(self.closing_times[x])\n\n # When there are enough %K_FAST values begin to calculate %K_SLOW values = sma of n %K_FAST values\n if len(self.k_fast_array['k_fast']) >= self.k_slow_period:\n k_slow = self.simple_moving_average(self.k_fast_array['k_fast'][-1*self.k_slow_period:], self.k_slow_period)\n self.k_slow_array['k_slow'].append(k_slow)\n self.k_slow_array['time'].append(self.closing_times[x])\n\n # When there are enough %K_SLOW values begin to calculate %D_SLOW values = sma of n %K_SLOW values\n if len(self.k_slow_array['k_slow']) >= self.d_slow_period:\n d_slow = self.simple_moving_average(self.k_slow_array['k_slow'][-1*self.d_slow_period:], self.d_slow_period)\n self.d_slow_array['d_slow'].append(d_slow)\n self.d_slow_array['time'].append(self.closing_times[x])\n\n self.bollinger_bands(self.checked_prices, self.sma_period, self.deviation, self.checked_times[x])\n\n #Once all values start to be calculated we can determine whether to buy or sell until we hit the last\n self.buy_sell(current_time = self.checked_times[x])\n\n self.plot_orders() #Plot orders on graph", "def run_and_evaluate_algorithm(**kwargs):\n name = kwargs['name']\n strategy = kwargs['strategy']\n strategy_parameters = kwargs['strategy_parameters']\n num_shares = kwargs['num_shares']\n max_num_orders = kwargs['max_num_orders']\n symbol = kwargs['symbol']\n trader = kwargs['trader'] # reference to the 1 trader instance connnected to cloudX\n\n # create the AlgorithmicTrader Object\n algo = strategy(trader, [symbol], bin_interval_ms=GLOBALS['BIN_INTERVAL_MS'])\n\n # get and set id for this trader (for logging purposes)\n trader_id = name + \"_\" + str(time.time()).split(\".\")[0]\n\n # Calculate portfolio state pre-trading\n pass\n\n # start and finish trading\n order_ids = algo.trade(symbol, num_shares, max_num_orders, GLOBALS['WAIT_INTERVAL_SECONDS'], trader_id=trader_id,\n **strategy_parameters)\n # can SIMULATE if we want\n\n # calculate portfolio state post-trading\n pass\n\n # time.sleep(10)\n # write the order ids to a log file\n print(trader_id + \"_order_ids\", json.dumps(order_ids))\n # write the ROI information a log file\n pass", "def _run_transient(self, t):\n tf = self.settings['t_final']\n dt = self.settings['t_step']\n to = self.settings['t_output']\n tol = self.settings['t_tolerance']\n t_pre = self.settings['t_precision']\n quantity = self.settings['quantity']\n s = self.settings['t_scheme']\n res_t = 1e+06 # Initialize the residual\n\n if type(to) in [float, int]:\n # Make sure 'tf' and 'to' are multiples of 'dt'\n tf = tf + (dt-(tf % dt))*((tf % dt) != 0)\n to = to + (dt-(to % dt))*((to % dt) != 0)\n self.settings['t_final'] = tf\n self.settings['t_output'] = to\n out = np.arange(t+to, tf, to)\n elif type(to) in [np.ndarray, list]:\n out = np.array(to)\n out = np.append(out, tf)\n out = np.unique(out)\n out = np.around(out, decimals=t_pre)\n\n if s == 'steady': # If solver in steady mode, do one iteration\n logger.info(' Running in steady mode')\n x_old = self[quantity]\n self._t_run_reactive(x0=x_old)\n x_new = self[quantity]\n\n else: # Do time iterations\n # Export the initial field (t=t_initial)\n t_str = self._nbr_to_str(t)\n quant_init = self[quantity]\n self[quantity + '@' + t_str] = quant_init\n for time in np.arange(t+dt, tf+dt, dt):\n if (res_t >= tol): # Check if the steady state is reached\n logger.info(' Current time step: ' + str(time) + ' s')\n x_old = self[quantity]\n self._t_run_reactive(x0=x_old)\n x_new = self[quantity]\n # Compute the residual\n res_t = np.sum(np.absolute(x_old**2 - x_new**2))\n logger.info(' Residual: ' + str(res_t))\n # Output transient solutions. Round time to ensure every\n # value in outputs is exported.\n if round(time, t_pre) in out:\n t_str = self._nbr_to_str(time)\n self[quantity + '@' + t_str] = x_new\n logger.info(' Exporting time step: '\n + str(time) + ' s')\n # Update A and b and apply BCs\n self._t_update_A()\n self._t_update_b()\n self._apply_BCs()\n self._A_t = (self._A).copy()\n self._b_t = (self._b).copy()\n\n else: # Stop time iterations if residual < t_tolerance\n # Output steady state solution\n t_str = self._nbr_to_str(time)\n self[quantity + '@' + t_str] = x_new\n logger.info(' Exporting time step: '\n + str(time) + ' s')\n break\n if (round(time, t_pre) == tf):\n logger.info(' Maximum time step reached: '\n + str(time) + ' s')\n else:\n logger.info(' Transient solver converged after: '\n + str(time) + ' s')", "def run_lorenz96_forecast(x_initial, u_initial, f, u_model, random_updater, num_steps,\n num_random, time_step=0.005, x_only=True,\n predict_residuals=False, order=2, rs=None):\n if order == 4:\n time_inc = np.array([0.5, 0.5, 1])\n else:\n time_inc = np.array([0.5, 1])\n steps = np.arange(num_steps)\n times = steps * time_step\n x_u_curr = np.zeros((3, x_initial.shape[0]))\n x_u_curr[0] = x_initial[:]\n x_u_curr[1] = u_initial[:]\n coords = {\"step\": steps, \"x_size\": np.arange(x_initial.size)}\n X_out = np.zeros((num_steps, x_initial.size))\n U_out = np.zeros((num_steps, x_initial.size))\n U_res_out = np.zeros((num_steps, x_initial.size))\n k_dXdt = np.zeros((order, x_initial.shape[0]))\n X_out[0] = x_initial[:]\n U_out[0] = u_initial[:]\n if not predict_residuals:\n if rs is None:\n random_values = np.random.normal(size=(x_initial.size, num_random))\n else:\n random_values = rs.normal(size=(x_initial.size, num_random))\n U_res_out[0] = random_values[:, 0]\n else:\n random_values = np.random.normal(size=(x_initial.size, num_random))\n for n in range(1, num_steps):\n if n % 400 == 0:\n print(n, x_u_curr[0], x_u_curr[1], x_u_curr[2])\n\n for o in range(order):\n if predict_residuals:\n if x_only:\n x_u_curr[1] = u_model.predict_mean(x_u_curr[0:1].T)\n else:\n x_u_curr[1] = u_model.predict_mean(x_u_curr.T, x_u_curr[2:3].T)\n else:\n if x_only:\n x_u_curr[1] = u_model.predict(x_u_curr[0:1].T, random_values)\n else:\n x_u_curr[1] = u_model.predict(x_u_curr[0:2].T, random_values)\n U_out[n] = x_u_curr[1]\n U_res_out[n] = random_values[:, 0]\n k_dXdt[o] = l96_forecast_step(x_u_curr[0], f) - x_u_curr[1] + x_u_curr[2]\n if o < order - 1:\n x_u_curr[0] = X_out[n - 1] + k_dXdt[o] * time_inc[o] * time_step\n if order == 4:\n x_u_curr[0] = X_out[n - 1] + (k_dXdt[0] + 2 * k_dXdt[1] + 2 * k_dXdt[2] + k_dXdt[3]) / 6 * time_step\n else:\n x_u_curr[0] = X_out[n - 1] + k_dXdt[1] * time_step\n X_out[n] = x_u_curr[0]\n U_out[n] = x_u_curr[1] + x_u_curr[2]\n if predict_residuals:\n U_res_out[n] = x_u_curr[2]\n x_u_curr[2] = u_model.predict_res(x_u_curr[2])\n else:\n random_values = random_updater.update(random_values)\n output = xr.Dataset(data_vars=dict(x=xr.DataArray(X_out, coords=coords,\n dims=(\"step\", \"x_size\"), attrs={\"long_name\": \"x values\"}),\n u=xr.DataArray(U_out, coords=coords,\n dims=(\"step\", \"x_size\"), attrs={\"long_name\": \"u values\"}),\n u_res=xr.DataArray(U_res_out, coords=coords,\n dims=(\"step\", \"x_size\"), attrs={\"long_name\": \"u res values\"}),\n time=times),\n coords=coords)\n return output", "def simulate_trade(real_values, predictions, initial_capital):\n trader = Trader(initial_capital)\n for day in range(len(predictions)):\n if predictions[day] > real_values[day]:\n trader.buy_or_hold_order(real_values[day])\n else:\n trader.sell_order(real_values[day])\n\n # At the end of the dataset, a sell order is placed to convert all stocks to liquid with the price of the last\n # observation:\n trader.sell_order(real_values[len(predictions) - 1])\n return calculate_roi(trader.capital, initial_capital)", "def run_resid_backtest(closes, weights, carry, resids, resid_lookback_diff, vol_lookback, entry_threshold, pt_sl, vertbar,\r\n max_signals=1, even_weight=True, log_ret=False, vs_ma=False, rebal_freq=None, plot=True, tc_pct=0.0, \r\n roll_cost=None, cusum_pct=None, exit_pct=False, window=3.):\r\n # generate ETF synthetic series\r\n\r\n tr = ETFTrick(closes.shift(1), closes, weights, carry, rebal_freq=rebal_freq)\r\n trs, etf_inter_data = tr.get_etf_series(return_data=True)\r\n \r\n # need to reindex the residuals to days where my trs are defined (i.e. drop NaN days)\r\n resids = resids.reindex(trs.index)\r\n\r\n # rolling change zscores of the aggregated residuals\r\n # TODO: maybe we should consider change versus a moving average rather than a specific lookback?\r\n zscore_resids = lookback_zscore(resids, lookback=resid_lookback_diff, vol_lookback=vol_lookback, \r\n log_ret=log_ret, vs_ma=vs_ma)\r\n \r\n # generating over threshold .75 z-score signals for reversion\r\n signals = zscore_signal(zscore_resids, threshold=entry_threshold, signal_type='Reversion').rename('signal')\r\n\r\n # cusum reversal too\r\n if cusum_pct is not None:\r\n cusum_signals = cusum_sym_filter(resids, cusum_pct)\r\n # full signal from cusum and zscore\r\n full_signals = signals.to_frame().join(cusum_signals).fillna(0).apply(lambda x: x['signal'] if x['signal']==x['CusumFilter'] \r\n else 0, axis=1)\r\n else:\r\n full_signals = signals\r\n \r\n # generate initial events DataFrame for this reversion strategy\r\n events0, df0 = zscore_sizing(full_signals, trs, vertbar=vertbar, pt_sl=pt_sl, \r\n max_signals=max_signals, even_weight=even_weight, model_resids=zscore_resids,\r\n exit_pct=exit_pct)\r\n \r\n events = generate_pnl(events0, trs, pct_change=True)\r\n \r\n # tc cost on $1 (i.e. 1bp = 1e-4), weights_diff_delev is absolute change in weights\r\n rebal_cost_srs = -tc_pct*etf_inter_data['weights_diff_delev'].squeeze().rename('weights')\r\n \r\n if roll_cost is not None:\r\n # add tc cost on $1 rolled\r\n total_rebal_cost_srs = rebal_cost_srs.to_frame().join(roll_cost.rename('roll_cost'), how='outer').fillna(0.0)\r\n total_rebal_cost_srs['total_cost'] = total_rebal_cost_srs['weights']+total_rebal_cost_srs['roll_cost']\r\n else: \r\n total_rebal_cost_srs=rebal_cost_srs.rename('total_cost').to_frame()\r\n \r\n # update events['ret'] for tc and calculate full cost to apply to mtm_pnl\r\n events, rebal_cost_strat = _get_tc(events, tc_pct, total_rebal_cost_srs['total_cost'])\r\n \r\n mtm_pnl = generate_mtm_pnl(events, trs, log_diff=True, tc=tc_pct) # subtract tc from return on open and close, doesn't use ret\r\n rebal_cost_strat = rebal_cost_strat.reindex(mtm_pnl.index, fill_value=0.0).rename('strat')\r\n \r\n pnl_index = generate_pnl_index(mtm_pnl, rebal_cost_strat)\r\n exposures = generate_exposures(events, trs)\r\n if plot:\r\n # compute data for rolling sharpe\r\n window_m = int(window*12)\r\n rolling_pct = pnl_index.apply(np.log).diff(252*window)\r\n cagr_srs = np.power(pnl_index.pct_change(int(252*window))+1., 1/window)-1.\r\n\r\n log_m_returns = pnl_index.copy(deep=True).asfreq('BM', method='ffill').apply(np.log).diff(1).dropna()\r\n\r\n vol_m_srs = log_m_returns.rolling(window_m).std()\r\n\r\n # monthly and account for autocorr\r\n acorr_scale = log_m_returns.rolling(window_m).apply(lambda x: np.sqrt(12 + \r\n 2*sum([(12-i) * x.autocorr(lag=i) for i in range(1,12)])), \r\n raw=False).fillna(1.)\r\n mvol_srs_ann = vol_m_srs * acorr_scale\r\n sharpe_m = cagr_srs.asfreq('BM', method='ffill') / mvol_srs_ann\r\n fig, ax = plt.subplots(figsize=(6,7), nrows=3, dpi=300)\r\n exposures.plot(ax=ax[0])\r\n pnl_index.plot(ax=ax[1])\r\n sharpe_m.plot(ax=ax[2])\r\n ax[0].set_title(\"Exposure in Basket\")\r\n ax[1].set_title(r\"Daily MTM Equity Curve ({0}bp TC)\".format(np.round(tc_pct*1e4, 1)))\r\n ax[2].set_title(r\"Rolling {0}yr Sharpe {1}bp TC\".format(window, np.round(tc_pct*1e4, 1)))\r\n fig.tight_layout()\r\n plt.show()\r\n perf_summary = generate_perf_summary(events, trs, tc_pct=tc_pct, rebal_cost=rebal_cost_strat)\r\n \r\n return events, df0, pnl_index, exposures, trs, perf_summary", "def test_td_residual_smoke():\n rewards = np.array([1, 3, 2, 8])\n values = np.array([2, 3, 5, 2])\n gamma = 0.9\n last_val = -1\n ret = math.td_residual(rewards, values, gamma=gamma, last_val=last_val)\n assert ret[0] == 1 + gamma*3 - 2\n assert ret[3] == 8 + gamma*last_val - 2", "def assess_portfolio(\n sd = dt.datetime(2008,1,1), ed = dt.datetime(2009,1,1), \\\n syms = ['GOOG','AAPL','GLD','XOM'], \\\n allocs=[0.1,0.2,0.3,0.4], \\\n sv=1000000, rfr=0.0, sf=252.0, \\\n gen_plot=False):\n \n # read in adjusted closing prices for given symbols, date range\n # adding SPY to allocation for calulations and trading days\n dates = pd.date_range(sd.date(), ed.date())\n df_all = get_data(syms, dates) # automatically adds SPY\n df = df_all[syms] \n \n # get daily portfolio value \n df_nrm = df / df.ix[0,:] \n allocated = df_nrm * allocs\n position_values = allocated * sv\n port_value = position_values.sum(axis = 1)\n # daily returns (y_{t} = x_{t}/x_{t-1} - 1\n d_returns = port_value.copy() \n d_returns = (port_value/port_value.shift(1) - 1)\n d_returns = d_returns[1:]\n \n # Below are desired output values\n \n # cumulative return (final - initial) - 1\n cr = port_value[-1] / port_value[0] - 1\n # average daily return\n adr = d_returns.mean()\n # standard deviation of daily return\n sddr = d_returns.std()\n # sharpe ratio ((Mean - Risk free rate)/Std_dev)\n daily_rfr = (1.0 - rfr)**(1/252) - 1 #Should this be sampling freq instead of 252? \n sr = (d_returns - daily_rfr).mean() / sddr\n sr_annualized = sr * (sf**0.5)\n \n # compare daily portfolio value with SPY using a normalized plot\n if gen_plot:\n df_nrm_SPY = df_all['SPY'] / df_all['SPY'].ix[0,:]\n \n port_value_norm = port_value / port_value.ix[0,:]\n port_vs_SPY = df_nrm_SPY.copy()\n port_vs_SPY = port_vs_SPY.to_frame().join(port_value_norm.to_frame('Portfolio'))\n \n ax_portfolio = port_vs_SPY.plot(title = 'Daily Returns against SPY', grid = True, legend = 'reverse')\n ax_portfolio.set_xlabel('Date')\n ax_portfolio.set_ylabel('Normalized Price')\n plt.show()\n \n # end value\n ev = port_value[-1]\n \n return cr, adr, sddr, sr_annualized, ev", "def esm_arima(ts):\n\n test_n = 60\n ses = []\n trend = []\n dtrend = []\n arima = []\n j=0\n \n for i in range(test_n,0,-1): #(60,59,58...3,2,1)\n # moving window, walk foward 1 step \n train = np.asarray(ts[j:len(ts)-i])\n j= j+1\n \n # 3 different types of ESM models. Each 1 makes 1 step ahead predictions\n ses.append(SimpleExpSmoothing(train).fit(optimized = True).\\\n forecast(1)[0])\n \n trend.append(ExponentialSmoothing(train, \n trend='add',\n damped=False,\n seasonal='None').fit(optimized = True).\\\n forecast(1)[0])\n \n dtrend.append(ExponentialSmoothing(train, \n trend='add',\n damped=True,\n seasonal='None').fit(optimized = True).\\\n forecast(1)[0])\n \n # Auto arima model makes 1 step ahead prediction.\n model = auto_arima(train, trace=False, error_action='ignore', \n suppress_warnings=True, max_p=15, max_q=15,\n d=0, D=0, max_order=20, seasonal = False)\n model.fit(train)\n forecast = model.predict(n_periods=1)\n \n arima.append(forecast)\n \n print('done with step: ', j)\n \n test = ts.tail(test_n) # test set\n \n # naive forecast predicts no change in price aka return = 0\n naive_mae = mean_absolute_error([0] * test_n, test)\n \n # calculate MAE for all 4 model types\n ses_mae = mean_absolute_error(ses, test)\n trend_mae = mean_absolute_error(trend, test)\n dtrend_mae = mean_absolute_error(dtrend, test)\n arima_mae = mean_absolute_error(arima, test)\n \n # calculate MASE for all 4 model types\n ses_mase = ses_mae / naive_mae\n trend_mase = trend_mae / naive_mae\n dtrend_mase = dtrend_mae / naive_mae\n arima_mase = arima_mae / naive_mae\n \n # create list of all metrics\n metrics = [naive_mae, ses_mae, trend_mae, dtrend_mae, arima_mae,\n ses_mase, trend_mase, dtrend_mase, arima_mase]\n \n return(metrics)", "def _SSA_single_simulation(self, final_time, time_stamp, model_dimension, trans_number):\n # tracks simulation time and state\n time = 0\n state = self.x0\n # tracks index of the time stamp vector, to save the array\n print_index = 1\n x = np.zeros((len(time_stamp), model_dimension))\n # save initial state\n x[0, :] = self.x0\n # main SSA loop\n trans_code = range(trans_number)\n while time < final_time:\n # compute rates and total rate\n rates = self.model.evaluate_rates(state)\n # sanity check, to avoid negative numbers close to zero\n rates[rates < 1e-14] = 0.0\n total_rate = sum(rates)\n # check if total rate is non zero.\n if total_rate > 1e-14:\n # if so, sample next time and next state and update state and time\n trans_index = rnd.choice(trans_number, p=rates / total_rate)\n delta_time = rnd.exponential(1 / (self.model.system_size * total_rate))\n time += delta_time\n state = state + self.model.transitions[trans_index].update.flatten() / self.model.system_size\n else:\n # If not, stop simulation by skipping to final time\n time = final_time\n # store values in the output array\n while print_index < len(time_stamp) and time_stamp[print_index] <= time:\n x[print_index, :] = state\n print_index += 1\n # computes observables\n y = self._compute_observables(x)\n return y", "def FXSim(fxspot, vol, rdm, time):\n # create an array of lenght NbSims x \"time\" horizon\n sim = np.zeros((NbSims,len(time)))\n # simulate a random walk FX with no IR discounting\n for i in range(0,NbSims):\n for j in range(0,len(time)):\n #sim[i,j] = fxspot+time[j]*(vol)*rdm[i,j]*10/2 # percentage divide by 2 (xccy)\n if j == 0:\n sim[i,j] = fxspot\n else:\n sim[i,j] = sim[i,j-1]+np.sqrt(time[j]-time[j-1])*(vol)*rdm[i,j]\n # return simulation\n return sim", "def simulate(self, cslsq):\n self._set_tta_rates()\n self._set_generation_rates()\n y0 = np.array([self.GS_0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) # the number of zeros needs to match the number of species!\n y = odeint(lambda y, t: self._rate_equations(t, y, cslsq), y0, self.t)\n self._unpack_simulation(y, cslsq)", "def __init__(s, backtest=False, market_order=False, resolution=['1m', '5s'][0]):\n s.model_direction = Direction.long # can only be long in here.\n s.backtest = backtest\n s.resolution = 1 if not backtest else 1\n s.db_resolution = '1min' if s.resolution == 60 else '1s'\n s.sec_multiplier = 1 if s.resolution == 60 else 60 // s.resolution\n s.market_order = market_order\n s.asset = Assets.ETHUSD\n s.ts_start = datetime.datetime(2019, 4, 1)\n s.ts_end = datetime.datetime(2019, 4, 1, 23, 59, 59)\n s.params = dotdict()\n s.params.asset = 'ethusd'#s.asset\n s.params.data_start = s.ts_start\n s.params.data_end = s.ts_end\n s.params.exchange = \"bitmex\"\n s.steps = 0\n for fn in ['ohlc', 'ohlc_bid', 'ohlc_ask']:\n with open(os.path.join('./data/{}'.format(fn)), 'rb') as f:\n s.__setattr__(fn, pickle.load(f))\n with open(os.path.join('./data/predictions'), 'rb') as f:\n preds = pickle.load(f)\n s.ix_close = s.ohlc.columns.get_loc('close')\n # temp fix\n preds = preds[np.where(preds[:, 0]==s.ohlc.index[0])[0][0]:1+np.where(preds[:, 0]==s.ohlc.index[-1])[0][0]]\n s.states_ts = preds[:, 0]\n s.close_preds = preds[:, 1:]\n first_derivation = np.zeros_like(s.states_ts)\n first_derivation[1:] = np.subtract(preds[1:, 1], preds[:-1, 1])\n s.entry_ts = s.states_ts[np.where((preds[:, 1] >= 0.16) & (first_derivation > 0))]\n # cut some for testing here:\n s.entry_ts = s.entry_ts[::10]\n s.trade_entry_ix = np.where(s.states_ts==s.entry_ts[0])[0][0]\n # s.close_preds = s.load_from_db()\n # s.match_resolution()\n s.ma_period = 10 * s.sec_multiplier # int in min\n s.close_ma = s.get_talib_on_close(data=s.ohlc.iloc[:, s.ix_close].astype(float), inputParams=dict(timeperiod=s.ma_period))\n # s.reset_start_ix()\n s.close = s.ohlc.iloc[:, s.ix_close]\n s.states = s.init_state_array(len(preds))\n s.sql_to_state()\n s.state_size = s.states.shape[1]\n s.init_statistics()\n s.t_last_direction_change = 0\n s.action_space = ActionSpace()\n s.action_size = s.action_space.n\n s.ix = 0\n s.ts_now: datetime.datetime = s.to_ts(0)\n s.done = False\n s.actions = []\n s.rewards = []\n s.order_fills = []\n s.order_fee = {Assets.ETHUSD: 0.0, Assets.XBTUSD: 0}[s.asset]\n # if s.backtest:\n # s.vb = VectorizedBacktest(ts_start=pd.to_datetime(s.ts_start), ts_end=pd.to_datetime(s.ts_end))", "def simulate_trading(self):\n out_filename = \"multiBacktestResults.csv\"\n resultsDir = settings.OUTPUT_RESULTS_DIR\n out_file = os.path.join(resultsDir, out_filename)\n out = open(out_file, \"w\")\n \n spl = len(self.strat_params_list)\n for i, sp in enumerate(self.strat_params_list):\n print(\"Strategy %s out of %s...\" % (i+1, spl))\n self._generate_trading_instances(sp)\n self._run_backtest()\n stats = self._output_performance()\n pprint.pprint(stats)\n \n tot_ret = float(stats[0][1].replace(\"%\",\"\"))\n cagr = float(stats[1][1].replace(\"%\",\"\"))\n sharpe = float(stats[2][1])\n max_dd = float(stats[3][1].replace(\"%\",\"\"))\n dd_dur = int(stats[4][1])\n \n out.write(\n \"%s,%s,%s,%s,%s,%s,%s\\n\" % (\n sp[\"short_window\"], sp[\"long_window\"],\n tot_ret, cagr, sharpe, max_dd, dd_dur))\n \n out.close()\n \n \n self._run_backtest()\n self._output_performance()\n print(\"Backtest complete.\")", "def simulate_trade_random(real_prices, initial_capital):\n trader = Trader(initial_capital)\n for day in range(len(real_prices)):\n if random.choice([True, False]):\n trader.buy_or_hold_order(real_prices[day])\n else:\n trader.sell_order(real_prices[day])\n return calculate_roi(trader.capital, initial_capital)", "def main(self, useDelay = False):\n for currentTau in range(0,self.finalTau):\n #print(currentTau)\n self.runOneTimeStep(currentTau)\n if useDelay:\n time.sleep(self.tau)", "def main_program(positions_input, number_of_simulations):\n print(\"Please WAIT! The program is calculating daily returns for your inputted scenarios. This may take a while.\")\n \n # this is the file where the stats results will be saved\n file = open(\"results.txt\", \"w\")\n file.close()\n for i in positions_input:\n # for each position, define daily_return using the class to \"fix\" simulated results so that\n # the histogram and stats are produced using the same daily return values\n daily_ret = investment_instrument(i,number_of_simulations).generate_daily_returns()\n investment_instrument(i,number_of_simulations).histogram(daily_ret)\n investment_instrument(i,number_of_simulations).summary_stats(daily_ret)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Classifies the given pattern.
def classify(self, pattern): import numpy w = numpy.array([self.weights]) x = numpy.array([pattern]) u = numpy.dot(w,x.transpose()) return self.actvf(u)
[ "def add_pattern(self, pattern_name, pattern_class):\n if pattern_name not in self.config['pattern']:\n self.config['pattern'][pattern_name] = {}\n self.pattern[pattern_name] = pattern_class(\n self.config['pattern'][pattern_name],\n self.config['system']\n )", "def pattern(self, pattern):\n\n self.container['pattern'] = pattern", "def get_for_pattern(self, pattern):", "def output_pattern(self, pattern):\n self._clear()\n for i, line in enumerate(pattern.split(\"\\n\")):\n # for each row in the pattern\n for j, c in enumerate(line):\n # for each cell in that row\n if c == \"*\":\n # If the cell is alive, set that cell's coordinates, ready to be drawn.\n self._set(j, i)\n # Draws to the grid, turning all of the set cells on.\n self._draw()", "def compile_pattern(self):\r\n if self.PATTERN is not None:\r\n PC = PatternCompiler()\r\n self.pattern, self.pattern_tree = PC.compile_pattern(self.PATTERN,\r\n with_tree=True)", "def output_pattern(self, pattern):\n self._clear()\n for i, line in enumerate(pattern.split(\"\\n\")):\n # for each row in the given pattern.\n for j, c in enumerate(line):\n # for each cell inside that row\n if c == \"*\":\n # If the cell is alive, set the coordinates of that cell on the display to be drawn\n self._set(j, i)\n # Draw the new configuration to the display.\n self._draw()", "def __code_pattern_analyzer__(self):\n\n if self.get_pattern() is not None and len(self.get_pattern()) == len(self.get_pattern_seperator()):\n for i in range(len(self.get_pattern())):\n pattern_sep = str(self.get_pattern_seperator()[i]) if self.get_pattern_seperator()[i] else None\n data, pattern = condition_checker.check_condition(str(self.get_pattern()[i]), self.dataframe,\n pattern_sep)\n if self.get_run_pattern_match():\n self.__report_xlsx__(data, \"%s_pattern\" % self.get_pattern()[i])\n pattern.to_html(\"%s.html\" % os.path.join(self.report_path, self.get_pattern()[i] + \"Pivot_\" +\n self.get_timestamp()))\n else:\n print(\"The pattern input is expected to be list and should be of same length as pattern separators\")", "def applyAttrPattern(nodeType=\"string\", patternName=\"string\"):\n pass", "def target(self, pattern):\n raise NotImplementedError", "def Pattern(self) -> str:", "def add_pattern(self,name,pat):\n\t\tself.pattern.append(pat)\n\t\tself.store.append(['%s (%s)' %(name,pat)])", "def _createRegex(self, pattern):\n return '%s$' % pattern.replace( '*', '.*').replace( '?', '.')", "def __init__(self, pattern):\r\n\r\n self.regexp = None\r\n self.pattern = pattern\r\n \r\n # Is pattern a regular expression?\r\n if len(pattern)>=2 and pattern[0]==\"/\" and pattern[-1]==\"/\":\r\n self.regexp = re.compile(pattern[1:-1])", "def compile_pattern(self, input, debug=False, with_tree=False):\r\n tokens = tokenize_wrapper(input)\r\n try:\r\n root = self.driver.parse_tokens(tokens, debug=debug)\r\n except parse.ParseError as e:\r\n raise PatternSyntaxError(str(e))\r\n if with_tree:\r\n return self.compile_node(root), root\r\n else:\r\n return self.compile_node(root)", "def register_rule(cls, klass):\n\t\tfor_type = klass.rule_type if klass else None\n\t\tif not for_type:\n\t\t\traise Exception('I need a class with a rule_type')\n\t\tif for_type in cls.matcher_classes:\t\t# could check if class is different to fail gracefully on double-imports\n\t\t\traise Exception('I have already registered {} for {}'.format(cls.matcher_classes[for_type]), for_type)\n\t\tcls.matcher_classes[for_type] = klass", "def on_pattern_message(self, sender, data, topic=pub.AUTO_TOPIC):\n\n logger.debug(\"Topic {}, Params: {}\".format(topic.getName(), data))\n\n if len(data) == 0:\n return\n\n self.apa102.set_pattern(data)", "def save_pattern(self):\n _dir = os.path.join(PATTERN_DIR, self.get_name()+'.pattern')\n save(self.pattern, _dir)", "def hasPattern(self, column, pattern, assertion = is_one):\n # function = jc.scala_function1(self.spark.sparkContext._gateway,\n # assertion)\n # pattern = jc.scala_regex(self.spark.sparkContext._gateway, pattern)\n # jvmConstraint = self.jvmCheck.hasPattern(\n # column,\n # pattern,\n # function,\n # getattr(self.jvmCheck, \"hasPattern$default$4\")(),\n # getattr(self.jvmCheck, \"hasPattern$default$5\")()\n # )\n # return Check(\n # self.spark,\n # self.level,\n # self.description,\n # jvmConstraint\n # )\n pass", "def scan_and_classify(self, directory, patterns):\n\n def walk(name, path):\n\n # Ignore ASCII control characters, like (Icon\\r on the mac).\n if re.search('[\\x00-\\x19]', name):\n return\n\n is_dir = os.path.isdir(path)\n\n if is_dir:\n match_names = [ name + \"/\", name ]\n else:\n match_names = [ name ]\n\n for pattern, file_list in patterns:\n\n matched = False\n\n for match_name in match_names:\n\n if match(match_name, pattern):\n\n # When we have ('test/**', None), avoid excluding test.\n if (not file_list) and is_dir:\n new_pattern = pattern.rstrip(\"*\")\n if (pattern != new_pattern) and match(match_name, new_pattern):\n continue\n\n matched = True\n break\n\n if matched:\n break\n\n else:\n print(str(match_name), \"doesn't match anything.\", file=self.log)\n\n pattern = None\n file_list = None\n\n print(str(match_name), \"matches\", str(pattern), \"(\" + str(file_list) + \").\", file=self.log)\n\n if file_list is None:\n return\n\n for fl in file_list:\n f = File(name, path, is_dir, False)\n self.file_lists[fl].append(f)\n\n if is_dir:\n\n for fn in os.listdir(path):\n walk(\n name + \"/\" + fn,\n os.path.join(path, fn),\n )\n\n for fn in os.listdir(directory):\n walk(fn, os.path.join(directory, fn))" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handles the error when the server fails to find a sequence. Function expects a client state object, a username, and the sequence id that raises the exception. Function shall return the state from GET /Elixys/state.
def handle_sequence_not_found(client_state, username, sequence_id): client_state = getCurrentClientState(username) current_app.logger.debug("Failed to find sequence: " + str(sequence_id) + \ "Client state: " + str(client_state)) # Was it the sequence that the user is currently on? if client_state["sequenceid"] == int(sequence_id): # Yes, so return the user to the last Select Sequence screen client_state = direct_to_last_select_screen(client_state) db.update_user_client_state(username, client_state) current_app.logger.error("Redirecting user to select sequences page") # Return the state elixys_get_state = Elixys_Get_State() return elixys_get_state.state_index()
[ "def handle_invalid_sequence(username, sequence_id):\n current_app.logger.error(\"Cannot run invalid sequence (\" +\n str(sequence_id) + \"\\nUser:\" + str(username))\n return {\"type\":\"error\", \"description\":\"Invalid sequence\"}", "def testBadStateid(t, env):\n c = env.c1\n c.init_connection()\n fh, stateid = c.create_confirm(t.code)\n res = c.lock_file(t.code, fh, stateid4(0, ''))\n check(res, NFS4ERR_BAD_STATEID, \"LOCK with a bad stateid\")", "def socksclienterror(self) :\n\t\ttry :\n\t\t\treturn self._socksclienterror\n\t\texcept Exception as e:\n\t\t\traise e", "def get_error(self, indication, status, index, address):\n\t\t\n\t\t#print('SNMPGET ERROR')\n\n\t\tif indication:\n\t\t\tprint(str(indication) + ' from ' + str(address))\n\t\telif status:\n\t\t\tprint(status)", "def error(self):\n \n print('---error state report ---')\n print(' state', self.state)\n print(' scenario', self.scenario)\n print(' parameters', self.parameters)\n print(' msg', self.msg)\n print('state history', self.state_history)\n print(' tree dump:')\n print(self.tree[0].dump())\n print('--end error state report---')\n raise RuntimeError('error state')", "async def get_callback_esi(code: str, state: str):\n logging.info(\"Received callback from ESI for state %s\", state)\n\n state_code: StateCode = StateCode.objects.get(uuid=state)\n state_code.delete()\n\n try:\n esi_response = get_access_token_from_callback_code(code)\n access_token = decode_access_token(esi_response.access_token)\n save_esi_tokens(esi_response)\n except EsiTokenError:\n return token_manipulation_error_response()\n\n usr: User = User.objects.get(character_id=access_token.character_id)\n if state_code.inviting_corporation is not None:\n usr.corporation = state_code.inviting_corporation\n usr.clearance_level = -1\n usr.save()\n\n if not is_authorized_to_login(usr):\n return not_authorized_to_login_response(\n usr.character_name, usr.character_id\n )\n if not token_has_enough_scopes(access_token, usr):\n return not_enough_scopes_response(\n usr.character_name,\n usr.character_id,\n list(usr.cumulated_mandatory_esi_scopes()),\n access_token.scp,\n )\n\n user_token = create_user_token(state_code.app_token, usr)\n user_jwt_str = to_jwt(user_token)\n logging.info(\n \"Issuing token %s to app %s\", user_jwt_str, state_code.app_token.uuid\n )\n\n if state_code.app_token.callback is None:\n return {\n \"created_on\": user_token.created_on,\n \"expires_on\": user_token.expires_on,\n \"jwt\": user_jwt_str,\n \"owner\": {\n \"character_id\": user_token.owner.character_id,\n \"character_name\": user_token.owner.character_name,\n \"clearance_level\": user_token.owner.clearance_level,\n },\n }\n\n request = requests.Request(\n \"GET\",\n state_code.app_token.callback,\n params={\n \"state_code\": str(state_code.uuid),\n \"user_token\": user_jwt_str,\n },\n )\n url = request.prepare().url\n if url is None:\n logging.error(\n \"Failed to redirect user to %s\", state_code.app_token.callback,\n )\n return PlainTextResponse(\n f\"Failed to redirect to {state_code.app_token.callback}\"\n )\n return RedirectResponse(url=url)", "async def save_error_state(\n self,\n session: ProfileSession,\n *,\n state: str = None,\n reason: str = None,\n log_params: Mapping[str, Any] = None,\n log_override: bool = False,\n ):\n\n if self._last_state == state: # already done\n return\n\n self.state = state or V10CredentialExchange.STATE_ABANDONED\n if reason:\n self.error_msg = reason\n\n try:\n await self.save(\n session,\n reason=reason,\n log_params=log_params,\n log_override=log_override,\n )\n except StorageError:\n LOGGER.exception(\"Error saving credential exchange error state\")", "def test_throws_error_on_wrong_state(self):\n with self.assertRaises(StreamlitAPIException):\n st.status(\"label\", state=\"unknown\")", "def on_tac_error(self, error: Error) -> None:\n logger.error(\"[{}]: Received error from the controller. error_msg={}\".format(self.agent_name, error.error_msg))\n if error.error_code == ErrorCode.TRANSACTION_NOT_VALID:\n # if error in checking transaction, remove it from the pending transactions.\n start_idx_of_tx_id = len(\"Error in checking transaction: \")\n transaction_id = error.error_msg[start_idx_of_tx_id:]\n if transaction_id in self.game_instance.transaction_manager.locked_txs:\n self.game_instance.transaction_manager.pop_locked_tx(transaction_id)\n else:\n logger.warning(\"[{}]: Received error on unknown transaction id: {}\".format(self.agent_name, transaction_id))\n pass\n elif error.error_code == ErrorCode.TRANSACTION_NOT_MATCHING:\n pass\n elif error.error_code == ErrorCode.AGENT_PBK_ALREADY_REGISTERED or error.error_code == ErrorCode.AGENT_NAME_ALREADY_REGISTERED or error.error_code == ErrorCode.AGENT_NOT_REGISTERED:\n self.liveness._is_stopped = True\n elif error.error_code == ErrorCode.REQUEST_NOT_VALID or error.error_code == ErrorCode.GENERIC_ERROR:\n logger.warning(\"[{}]: Check last request sent and investigate!\".format(self.agent_name))", "def get_error(session, error_id):\n error = session.query(models.Error).get(error_id)\n if not error: # If invalid error id, bail out\n raise InvalidErrorReference(\"No error with id %s\" % str(error_id))\n return derive_error_dict(error)", "def error(r, line, bot, chan):\n raise Exception('IRCD Error \"{}\"'.format(line))", "def _check_status(sdp_state):\n try:\n errval = \"error\"\n errdict = dict(state=\"unknown\", reason=\"unknown\")\n if sdp_state.current_state == \"unknown\":\n errdict['reason'] = 'database not initialised.'\n LOG.debug('Current state is unknown;')\n LOG.debug('Target state is %s;', sdp_state.target_state)\n LOG.debug('Current state timestamp is %s;',\n sdp_state.current_timestamp)\n elif sdp_state.current_state is None:\n errdict['reason'] = 'Master Controller Services may have died.'\n LOG.debug('Current state is NONE;')\n LOG.debug('Target state is %s;', sdp_state.target_state)\n LOG.debug('Current state timestamp is %s;',\n sdp_state.current_timestamp)\n elif sdp_state.target_state is None:\n errdict['reason'] = 'Master Controller Services may have died.'\n LOG.debug('Current state is %s;',\n sdp_state.current_state)\n LOG.debug('Target state is NONE;')\n LOG.debug('Current state timestamp is %s;',\n sdp_state.current_timestamp)\n LOG.debug('Target state timestamp is %s;',\n sdp_state.target_timestamp)\n elif sdp_state.current_timestamp is None:\n errdict['reason'] = 'Master Controller Services may have died.'\n LOG.debug('Current state is %s;',\n sdp_state.current_state)\n LOG.debug('Target state is %s;', sdp_state.target_state)\n LOG.debug('Current state timestamp is NONE')\n LOG.debug('Target state timestamp is %s;',\n sdp_state.target_timestamp)\n elif sdp_state.target_timestamp is None:\n errdict['reason'] = 'Master Controller Services may have died.'\n LOG.debug('Current state is %s;',\n sdp_state.current_state)\n LOG.debug('Target state is %s;', sdp_state.target_state)\n LOG.debug('Current state timestamp is %s;',\n sdp_state.current_timestamp)\n LOG.debug('Target state timestamp is NONE')\n elif sdp_state.current_timestamp < sdp_state.target_timestamp:\n errdict['reason'] = \\\n 'Timestamp for Master Controller Services is stale.'\n LOG.debug('Current state is %s;',\n sdp_state.current_state)\n LOG.debug('Target state is %s;', sdp_state.target_state)\n LOG.debug('Current state timestamp is %s;',\n sdp_state.current_timestamp)\n LOG.debug('Target state timestamp is %s;',\n sdp_state.target_timestamp)\n else:\n errval = \"okay\"\n except ConnectionError as err:\n errdict['reason'] = err\n LOG.debug('Connection Error %s', err)\n return errval, errdict", "async def a_error_handler(response: ClientResponse):\n resp = await response.json()\n if response.status != 200:\n if isinstance(resp, dict):\n if resp.get(\"Error\"):\n raise FindcloneError(f\"error_code: {response.status}\", resp[\"Error\"])\n\n return True", "def test_instance_error_state(self):\n aws_svc, encryptor_image, guest_image = build_aws_service()\n instance = aws_svc.run_instance(guest_image.id)\n instance._state.name = 'error'\n try:\n encrypt_ami.wait_for_instance(aws_svc, instance.id, timeout=100)\n except encrypt_ami.InstanceError as e:\n self.assertTrue('error state' in e.message)", "async def test_get_isolate(error, spawn_client, resp_is, test_otu, test_sequence):\n client = await spawn_client(authorize=True)\n\n if error == \"404_isolate\":\n test_otu[\"isolates\"] = list()\n\n if error != \"404_otu\":\n await client.db.otus.insert_one(test_otu)\n\n await client.db.sequences.insert_one(test_sequence)\n\n resp = await client.get(\"/api/otus/6116cba1/isolates/cab8b360\")\n\n if error:\n assert await resp_is.not_found(resp)\n return\n\n assert resp.status == 200\n\n test_sequence[\"id\"] = test_sequence.pop(\"_id\")\n\n del test_sequence[\"otu_id\"]\n del test_sequence[\"isolate_id\"]\n\n assert await resp.json() == {\n \"default\": True,\n \"source_type\": \"isolate\",\n \"source_name\": \"8816-v2\",\n \"id\": \"cab8b360\",\n \"sequences\": [test_sequence]\n }", "def recover(self, error):\n raise error", "def raise_grib_error(errid):\n raise ERROR_MAP[errid](errid)", "def error_received(self, exc: Exception) -> None:", "def _translate_job_errors(self, job_id):\n try:\n yield\n except OpenEoApiError as e:\n if e.code == JobNotFoundException.code:\n raise JobNotFoundException(job_id=job_id, )\n elif e.code == JobNotFinishedException.code:\n raise JobNotFinishedException(message=e.message)\n raise" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handles the error when the server fails to find a component Function expects a client state, username and component id that generate the exception. Function return the state from GET /Elixys/state.
def handle_component_not_found(client_state, username, component_id): current_app.logger.debug("Failed to find component " + str(component_id)) # Was it the component that the user is currently on? if client_state["componentid"] == component_id: # Yes sequence_id = 0 try: # Get the sequence sequence_id = client_state["sequenceid"] sequence = db.get_sequence(sequence_id) # Move the client to the first unit operation client_state["componentid"] = sequence["components"][0]["id"] db.update_user_client_state(username, client_state) current_app.logger.warn("Redirecting user to the " + \ "first component of sequence " + str(sequence_id)) except Exceptions.SequenceNotFoundException as ex: # Sequence not found current_app.logger.error("Sequence Not Found Exception" + str(ex)) return handle_sequence_not_found( client_state, username, sequence_id) # Return the state elixys_get_state = Elixys_Get_State() return elixys_get_state.state_index()
[ "def handle_sequence_not_found(client_state, username, sequence_id):\n client_state = getCurrentClientState(username)\n\n current_app.logger.debug(\"Failed to find sequence: \" + str(sequence_id) + \\\n \"Client state: \" + str(client_state))\n\n # Was it the sequence that the user is currently on?\n if client_state[\"sequenceid\"] == int(sequence_id):\n # Yes, so return the user to the last Select Sequence screen\n client_state = direct_to_last_select_screen(client_state)\n db.update_user_client_state(username, client_state)\n current_app.logger.error(\"Redirecting user to select sequences page\")\n\n # Return the state\n elixys_get_state = Elixys_Get_State()\n return elixys_get_state.state_index()", "def socksclienterror(self) :\n\t\ttry :\n\t\t\treturn self._socksclienterror\n\t\texcept Exception as e:\n\t\t\traise e", "def get_component_exceptions(\n cluster: str,\n environ: str,\n topology: str,\n component: str,\n role: Optional[str]=None,\n) -> Any:\n base_url = create_url(EXCEPTIONS_URL_FMT)\n params = {\n \"cluster\": cluster,\n \"environ\": environ,\n \"topology\": topology,\n \"role\": role,\n \"component\": component,\n }\n return api_get(base_url, params)", "def test_throws_error_on_wrong_state(self):\n with self.assertRaises(StreamlitAPIException):\n st.status(\"label\", state=\"unknown\")", "def server_error(error):\n return make_response(jsonify({\"message\": \"Internall error\"}),500)", "def database_not_found_error_handler(e): # pragma: no cover\n\n log.warning(traceback.format_exc())\n return {'message': 'database result was required but none was found.'}, 404", "def log_component_not_found(entity: EntityID, component: Type[Component]):\n name = world.get_name(entity)\n logging.warning(f\"'{name}'({entity}) tried to get {component.__name__}, but it was not found.\")", "def test_server_invalid_state(self):\n artifact_id = self.my_create_appliance(\"testbad\")\n #But which exception? Currently we get a TypeError\n with self.assertRaises(Exception):\n s.touch_to_state(None, artifact_id, \"BAD\")", "def staconnfailure(self) :\n\t\ttry :\n\t\t\treturn self._staconnfailure\n\t\texcept Exception as e:\n\t\t\traise e", "def test_nonexistent_component_given(self, admin_node):\n logger.info(\"Error code for nonexistent component name\")\n component = [\"wrong_component\"]\n expected = 1\n cmd = \"ccp show-dep {}\".format(component[0])\n admin_node.check_call(cmd, expected=[expected])", "def socksservererror(self) :\n\t\ttry :\n\t\t\treturn self._socksservererror\n\t\texcept Exception as e:\n\t\t\traise e", "def cpsconnfailure(self) :\n\t\ttry :\n\t\t\treturn self._cpsconnfailure\n\t\texcept Exception as e:\n\t\t\traise e", "def map_remote_error(ex):\r\n inval_param_errors = (\r\n 'AttributeError',\r\n 'ValueError',\r\n 'InvalidTenant',\r\n 'StackNotFound',\r\n 'ResourceNotFound',\r\n 'ResourceNotAvailable',\r\n 'ResourceTypeNotFound',\r\n 'PhysicalResourceNotFound',\r\n 'WatchRuleNotFound',\r\n 'StackValidationFailed',\r\n 'InvalidTemplateReference',\r\n 'InvalidTemplateVersion',\r\n 'InvalidTemplateSection',\r\n 'UnknownUserParameter',\r\n 'UserParameterMissing',\r\n 'InvalidTemplateParameter',\r\n )\r\n denied_errors = ('Forbidden', 'NotAuthorized')\r\n already_exists_errors = ('StackExists')\r\n invalid_action_errors = ('ActionInProgress',)\r\n\r\n ex_type = ex.__class__.__name__\r\n\r\n if ex_type.endswith(rpc_common._REMOTE_POSTFIX):\r\n ex_type = ex_type[:-len(rpc_common._REMOTE_POSTFIX)]\r\n\r\n if ex_type in inval_param_errors:\r\n return HeatInvalidParameterValueError(detail=six.text_type(ex))\r\n elif ex_type in denied_errors:\r\n return HeatAccessDeniedError(detail=six.text_type(ex))\r\n elif ex_type in already_exists_errors:\r\n return AlreadyExistsError(detail=six.text_type(ex))\r\n elif ex_type in invalid_action_errors:\r\n return HeatActionInProgressError(detail=six.text_type(ex))\r\n else:\r\n # Map everything else to internal server error for now\r\n return HeatInternalFailureError(detail=six.text_type(ex))", "def server_error(err):\n\n return connexion.problem(\n status=503,\n title='Service unavailable',\n detail=err.format_message())", "def testBadStateColocation(self):\n with self.assertRaisesRegexp(ValueError, \"(?s)state.*colocate.*loc:@u\"):\n _ = hub.create_module_spec(bad_state_colocation_module_fn)", "def error(r, line, bot, chan):\n raise Exception('IRCD Error \"{}\"'.format(line))", "def error(self):\n \n print('---error state report ---')\n print(' state', self.state)\n print(' scenario', self.scenario)\n print(' parameters', self.parameters)\n print(' msg', self.msg)\n print('state history', self.state_history)\n print(' tree dump:')\n print(self.tree[0].dump())\n print('--end error state report---')\n raise RuntimeError('error state')", "def error():\n try:\n status = int(request.environ['REDIRECT_STATUS'])\n except:\n # if there's an exception, it means that a client accessed this directly;\n # in this case, we want to make it look like the endpoint is not here\n return api_404_handler()\n msg = 'Unknown error'\n # for now, we just provide specific error for stuff that already happened;\n # before adding more, I'd like to see them actually happening with reproducers\n if status == 401:\n msg = 'Authentication failed'\n elif status == 405:\n msg = 'Method not allowed for this endpoint'\n raise HTTPError(status, msg)", "def handle_error(self):\n LOG.debug(\"Error during a call to NSS library, trying to obtain error info\")\n\n code = self._PORT_GetError()\n name = self._PR_ErrorToName(code)\n name = \"NULL\" if name is None else name.decode(\"ascii\")\n # 0 is the default language (localization related)\n text = self._PR_ErrorToString(code, 0)\n text = text.decode(\"utf8\")\n\n LOG.debug(\"%s: %s\", name, text)", "def virConnGetLastError(self):\n ret = libvirtmod.virConnGetLastError(self._o)\n return ret" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handles the error when the server fails to find a reagent. Function expects a client state, username and reagent id. Function shall redirect user to previous screen on client. Function returns the state from GET /Elixys/state.
def handle_reagent_not_found(client_state, username, reagent_id): current_app.logger.debug("Failed to find reagent " + str(reagent_id)) # This error should only occur if the user has # the sequence they are currently viewing delete out from # under them. Redirect them to the last Select Sequence screen client_state = direct_to_last_select_screen(client_state) db.update_user_client_state(username, client_state) current_app.logger.warn("Redirecting user to last screen.") # Return the state get_state = Elixys_Get_State() return get_state.state_index()
[ "def error():\n try:\n status = int(request.environ['REDIRECT_STATUS'])\n except:\n # if there's an exception, it means that a client accessed this directly;\n # in this case, we want to make it look like the endpoint is not here\n return api_404_handler()\n msg = 'Unknown error'\n # for now, we just provide specific error for stuff that already happened;\n # before adding more, I'd like to see them actually happening with reproducers\n if status == 401:\n msg = 'Authentication failed'\n elif status == 405:\n msg = 'Method not allowed for this endpoint'\n raise HTTPError(status, msg)", "def handle_sequence_not_found(client_state, username, sequence_id):\n client_state = getCurrentClientState(username)\n\n current_app.logger.debug(\"Failed to find sequence: \" + str(sequence_id) + \\\n \"Client state: \" + str(client_state))\n\n # Was it the sequence that the user is currently on?\n if client_state[\"sequenceid\"] == int(sequence_id):\n # Yes, so return the user to the last Select Sequence screen\n client_state = direct_to_last_select_screen(client_state)\n db.update_user_client_state(username, client_state)\n current_app.logger.error(\"Redirecting user to select sequences page\")\n\n # Return the state\n elixys_get_state = Elixys_Get_State()\n return elixys_get_state.state_index()", "def error_page(code):\n # check if code is valid in case someone entered the url manually\n try:\n errornames[str(code)]\n except:\n return redirect(url_for(\"error_page\", code=404))\n # get the origin\n if \"origin\" in request.args:\n origin_url = request.args.get(\"origin\")\n else:\n origin_url = \"https://\" + app.config[\"SERVER_NAME\"]\n return (\n render_template(\n \"error.html\",\n code=str(code),\n message=errornames[str(code)] + \"!\",\n origin=origin_url,\n ),\n code,\n )", "def handle_login_error(e): \n flash(\"You do not have access rights.\")\n return redirect(url_for('auth.login'))", "def error(message, url=None):\n flash_error(message)\n return flask.redirect(url or referrer_or_home())", "def check_callback_errors(self):\n args = flask.request.args\n logged_in = current_user is not None and current_user.is_authenticated\n\n # redirect logged in user to index view\n if logged_in:\n flask.redirect(flask.url_for('index'))\n\n # error handling\n if 'error' in args:\n msg = 'Error encountered.'\n if args.get('error') == 'access_denied':\n msg = \"Access was denied.\"\n return msg\n\n if 'code' not in args and 'state' not in args:\n return flask.redirect(flask.url_for('login'))", "def server_error(error):\n return redirect(url_for('admin.bugsplat', error=error))", "def server_error(error):\n return make_response(jsonify({\"message\": \"Internall error\"}),500)", "def checkUserRequest():\r\n if request.args.get('state') != login_session['state']:\r\n return makeResponse('Invalid state parameter', 401)", "def error_page(e):\n return render_template('404.html'), 404", "def display_url_error(self, error_reason):\r\n self._display_error(f\"The server couldn't be reached (reason: {error_reason}). Please try again.\")", "def on_tac_error(self, error: Error) -> None:\n logger.error(\"[{}]: Received error from the controller. error_msg={}\".format(self.agent_name, error.error_msg))\n if error.error_code == ErrorCode.TRANSACTION_NOT_VALID:\n # if error in checking transaction, remove it from the pending transactions.\n start_idx_of_tx_id = len(\"Error in checking transaction: \")\n transaction_id = error.error_msg[start_idx_of_tx_id:]\n if transaction_id in self.game_instance.transaction_manager.locked_txs:\n self.game_instance.transaction_manager.pop_locked_tx(transaction_id)\n else:\n logger.warning(\"[{}]: Received error on unknown transaction id: {}\".format(self.agent_name, transaction_id))\n pass\n elif error.error_code == ErrorCode.TRANSACTION_NOT_MATCHING:\n pass\n elif error.error_code == ErrorCode.AGENT_PBK_ALREADY_REGISTERED or error.error_code == ErrorCode.AGENT_NAME_ALREADY_REGISTERED or error.error_code == ErrorCode.AGENT_NOT_REGISTERED:\n self.liveness._is_stopped = True\n elif error.error_code == ErrorCode.REQUEST_NOT_VALID or error.error_code == ErrorCode.GENERIC_ERROR:\n logger.warning(\"[{}]: Check last request sent and investigate!\".format(self.agent_name))", "def get_error_page(self, loadbalancer):\r\n return loadbalancer.get_error_page()", "def error(r, line, bot, chan):\n raise Exception('IRCD Error \"{}\"'.format(line))", "def elixir_callback():\n # Handle errors from ELIXIR AAI\n error = request.args.get('error', '')\n if error:\n return \"Error: \" + error\n state = request.args.get('state', '')\n # Check if session has been hijacked (currently inoperable)\n if not is_valid_state(state):\n abort(403)\n\n # Fetch code item from ELIXIR AAI callback to generate authorized access token\n code = request.args.get('code')\n access_token = get_token(code)\n\n try:\n # Create a redirection to Beacon UI with access token stored in cookies\n response = application.make_response(redirect(os.environ.get('REDIRECT_URL', None)))\n response.set_cookie('access_token',\n access_token,\n max_age=int(os.environ.get('COOKIE_AGE', 3600)),\n secure=os.environ.get('COOKIE_SECURE', True),\n domain=os.environ.get('COOKIE_DOMAIN', None))\n if get_bona_fide_status(access_token):\n # If user has bona fide status, add a cookie for this\n response.set_cookie('bona_fide_status',\n BONA_FIDE_URL,\n max_age=int(os.environ.get('COOKIE_AGE', 3600)),\n secure=os.environ.get('COOKIE_SECURE', True),\n domain=os.environ.get('COOKIE_DOMAIN', None))\n except Exception as e:\n LOG.error(str(e))\n\n return response", "def redirect_error_handler(redirect_path: str, exception: Exception, **kwargs) -> RedirectResponse:\n return RedirectResponse(urls.with_query_params(redirect_path, error=exception, **kwargs))", "def _handleProxyErrors(self, errcode):\n if errcode == 503:\n # Service unavailable, make it a socket error\n e = socket.error(111, \"Service unavailable\")\n elif errcode == 502:\n # Bad gateway (server responded with some broken answer)\n e = socket.error(111, \"Bad Gateway (error reported by proxy)\")\n else:\n return\n # Proxy errors are treated as request errors, which are retriable.\n saved = util.SavedException(e)\n raise http_error.RequestError(saved)", "def _restore_resource(self, state, prev_state):\n log.debug(\"starting agent restore process, State: %s, Prev State: %s\", state, prev_state)\n\n # Get state to restore. If the last state was lost connection,\n # use the prior connected state.\n if not state:\n log.debug(\"State not defined, not restoring\")\n return\n\n if state == ResourceAgentState.LOST_CONNECTION:\n state = prev_state\n\n try:\n cur_state = self._fsm.get_current_state()\n\n # If unitialized, confirm and do nothing.\n if state == ResourceAgentState.UNINITIALIZED:\n if cur_state != state:\n raise Exception()\n\n # If inactive, initialize and confirm.\n elif state == ResourceAgentState.INACTIVE:\n self._fsm.on_event(ResourceAgentEvent.INITIALIZE)\n cur_state = self._fsm.get_current_state()\n if cur_state != state:\n raise Exception()\n\n # If idle, initialize, activate and confirm.\n elif state == ResourceAgentState.IDLE:\n self._fsm.on_event(ResourceAgentEvent.INITIALIZE)\n self._fsm.on_event(ResourceAgentEvent.GO_ACTIVE)\n cur_state = self._fsm.get_current_state()\n if cur_state != state:\n raise Exception()\n\n # If streaming, initialize, activate and confirm.\n # Driver discover should put us in streaming mode.\n elif state == ResourceAgentState.STREAMING:\n self._fsm.on_event(ResourceAgentEvent.INITIALIZE)\n self._fsm.on_event(ResourceAgentEvent.GO_ACTIVE)\n self._fsm.on_event(ResourceAgentEvent.RUN)\n self._fsm.on_event(ResourceAgentEvent.EXECUTE_RESOURCE, DriverEvent.START_AUTOSAMPLE)\n cur_state = self._fsm.get_current_state()\n if cur_state != state:\n raise Exception()\n\n # If command, initialize, activate, confirm idle,\n # run and confirm command.\n elif state == ResourceAgentState.COMMAND:\n self._fsm.on_event(ResourceAgentEvent.INITIALIZE)\n self._fsm.on_event(ResourceAgentEvent.GO_ACTIVE)\n cur_state = self._fsm.get_current_state()\n if cur_state != ResourceAgentState.IDLE:\n raise Exception()\n self._fsm.on_event(ResourceAgentEvent.RUN)\n cur_state = self._fsm.get_current_state()\n if cur_state != state:\n raise Exception()\n\n # If paused, initialize, activate, confirm idle,\n # run, confirm command, pause and confirm stopped.\n elif state == ResourceAgentState.STOPPED:\n self._fsm.on_event(ResourceAgentEvent.INITIALIZE)\n self._fsm.on_event(ResourceAgentEvent.GO_ACTIVE)\n cur_state = self._fsm.get_current_state()\n if cur_state != ResourceAgentState.IDLE:\n raise Exception()\n self._fsm.on_event(ResourceAgentEvent.RUN)\n cur_state = self._fsm.get_current_state()\n if cur_state != ResourceAgentState.COMMAND:\n raise Exception()\n self._fsm.on_event(ResourceAgentEvent.PAUSE)\n cur_state = self._fsm.get_current_state()\n if cur_state != state:\n raise Exception()\n\n # If in a command reachable substate, attempt to return to command.\n # Initialize, activate, confirm idle, run confirm command.\n elif state in [ResourceAgentState.TEST,\n ResourceAgentState.CALIBRATE,\n ResourceAgentState.DIRECT_ACCESS,\n ResourceAgentState.BUSY]:\n self._fsm.on_event(ResourceAgentEvent.INITIALIZE)\n self._fsm.on_event(ResourceAgentEvent.GO_ACTIVE)\n cur_state = self._fsm.get_current_state()\n if cur_state != ResourceAgentState.IDLE:\n raise Exception()\n self._fsm.on_event(ResourceAgentEvent.RUN)\n cur_state = self._fsm.get_current_state()\n if cur_state != ResourceAgentState.COMMAND:\n raise Exception()\n\n # If active unknown, return to active unknown or command if\n # possible. Initialize, activate, confirm active unknown, else\n # confirm idle, run, confirm command.\n elif state == ResourceAgentState.ACTIVE_UNKNOWN:\n self._fsm.on_event(ResourceAgentEvent.INITIALIZE)\n self._fsm.on_event(ResourceAgentEvent.GO_ACTIVE)\n cur_state = self._fsm.get_current_state()\n if cur_state == ResourceAgentState.ACTIVE_UNKNOWN:\n return\n elif cur_state != ResourceAgentState.IDLE:\n raise Exception()\n self._fsm.on_event(ResourceAgentEvent.RUN)\n cur_state = self._fsm.get_current_state()\n if cur_state != ResourceAgentState.COMMAND:\n raise Exception()\n\n else:\n log.error('Instrument agent %s error restoring unhandled state %s, current state %s.',\n self.id, state, cur_state)\n\n except Exception as ex:\n log.error('Instrument agent %s error restoring state %s, current state %s, exception %s.',\n self.id, state, cur_state, str(ex))\n log.exception('###### Agent restore stack trace:')\n\n else:\n log.debug('Instrument agent %s restored state %s = %s.',\n self.id, state, cur_state)", "async def save_error_state(\n self,\n session: ProfileSession,\n *,\n state: str = None,\n reason: str = None,\n log_params: Mapping[str, Any] = None,\n log_override: bool = False,\n ):\n\n if self._last_state == state: # already done\n return\n\n self.state = state or V10CredentialExchange.STATE_ABANDONED\n if reason:\n self.error_msg = reason\n\n try:\n await self.save(\n session,\n reason=reason,\n log_params=log_params,\n log_override=log_override,\n )\n except StorageError:\n LOGGER.exception(\"Error saving credential exchange error state\")", "def do_change_errorpage(self, args):\n lb = self.findlb(args.loadbalancer)\n ep = lb.errorpage()\n ep.add(args.html)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handles the error when the use attempts to run an invalid sequence
def handle_invalid_sequence(username, sequence_id): current_app.logger.error("Cannot run invalid sequence (" + str(sequence_id) + "\nUser:" + str(username)) return {"type":"error", "description":"Invalid sequence"}
[ "def handle_seq_abort():\n global _RUNNING_SEQ\n\n with Sessions.current() as session: # noqa: F841\n if _RUNNING_SEQ:\n _RUNNING_SEQ.kill()\n _RUNNING_SEQ = None\n log.info(\"Sequence aborted by user\")\n Sessions.add_event(\"seq:err\", \"Sequence aborted by user\")", "def test_sequence_failure(self):\n\n success1 = Stub(Result.Success)\n success2 = Stub(Result.Success)\n continue3 = Stub(Result.Continue)\n failure4 = Stub(Result.Failure)\n failure5 = Stub(Result.Failure)\n\n sequence = Sequence(\"Failing Sequence\")\n sequence.append(success1)\n sequence.append(success2)\n sequence.append(continue3)\n sequence.append(failure4)\n sequence.append(failure5)\n\n sequence.run(None)\n continue3.return_value = Result.Success\n result = sequence.run(None)\n\n self.assertEqual(Result.Failure, result)\n self.assertEqual(1, success1.calls)\n self.assertEqual(1, success2.calls)\n self.assertEqual(2, continue3.calls)\n self.assertEqual(1, failure4.calls)\n self.assertEqual(0, failure5.calls)", "def test_invalid_sequence(self):\n numeral = \"IVX\"\n response = validate(numeral)\n self.assertFalse(response['statusCode'] == 200, numeral + \" should not be a valid numeral sequence\")\n\n numeral = \"VXV\"\n response = validate(numeral)\n self.assertFalse(response['statusCode'] == 200, numeral + \" should not be a valid numeral sequence\")\n\n numeral = \"VXL\"\n response = validate(numeral)\n self.assertFalse(response['statusCode'] == 200, numeral + \" should not be a valid numeral sequence\")\n\n numeral = \"LC\"\n response = validate(numeral)\n self.assertFalse(response['statusCode'] == 200, numeral + \" should not be a valid numeral sequence\")", "def test_workflow_rule_no_sequence_run(self):\n mock_workflow: Workflow = Workflow()\n try:\n _ = WorkflowRule(mock_workflow).must_associate_sequence_run().must_have_output()\n except ValueError as e:\n logger.exception(f\"THIS ERROR EXCEPTION IS INTENTIONAL FOR TEST. NOT ACTUAL ERROR. \\n{e}\")\n\n self.assertRaises(ValueError)", "def running_sequence():\n raise NoSequenceFound", "def error(s):\n print('Robotics toolbox error:', s)\n\n #traceback.print_exc();\n raise ValueError", "def _failed():\n raise BaseException", "def failure(self):\n raise RuntimeError, \"This function always raises an error.\"", "def _encountered_error(self, event):\n self._log.error(vlc.libvlc_errmsg())\n self.next()", "def handle_sequence_not_found(client_state, username, sequence_id):\n client_state = getCurrentClientState(username)\n\n current_app.logger.debug(\"Failed to find sequence: \" + str(sequence_id) + \\\n \"Client state: \" + str(client_state))\n\n # Was it the sequence that the user is currently on?\n if client_state[\"sequenceid\"] == int(sequence_id):\n # Yes, so return the user to the last Select Sequence screen\n client_state = direct_to_last_select_screen(client_state)\n db.update_user_client_state(username, client_state)\n current_app.logger.error(\"Redirecting user to select sequences page\")\n\n # Return the state\n elixys_get_state = Elixys_Get_State()\n return elixys_get_state.state_index()", "def test_path_to_DNA_failure(self):\r\n\r\n for path in self.known_pattern_failure:\r\n self.assertRaises(ValueError, assembler.path_to_DNA, path)", "def recover(self, error):\n raise error", "def check_sequence(self) -> None:\n if not isinstance(self, SequenceType):\n raise UnexpectedTypeError(SequenceType, self)", "def error_received(self, exc: Exception) -> None:", "async def handle_error(self) -> RetryDirective:\n raise NotImplementedError()", "def test_read_input_rejection_invalid_symbol(self):\n with nose.assert_raises(exceptions.RejectionException):\n self.ntm1.read_input('02')", "def raise_runtime_error(self, message):\n print(\"Iceberg Runtime ERROR!\")\n print(\"In instruction number \" + str(self.exec_pos) + \",\")\n print(message)\n raise RuntimeError", "def test_send_unspent_inputs_to_error_already_finalized(self):\n self.bundle.add_transaction(ProposedTransaction(\n address =\n Address(\n b'TESTVALUE9DONTUSEINPRODUCTION99999XE9IVG'\n b'EFNDOCQCMERGUATCIEGGOHPHGFIAQEZGNHQ9W99CH'\n ),\n\n value = 0,\n ))\n\n self.bundle.finalize()\n\n with self.assertRaises(RuntimeError):\n self.bundle.send_unspent_inputs_to(Address(b''))", "def testIllegalSequenceType(self):\n seq_set = self.session.create_object(\"wgs_assembled_seq_set\")\n\n # Test int argument\n with self.assertRaises(Exception):\n seq_set.sequence_type = 1\n\n # Test list argument\n with self.assertRaises(Exception):\n seq_set.sequence_type = ['a', 'b', 'c']\n\n # Test dict argument\n with self.assertRaises(Exception):\n seq_set.sequence_type = {'a': 1, 'b': 2}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
output file name for the given neutron component in the output directory of the job directory This has to be unique so that different components don't write to the same output file.
def outputfilename(component): f = '%s-%s.out' % (component.__class__.__name__, component.componentname) return f
[ "def name_file(self, output_filename):\n return self.output_path / output_filename", "def _make_output_file_path_unique(self, run_name: str, op_name: str,\n output_file: str) -> str:\n if not output_file.startswith(\"/tmp/\"):\n return output_file\n return f'{self._pipeline_root}/{run_name}/{op_name.lower()}/{output_file[len(\"/tmp/\"):]}'", "def get_file_name(self, output_dir, model_name):\n file_name = \"%sGroup%s_Seg%s_%s.dat\" % (model_name, self.group, self.segment, self.data_name)\n return os.path.join(output_dir, file_name)", "def _get_output_file_name(self):\n datetime_suffix = datetime.now().strftime('%Y%m%d_%H%M%S')\n\n # Only select the non-empty strings from the file name parts\n output_file_name = '_'.join([a for a in\n [self.output_file_name_prefix, self.output_file_name,\n self.output_file_name_suffix, datetime_suffix] if a\n ])\n\n return f\"{output_file_name}{self._get_output_file_extension()}\"", "def GetOutputFilename(self, fname):\n return os.path.join(self.outdir, fname)", "def _write_component(component_spec: ComponentSpec, output_path: str):\n component_spec.save(output_path)", "def create_pathname(self, output_path):\n self.generate_name()\n\n return os.path.join(output_path, self.name)", "def get_output_basename(self):\n cumf_base_name = self.options[\"full_task_name\"]\n cumf_base_name = re.sub(r\"[() ]\", r\"_\", cumf_base_name)\n if cumf_base_name.endswith(\"_\"):\n cumf_base_name = cumf_base_name[:-1]\n return \"ana.\" + cumf_base_name", "def get_rotated_out_filename(self):\n\n basename = self._output_file\n if self._has_rotated_stdout_err_files:\n basename += \".%03d\" % (self._job_output_counter)\n\n return basename", "def get_output_name(self):\n return self.current_item[\"name\"] + \"Output\"", "def name_the_output_file(data):\n\n # Parse the input data as a URL\n parsed_data = urllib.parse.urlparse(data)\n\n # Use the path component of the URL\n path = parsed_data.path if parsed_data.path else data\n\n # Use the basename of the path as the output file name\n output = os.path.basename(path)\n\n # Set a default file name if the output is empty\n if not output:\n output = \"output\"\n\n return output", "def _get_output_file(self, type_):\n name = self._opts[type_]\n if name == 'NONE' and type_ in self._optional_outputs:\n return name\n name = self._process_output_name(name, type_)\n path = utils.normpath(os.path.join(self['OutputDir'], name), False)\n self._create_output_dir(os.path.dirname(path), type_)\n return path", "def create_outfile_name(bamfile, outroot):\n (bamsample, condition) = clip_bamfile_name(bamfile)\n outtable = bamsample + \".\" + condition + \".\" + \"FRiP_table.txt\"\n if outroot != \"\":\n outtable = outroot + \".\" + outtable\n return(outtable)", "def _define_merged_file_name(self, output_folder='', run_label='', position_label=''):\n return os.path.join(output_folder, \"{}_{}.tiff\".format(run_label, position_label))", "def output_components(output_dir):\n if output_dir is None:\n return\n\n component = 0\n paths_by_start = {}\n for path in Read.known_paths:\n if path[0] not in paths_by_start:\n paths_by_start[path[0]] = []\n paths_by_start[path[0]].append(path)\n\n with open(output_dir + '/single_nodes.txt', 'w', 0) as single_file:\n single_file.write(\"ID\\tBases\\tCopycount\\tNormalization\\n\")\n\n for source_node in Node.nodes:\n if hasattr(source_node, 'destroyed'):\n continue\n with open(output_dir + '/nodes'+str(component)+'.txt', 'w', 0) as nodefile, \\\n open(output_dir + '/edges'+str(component)+'.txt', 'w', 0) as edgefile, \\\n open(output_dir + '/paths'+str(component)+'.txt', 'w', 0) as pathfile:\n component_nodes, component_edges = source_node.add_component()\n component_nodes = Node.topological_sort(component_nodes)\n\n if len(component_nodes) == 1:\n source_node.hash = -1\n single_file.write(source_node.to_string())\n source_node.destroyed = True\n continue\n\n node_hash = 0\n nodefile.write(\"ID\\tBases\\tCopycount\\tNormalization\\n\")\n pathfile.write(\"ID1\\tID2\\tEtc.\\n\")\n for node in component_nodes:\n node.hash = node_hash\n node_hash += 1\n nodefile.write(node.to_string())\n node.destroyed = True\n\n for node in component_nodes:\n if node not in paths_by_start: continue\n paths = paths_by_start[node]\n for path in paths_by_start[node]:\n path = [str(n.hash) for n in path]\n pathfile.write(\"\\t\".join(path) + \"\\n\")\n\n edgefile.write(\"InID\\tOutID\\tWeight\\tCopycount\\tNormalization\\n\")\n for edge in component_edges:\n #np = tuple([edge.in_node,edge.out_node]) #node-pair\n if edge.copy_count > 0: #either the edge has a copy count or edge weight >= Read.K\n #edge.copy_count = max(Read.known_edges.get(np,0),1)/max(Read.L - edge.weight - 1, 1)\n edgefile.write(edge.to_string())\n component += 1", "def generate_output_workspace_name(self, event_file_name):\n out_ws_name = os.path.basename(event_file_name).split(\n '.')[0] + '_{0}banks'.format(self._number_banks)\n ref_id = out_ws_name\n\n return out_ws_name, ref_id", "def _get_clean_name(self, output_folder, extension=\"dcm\"):\n if output_folder is None:\n output_folder = self.output_folder\n\n if not os.path.exists(output_folder):\n bot.debug(\"Creating output folder %s\" % output_folder)\n os.makedirs(output_folder)\n\n basename = re.sub(\"[.]dicom|[.]dcm\", \"\", os.path.basename(self.dicom_file))\n return \"%s/cleaned-%s.%s\" % (output_folder, basename, extension)", "def output_file(self):\n\n return self._outfile", "def generate_output_file(final_model,out_name):\n\n\tout_name = str(out_name.strip())\n\t# If the output file is too big, we save it in \".mmcif\" format\n\tif len(list(final_model[0].get_atoms())) > 99999 or len(list(final_model[0].get_chains())) > 62:\n\t\tmmcif_IO = MMCIFIO()\n\t\tmmcif_IO.set_structure(final_model[0])\n\t\tmmcif_IO.save(out_name + \".cif\")\n\t# Otherwise, save it \".pdb\" format\n\telse:\n\t\tpdb_IO = PDBIO()\n\t\tpdb_IO.set_structure(final_model[0])\n\t\tpdb_IO.save(out_name + \".pdb\")" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
>>> get_relative_change(10, 0) 999.0 >>> get_relative_change(10, 1) 9.0 >>> get_relative_change(10, 5) 1.0 >>> get_relative_change(10, 10) 0.0 >>> get_relative_change(10, 15) 0.5 >>> get_relative_change(10, 20) 1.0 >>> get_relative_change(10, 100) 9.0 >>> get_relative_change(0, 10) 999.0 >>> get_relative_change(0, 0) 0.0
def get_relative_change(val1, val2): assert val1 >= 0, val1 assert val2 >= 0, val2 if val1 == 0: val1 = EPSILON if val2 == 0: val2 = EPSILON if val1 > val2: return 1 - val1 / float(val2) return val2 / float(val1) - 1
[ "def getRelativeFieldChange(self):\n\t\treturn self.relative_field_change", "def pct_change():\n original_value = bank_of_rick.original_value\n current_total_value = sum(total_value())\n return 100 * (current_total_value - original_value) / original_value", "def fracChange(new, control, deltaT):\n return ((new - control)/control)*100/deltaT", "def _calculate_change_rate(self, known_value, forecasted_value):\n logger.debug(\n repr(self) + 'If last known value is 0, substitute it to 1')\n known_value = 1 if known_value == 0 else known_value\n logger.debug(\n str(self) + 'Forecasted value {}'.format(forecasted_value))\n logger.debug(str(self) + 'Last known value {}'.format(known_value))\n difference = forecasted_value - known_value\n result = float((difference) * constants.CONVERT_PERCENT / known_value)\n logger.debug(\n repr(self) + 'Percentage rate of change {}'.format(result))\n return result", "def change(self):\n return numpy.abs(self.initial - self.result)", "def __relative_diff(v1, v2):\n s1 = \"\"\n s2 = \"\"\n for c in str(v1):\n if c in \"0123456789.,\":\n s1 += c\n else:\n break\n for c in str(v2):\n if c in \"0123456789.,\":\n s2 += c\n else:\n break\n\n try:\n value = 1 - abs(float(s1) - float(s2))/float(s1)\n except (TypeError, ValueError) as e:\n # print(e)\n value = 0\n return value", "def getChange(self):\n newValue = self.getValue()\n change = newValue - self._lastValue\n self._lastValue = newValue\n return change", "def cal_relative(process_setting, log_array, log_object, log_file, procedure_length):\n cylinder_name = process_setting['FIRING_CYLINDER_NAME']\n temperature_name = process_setting['TEMPERATURE_NAME']\n cylinder_num = len(cylinder_name)\n fixed_step = process_setting['TEMPERATURE_STEP']\n node_result = process_setting['NODE_RESULT']\n start_record_value = process_setting['START_LOG_VALUE']\n i = 0\n threshold = 0\n for key, value in node_result.items(): # type: model.ChgNodes\n value.cal_relative(fixed_step, cylinder_num, temperature_name)\n current_process = int(i * 100 / len(node_result))\n if current_process >= threshold:\n threshold += 10\n log_array.append(['Relative Motion Finished ' + str('%3.1f%%' % current_process),\n start_record_value + current_process * float(procedure_length) / 100])\n log_object.add_record(log_array[-1], log_file)\n return process_setting", "def get_change(amount, coins=eur_coins):\n change = []\n \n # Unlike a list, looping through a dictionary does not keep the order.\n # Therefore we use `sorted()` to sort the order. This will sstart with the\n # lowest by default, so we use `reverse=True` to start with the highest\n # denomination. The `while` ends when the domination quantity reaches 0.\n # An exception is thrown if there are insufficient coins to give change.\n \n for denomination in sorted(coins.keys(), reverse=True):\n while denomination <= amount and coins[denomination] > 0:\n amount -= denomination\n coins[denomination] -= 1\n change.append(denomination)\n \n if amount != 0:\n raise Exception(\"Insufficient coins to give change.\")\n\n return change\n\n\n\n#def get_change(amount, coins=eur_coins): # by providing the = it means the second argument is optional (so you can leave it empty)\n \"\"\"\n as code in general enough we can remove if statements\n \n if amount == 0:\n return []\n \n if amount in coins:\n return [amount]\n \n \n change = []\n for coin in coins:\n while coin <= amount: # change from if to while so only when coin is less than or equal to amount it carrys on adding\n amount -= coin\n change.append(coin)\n\n return change\n \"\"\"", "def discontinuite_relative(values, feature, parent):\n return max(float(values[0]),float(values[1]))/min(float(values[0]),float(values[1]))", "def get_relative_growth(country):\n\n\n # Implementation...\n # ...\n # ...\n # ...", "def expected_change(self):\n return numpy.abs(self.expected - self.initial)", "def calculate_change(total, received, denoms):\n change = received - total\n return _calculate_denoms(change, denoms)", "def compute_change(self, change_value):\n if change_value > self.value:\n raise NoChangePossibleException(\"Not enough money in stock\")\n coins_out = Coins()\n for key in sorted(list(self.keys()), reverse=True):\n coins_out[key] = min(change_value // key, self[key])\n change_value -= coins_out[key]*key\n if change_value == 0:\n break\n if change_value != 0:\n raise NoChangePossibleException(\"Cannot give change for this amount\")\n return coins_out", "def getCumulativeDifference(element):\n return element.cumulativeDifference", "def prev(x: float, delta: int=1) -> float:\n return bits_float(float_bits(x) - delta)", "def get_change(amount, coins=eur_wallet):\n change = []\n for coin in coins:\n while coin <= amount:\n amount -= coin\n change.append(coin)\n\n return change", "def getRelativeScore(self):\n minimum = self.getMinimumScore()\n current = self.getScore()\n # check how many times current score fits into min. score\n return current[1] / minimum", "def z_relative_move(self, delta):\n try:\n zStart = self.get_focus_pos()\n zEndCalc = zStart + delta\n self.move_focus_to(zEndCalc)\n z = self.get_focus_pos()\n except Exception:\n raise HardwareError(\n \"Error in Relative movement of focus in the z direction (connect_zen_black.py).\" # noqa\n )\n return z" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function creates an ray transfer matrix for d distance
def distance(d): arr01 = array([ [1, d], [0, 1] ], float) print("The ray transfer matrix for your setup at d distance is", ) print(arr01)
[ "def reconstruction_d_matrix(self):\n\n d_matrix = np.zeros_like(self.d_matrix)\n for n_step in np.arange(self.nsteps):\n transfer_matrix = self.transfer_matrix_from_simframe(os.path.abspath(os.path.join(os.getcwd(),\n 'quad_scan_setup_' +\n str(n_step))))\n np.savetxt(os.path.abspath(os.path.join(os.getcwd(), 'quad_scan_setup_' + str(n_step),\n \"transfer_matrix_rec_obs_VM.txt\")), transfer_matrix)\n self.calculation_d_matrix_step(transfer_matrix)\n for k in np.arange(self.d_matrix_step.shape[1]):\n d_matrix[(3 * n_step), k] = deepcopy(self.d_matrix_step[0, k])\n d_matrix[(3 * n_step) + 1, k] = deepcopy(self.d_matrix_step[1, k])\n d_matrix[(3 * n_step) + 2, k] = deepcopy(self.d_matrix_step[2, k])\n setattr(self, 'd_matrix', d_matrix)", "def _get_distance_matrix(self):\n\n # implement here", "def distmatrix(self):\n import numpy as np\n\n self.nodexnormal, self.nodeynormal = sf.FeatureScaling(self.nodex), sf.FeatureScaling(self.nodey)\n \n self.dmatrix = np.empty((self.nodenum, self.nodenum), dtype = float)\n self.dnormalmatrix = np.empty((self.nodenum, self.nodenum), dtype = float)\n \n for i in range(self.nodenum):\n for j in range(i, self.nodenum):\n self.dmatrix[i, j] = sf.dist(self.nodey[i], self.nodex[i], self.nodey[j], self.nodex[j])\n self.dmatrix[j, i] = self.dmatrix[i, j]\n \n self.dnormalmatrix[i, j] = sf.dist(self.nodeynormal[i], self.nodexnormal[i], self.nodeynormal[j], self.nodexnormal[j])\n self.dnormalmatrix[j, i] = self.dnormalmatrix[i, j]", "def GW_matrix(exp,a,atoms_name):\n n= exp[a].shape[0]\n if atoms_name =='Cs':\n learnt_mat = [gwu.np_sum_scaled_mat(exp['Cs'], exp[a][t]) for t in range(exp[a].shape[0]) ]\n else:\n learnt_mat = [gwu.np_sum_scaled_mat(exp['checkpoint_Cs'], exp[a][t]) for t in range(exp[a].shape[0]) ]\n\n D = np.zeros((n,n), dtype=np.float64)\n\n for i in tqdm(range(n-1)):\n for j in range (i+1, n):\n \n dist,T= gwu.np_GW2(learnt_mat[i],learnt_mat[j])\n D[i,j]= dist\n D[j,i]= dist\n return D", "def getDistanceMatrix(self):\n\t\tnatoms=self.atoms\n\t\tdist = [[0.0 for i in range(natoms)] for j in range(natoms)]\n\t\tfor i in range(0,natoms):\n\t\t #dist[i][i]=0.0 #diagonal elements are zero\n\t\t for j in range(i+1, natoms):\n\t\t\ticoord=self.coordDict[i+1]\n\t\t\tjcoord=self.coordDict[j+1]\n\t\t\txdiff=icoord[0]-jcoord[0]\n\t\t\tydiff=icoord[1]-jcoord[1]\n\t\t\tzdiff=icoord[2]-jcoord[2]\n\t\t\tdist[i][j]=math.sqrt(xdiff*xdiff+ydiff*ydiff+zdiff*zdiff)\n\t\t\tdist[j][i]=dist[i][j] #matrix is symmetric\n\n\t\treturn dist", "def ltriag_matrix(params: np.ndarray, d: int):\n T = np.zeros((d, d), dtype=complex)\n T[np.tril_indices(d)] += params[:((d * d + d) // 2)]\n T[np.tril_indices(d, -1)] += 1j * params[((d * d + d) // 2):]\n return qtp.Qobj(T)", "def dist_matrix(data_coords_atom):\n \treturn pd.DataFrame(distance_matrix(data_coords_atom.iloc[:,3:],\n \t\tdata_coords_atom.iloc[:,3:]), index = data_coords_atom.iloc[:, 3:].index,\n \tcolumns = data_coords_atom.iloc[:, 3:].index)", "def refflatmirror():\n arr05 = array([\n [1, 0],\n [0, 1]\n ], float)\n print(\"The ray transfer matrix for reflaction in a flat interface is \")\n print(arr05)", "def Distmatrix(self):\n self.distmatrix = np.zeros((self.nodenum1, self.linknum2), dtype = float)\n \n for i in range(self.nodenum1):\n for j in range(self.linknum2):\n self.distmatrix[i, j] = sf.dist(self.network1.y[self.network1.demandseries[i]], self.network1.x[self.network1.demandseries[i]], \\\n self.network2.edgelist[j][\"middley\"], self.network2.edgelist[j][\"middlex\"])", "def distances(self):\n sequence_count = self.sequence_count()\n dm = np.zeros((sequence_count, sequence_count))\n identifiers = []\n for i in xrange(sequence_count):\n self_i = self[i]\n identifiers.append(self_i.identifier)\n for j in xrange(i):\n dm[i, j] = dm[j, i] = self_i.distance(self[j])\n return DistanceMatrix(dm, identifiers)", "def get_distance_matrix(X, metric):\n ray.init(ignore_reinit_error=True)\n T = timer()\n n_samples = len(X)\n \n nC2 = 0.5*(n_samples*(n_samples-1))\n iu = np.triu_indices(n_samples,1)\n row_ids = np.unique(iu[0])\n \n iu_ray = ray.put(iu)\n X_ray = ray.put(X)\n metric_ray = ray.put(metric)\n \n remaining_result_ids = [_get_distance_row.remote(X_ray, metric_ray, rowid, iu_ray) for rowid in row_ids]\n \n dist = {}\n while len(remaining_result_ids) > 0:\n ready_result_ids, remaining_result_ids = ray.wait(remaining_result_ids, num_returns=1)\n result_id = ready_result_ids[0]\n dist_result,rowid_result, time_result = ray.get(result_id)\n dist[rowid_result] = dist_result\n print('Processed : {} took {} '.format(rowid_result, time_result)) \n \n del remaining_result_ids,result_id, iu_ray, metric_ray, X_ray, dist_result,rowid_result, time_result \n \n reduce_dist = [dist[k] for k in sorted(dist)]\n dist = np.hstack(reduce_dist)\n\n assert nC2==len(dist), \"Not all the reduced distances are returned. expected {} got {}\".format(nC2, len(dist))\n \n D = squareform(dist)\n \n assert n_samples==np.shape(D)[0] , \"Shape of distance matrix is {}, expected {}x{}\".format(D.shape, n_samples, n_samples)\n \n print('\\nComputation took : {}'.format(T.end()))\n\n return D", "def _dist_matrix(self, x, y):\n dm = dtw_distance(x, y, self.window, self.normalize)\n\n return dm", "def distseedmatrix(self):\n self.seedindex = []\n while(len(self.seedindex) < self.seednum):\n temp = np.random.randint(0, self.nodenum)\n if(temp in self.seedindex):\n continue\n else:\n self.seedindex.append(temp)\n \n self.dseedmatrix = np.empty((self.seednum, self.seednum), dtype = float)\n\n for i in range(self.seednum):\n for j in range(self.seednum):\n self.dseedmatrix[i, j] = self.dmatrix[self.seedindex[i], self.seedindex[j]]\n self.dseedmatrix[j, i] = self.dseedmatrix[i, j]", "def test_flow__distance_regular_grid_d4():\n\n # instantiate a model grid\n\n mg = RasterModelGrid((5, 4), xy_spacing=(1, 1))\n\n # instantiate an elevation array\n\n z = np.array(\n [[0, 0, 0, 0], [0, 21, 10, 0], [0, 31, 20, 0], [0, 32, 30, 0], [0, 0, 0, 0]],\n dtype=\"float64\",\n )\n\n # add the elevation field to the grid\n\n mg.add_field(\"topographic__elevation\", z, at=\"node\")\n\n # instantiate the expected flow__distance array\n # considering flow directions calculated with D4 algorithm\n\n flow__distance_expected = np.array(\n [[0, 0, 0, 0], [0, 1, 0, 0], [0, 2, 1, 0], [0, 3, 2, 0], [0, 0, 0, 0]],\n dtype=\"float64\",\n )\n flow__distance_expected = np.reshape(\n flow__distance_expected, mg.number_of_node_rows * mg.number_of_node_columns\n )\n\n # setting boundary conditions\n\n mg.set_closed_boundaries_at_grid_edges(\n bottom_is_closed=True,\n left_is_closed=True,\n right_is_closed=True,\n top_is_closed=True,\n )\n\n # calculating flow directions with FlowAccumulator component\n\n fr = FlowAccumulator(mg, flow_director=\"D4\")\n fr.run_one_step()\n\n # calculating flow distance map\n\n flow__distance = calculate_flow__distance(mg, add_to_grid=True, clobber=True)\n flow__distance = np.reshape(\n flow__distance, mg.number_of_node_rows * mg.number_of_node_columns\n )\n\n # test that the flow__distance utility works as expected\n\n assert_array_equal(flow__distance_expected, flow__distance)", "def matdist(self):\r\n self.latlong() \r\n self.coord = []\r\n self.mat = np.zeros((self.n,self.n))\r\n for i in range(self.n):\r\n self.coord.append((self.x[i],self.y[i]))\r\n for j in range(i+1,self.n):\r\n la = (self.x[i]-self.x[j])**2\r\n lon = (self.y[i]-self.y[j])**2\r\n self.mat[i,j] = (la + lon)**0.5\r\n self.mat[j,i] = self.mat[i,j]\r\n return self.mat,self.coord", "def _init_distance_vector(self):\r\n for router in [self.sourceRouter]+list(self.neighbours.keys()):\r\n self.routingTable[router] = {}\r\n self.routingTable[router][router] = {}\r\n self.routingTable[router][router]['distance'] = 0\r\n self.routingTable[router][router]['nextHopRouter'] = router\r\n\r\n for neighbourRouter, routerAddress in self.neighbours.items():\r\n sourceDV = self.routingTable[self.sourceRouter]\r\n neighbourDV = self.routingTable[neighbourRouter]\r\n\r\n sourceDV[neighbourRouter] = {}\r\n sourceDV[neighbourRouter]['distance'] = routerAddress['link_cost']\r\n sourceDV[neighbourRouter]['nextHopRouter'] = neighbourRouter\r\n\r\n neighbourDV[self.sourceRouter] = {}\r\n neighbourDV[self.sourceRouter]['distance'] = routerAddress['link_cost']\r\n neighbourDV[self.sourceRouter]['nextHopRouter'] = self.sourceRouter", "def _distance_matrix(self):\n def dist(ii, jj):\n \"\"\"\n Calculates a distance between two points at indices ii and jj in\n the xy data matrix.\n ARGS:\n ii, jj (int): Indices\n \"\"\"\n return (sqrt((self.xy[0][ii] - self.xy[0][jj]) ** 2 + (self.xy[1][ii] - self.xy[1][jj]) ** 2))\n return np.array([np.array([dist(ii, jj) for jj in range(len(self.xy[0]))]) for ii in range(len(self.xy[0]))])", "def delaunay_to_tri(d):\n return tri.Triangulation(x=d.x,y=d.y,triangles=d.triangle_nodes)", "def distance_matrix_calculate(self):\n qtd = self.mapa.shape[0]\n distancias = np.zeros([qtd, qtd])\n\n _temp_max = 0\n\n for i in range(qtd):\n for j in range(i, qtd):\n if i != j:\n b = self.mapa[i, 0] - self.mapa[j, 0]\n c = self.mapa[i, 1] - self.mapa[j, 1]\n a = np.sqrt(np.square(b) + np.square(c))\n\n distancias[i, j] = a\n distancias[j, i] = a\n\n if _temp_max < a:\n _temp_max = a\n\n self.distancias = distancias" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function creates an ray transfer matrix for a lens with f focal length
def thinlens(f): arr02 = array([ [1, 0], [-1/f, 1] ]) print("The ray transfer matrix for your thin lens of focal lenth f is", ) print(arr02)
[ "def refflatmirror():\n arr05 = array([\n [1, 0],\n [0, 1]\n ], float)\n print(\"The ray transfer matrix for reflaction in a flat interface is \")\n print(arr05)", "def traject(origin0,tetaOrigin0):\r\n\r\n #cf to \"Analytic ray curve tracing for outdoor sound propagation\"\r\n #to understand what follows in this function\r\n #the formulation of the ray traject in the article is true for\r\n #the local orthonormal coordinates (r,h) were h is the axis directed\r\n #by the direction of the gradient.\r\n \r\n x0,z0=origin0\r\n \r\n alpha=norm(x0,z0)\r\n Vorigin0=fV(x0,z0) \r\n correction=gradOrientation(z0)#the local coordinates are oriented according\r\n #to the direction of the gradient of V^-2\r\n #if it is the opposite of the z axis then we will need to inverse the local\r\n #polynome\r\n teta=correction*tetaOrigin0#because changing the coordinates we inverted\r\n #the vertical axis orientation and so we also change angles orientation\r\n\r\n changeSign=np.sign(teta)#to correct a mistake in the\r\n #formula of rf (sign of teta matters for the vertex position)\r\n #In case where teta=0 it does not matter because rf is equal to 0\r\n\r\n\r\n #Now we calculated the local traject with the poly1d class\r\n #to do this I calculated the coefficient a,b,c of the polynom under this form:\r\n #ar^2+br+c\r\n #it appears that c=0 (the polynome pass throught the origin of the local coordinates)\r\n #I developped rf and epsilon to simplify the expression\r\n a=alpha/(4*(np.cos(teta)/Vorigin0)**2)\r\n b=changeSign*(1/np.cos(teta)**2-1)**(1/2)\r\n #In local coordinate it gives\r\n #h=correction*np.poly1d([a,b,0])\r\n #let's define a polynome for global coordinates\r\n #the polynome is Z(r)=h(r-x0)+z0 and by manual calculating we obtain:\r\n Z=correction*np.poly1d([a,b-2*a*x0,correction*z0-b*x0+a*x0**2])\r\n return (Z)", "def refracurvemirror(Re):\n arr06 = array([\n [1, 0],\n [-2/Re, 1]\n ], float)\n print(\"The ray transfer matrix for refraction at a curved mirror is \")\n print(arr06)", "def ray_trace_full_set_jones(tstep=5, runtime=24, m0=(2*np.pi)/250, plots=True):\n ladcp, ctd, bathy = data_load.load_data()\n U, V, z_grid = oc.loadLADCP(ladcp)\n S, T, p, lat, lon = oc.loadCTD(ctd)\n N2 = oc.gswN2(S, T, p, lat, lon)\n for i, cast in enumerate(N2.T):\n N2[:,i] = oc.verticalBoxFilter1(cast, p[:,i])\n # Load Data\n lambdaH = pd.read_excel('lambdaH.xlsx')\n kh = pd.read_excel('Kh_masked.xlsx')\n omega = pd.read_excel('omega_masked.xlsx')\n # Depth grid stored as index in pandas dataframes\n depths = np.array(omega.index)\n X = pd.DataFrame(index=depths, columns=np.arange(0,21))\n Z = pd.DataFrame(index=depths, columns=np.arange(0,21))\n OM = pd.DataFrame(index=depths, columns=np.arange(0,21))\n m = pd.DataFrame(index=depths, columns=np.arange(0,21))\n# time = np.arange(0, runtime, tstep)\n x_all = []\n z_all = []\n Om_all = []\n starts = []\n count=0\n for i in range(kh.shape[1]):\n \n \n for k in range(kh.shape[0]):\n depth = depths[k]\n if np.isfinite(kh.loc[depth][i]) and np.isfinite(omega.loc[depth][i]):\n X.loc[depth][i], Z.loc[depth][i],\\\n OM.loc[depth][i], m.loc[depth][i]\\\n = ray_trace_jones_top_down(U[:,i], V[:,i], z_grid,\\\n N2[:,i], p[:,i], kh.loc[depth][i],\\\n m0, depth, omega.loc[depth][i], lat[:,i],\\\n tstep=tstep, runtime=runtime)\n starts.append([i+1, depth])\n x_all.append(X.loc[depth][i])\n z_all.append(Z.loc[depth][i])\n Om_all.append(OM.loc[depth][i])\n \n else:\n X.loc[depth][i] = np.nan\n OM.loc[depth][i] = np.nan\n Z.loc[depth][i] = np.nan\n m.loc[depth][i] = np.nan\n count +=1\n print(count)\n \n \n x_all = np.vstack(x_all)\n z_all = np.vstack(z_all)\n Om_all = np.vstack(Om_all)\n starts = np.vstack(starts)\n \n np.savetxt('x_ray_trace.csv', x_all)\n np.savetxt('z_ray_trace.csv', z_all)\n np.savetxt('Om_ray_trace.csv', Om_all)\n np.savetxt('starts_ray_trace.csv', starts)\n \n \n \n \n # Plotting Data\n if plots:\n fig = plt.figure()\n for i in range(kh.shape[1]):\n for k in range(kh.shape[0]):\n depth = depths[k]\n idx = i\n plt.plot(X.loc[depth][idx],Z.loc[depth][idx])\n plt.xlabel('Horizontal Distance (km)')\n plt.ylabel('depth (m)')\n plt.gca().invert_yaxis()\n \n \n fig = plt.figure()\n for i in range(kh.shape[1]):\n for k in range(kh.shape[0]):\n depth = depths[k]\n idx = i\n plt.plot(X.loc[depth][idx],m.loc[depth][idx]/(2*np.pi))\n plt.xlabel('Horizontal Distance (km)')\n plt.ylabel('vertical wavenumber')\n \n \n fig = plt.figure()\n for i in range(kh.shape[1]):\n for k in range(kh.shape[0]):\n depth = depths[k]\n idx = i\n plt.plot(X.loc[depth][idx],OM.loc[depth][idx])\n plt.xlabel('Horizontal Distance (km)')\n plt.ylabel('frequency ')\n \n \n \n \n \n return x_all, z_all, Om_all, starts", "def projectionMatrix(n,f,fov,ar):\n\n n = float(n)\n f = float(f)\n\n fov = float(fov)\n ar = float(ar)\n print 'ar', ar\n\n #r = 0.5 * w\n #t = 0.5 * h\n #perspective, w-h\n #return np.asarray([\n # [n/r,0,0,0],\n # [0,n/t,0,0],\n # [0,0,(f+n)/(f-n),-2*f*n/(f-n)],\n # [0,0,1,0]\n # ])\n #orthographic\n# return np.asarray([\n# [1./r,0,0,0],\n# [0,1./t,0,0],\n# [0,0,-2./(f-n),-(f+n)/(f-n)],\n# [0,0,0,1]\n# ])\n #perspective, fov-aspect\n #tan(fov/2) = (1/2)*w / n\n #1 / tan(fov/2) = 2n / w\n return np.asarray([\n [1/(ar*np.tan(fov/2)), 0, 0, 0],\n [0, 1/np.tan(fov/2), 0, 0],\n [0, 0, (f+n)/(f-n), -2*f*n/(f-n)],\n [0, 0, 1, 0]\n ])", "def facial_landmarks_torch(alpha, delta, w, t):\n landmarks_idx = np.loadtxt(\"Landmarks68_model2017-1_face12_nomouth.anl\", dtype=int)\n\n pca = read_pca_model()\n G = get_face_point_cloud_torch(pca, alpha, delta)[landmarks_idx].t()\n G_h = [G , torch.ones(G.shape[1]).view((1, -1))]\n G_h = torch.cat(G_h, dim=0)\n \n # get T matrix\n T = torch.eye(4)\n T[:3, :3] = rotation_matrix(w)#rotation_tensor(w, 1)#get_rotation_matrix_torch(w) #torch.tensor([[1, 0, 0], [0, 1, 0], [0, 0, 1]])#\n T[:3, 3] = t\n \n # Get V and P matrices\n W = 172\n H = 162\n\n image_aspect_ratio = W / H\n angle = 10\n near = .1\n far = 10\n\n right, left, top, bottom = get_perspective(image_aspect_ratio, angle, near, far)\n \n V = get_V(right, left, top, bottom)\n\n \n [V] = list(map(torch.from_numpy, [V]))\n V = V.to(dtype = torch.float32)\n n,f, t, b = near, far, top, bottom\n P = torch.Tensor([[(2 * n) / (t-b), 0, 0, 0],\n [0, (2 * n) / (t - b), 0, 0],\n [0, 0, -(f + n) / (f - n), -(2 * f * n) / (f - n)],\n [0, 0, -1, 0]])\n i = V @ P @ T @ G_h\n\n # homo to cartesian\n i = i/i[3,:].clone()\n\n # two-dimensional\n return i[:2, :].t()", "def build_F_matrix(self, svars, time, params):\n\n F = np.zeros((4, 4))\n\n year_time = (time*self.time_step) % self.year_length\n lower = year_time - self.time_step\n repro_ind = ((params['repro_time'] > lower) &\n (params['repro_time'] <= year_time))\n if repro_ind:\n F[0, :] = np.array([0,\n params['r'],\n params['r'],\n 0])\n\n return(F)", "def refraflat(n1 ,n2):\n arr03 = array([\n [1, 0],\n [0, n1/n2]\n ], float)\n print(\"The ray transfer matrix for refraction in a flat interface is \")\n print(arr03)", "def camera_1d(plan: np.array, center: (float, float), direction: float, view_angle: float, resolution: int, condition):\n scan = []\n for i in range(resolution):\n # display = True if any([i == 0, i == int(resolution/2), i == resolution - 1]) else False\n display = True\n ray_i_angle = direction - view_angle * (i / resolution - 0.5)\n scan.append(cast_ray(plan, center, ray_i_angle, condition, display))\n return np.array(scan)", "def createRays(pts, K_inv):\n # We simply need to multiply per K_inv, this way we get a 3D direction.\n # We can get the points of the ray multiplying the direction with a scalar.\n return [np.matmul(K_inv, p) for p in pts]", "def fir_design_matrix(events, len_hrf):\n event_types = np.unique(events)[np.unique(events) != 0]\n fir_matrix = np.zeros((events.shape[0], len_hrf * event_types.shape[0]))\n\n for t in event_types:\n idx_h_a = (np.array(np.where(event_types == t)[0]) * len_hrf)[0]\n idx_h_b = idx_h_a + len_hrf\n idx_v = np.where(events == t)[0]\n for idx_v_a in idx_v:\n idx_v_b = idx_v_a + len_hrf\n fir_matrix[idx_v_a:idx_v_b, idx_h_a:idx_h_b] += (np.eye(len_hrf) *\n np.sign(t))\n\n return fir_matrix", "def assemble_face_matrix(self, edges):\n n_edges = len(edges)\n n_nodes = self.mesh.n_nodes()\n mat = lil_matrix((n_edges, n_nodes))\n for edge_i, node_idx in enumerate(edges):\n mat[edge_i, node_idx] = 0.5\n return mat", "def rotate(state): \n size = state.shape # (100, 20, 11) \n last_dim = len(size) - 1 # 3\n dx = state[..., 4] - state[..., 0] # (100, 20)\n dy = state[..., 5] - state[..., 1]\n rot = torch.atan2(dy, dx) # (100, 20)\n\n dg = torch.norm(torch.cat([dx.unsqueeze(dim = last_dim), dy.unsqueeze(dim = last_dim)], dim=last_dim), 2, dim=last_dim, keepdim=True) # (100, 20, 1)\n vx = (state[..., 2] * torch.cos(rot) + state[..., 3] * torch.sin(rot)).unsqueeze(dim = last_dim) # (100, 20, 1)\n vy = (state[..., 3] * torch.cos(rot) - state[..., 2] * torch.sin(rot)).unsqueeze(dim = last_dim)\n \n vx1 = (state[..., 8] * torch.cos(rot) + state[..., 9] * torch.sin(rot)).unsqueeze(dim = last_dim) # (100, 20, 1)\n vy1 = (state[..., 9] * torch.cos(rot) - state[..., 8] * torch.sin(rot)).unsqueeze(dim = last_dim)\n\n px1 = (state[..., 6] - state[..., 0]) * torch.cos(rot) + (state[..., 7] - state[..., 1]) * torch.sin(rot) # (100, 20)\n px1 = px1.unsqueeze(dim = last_dim) # (100, 20, 1)\n\n py1 = (state[..., 7] - state[..., 1]) * torch.cos(rot) - (state[..., 6] - state[..., 0]) * torch.sin(rot)\n py1 = py1.unsqueeze(dim = last_dim)\n # radius1 = state[..., 10].unsqueeze(dim = last_dim)\n\n da = torch.norm(torch.cat([(state[..., 0] - state[..., 6]).unsqueeze(dim = last_dim), (state[..., 1] - state[..., 7]).\n unsqueeze(dim = last_dim)], dim=last_dim), 2, dim=last_dim, keepdim=True) # (100, 20, 1)\n new_state = torch.cat([dg, vx, vy, px1, py1, vx1, vy1, da], dim=last_dim)\n # new_state = torch.cat([dg, vx, vy, px1, py1, vx1, vy1, radius1, da], dim=last_dim)\n return new_state, rot[...,0] # (100, 20, 9) ", "def _celestial(self):\n cos = np.cos(self.lat)\n sin = np.sin(self.lat)\n transfo = np.matrix([ \n [0, -sin, cos],\n [1, 0, 0],\n [0, cos, sin]\n ])\n return transfo", "def create_rectified_fundamental_matrix(batch_size: int) -> Tensor:\n F_rect = tensor([[0.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]]).view(1, 3, 3)\n F_repeat = F_rect.expand(batch_size, 3, 3)\n return F_repeat", "def get_tilt_correction(morphology: Morphology,\n soma_voxel: List[int],\n slice_angle_matrix: float,\n closest_path,\n ):\n\n # Find slice plane vector\n M = slice_angle_matrix[0:3, :]\n o_ccf = np.dot(M, np.array([0, 0, 0, 1])) # slice plane origin in ccf\n x_ccf = np.dot(M, np.array([1, 0, 0, 1])) # slice plane x vector in ccf\n y_ccf = np.dot(M, np.array([0, 1, 0, 1])) # slice plane y vector in ccf\n\n norm_vec = np.cross(x_ccf - o_ccf, y_ccf - o_ccf) # z vector normal to slice plane\n norm_unit = norm_vec / euclidean(norm_vec, [0, 0, 0])\n\n # Find approximate streamline vector\n if euclidean(closest_path[:, 0], soma_voxel) == 0:\n # if soma is at the top, calculate from other end of streamline\n streamline_unit = (soma_voxel - closest_path[:, -1]) /\\\n euclidean(soma_voxel, closest_path[:, -1])\n else:\n streamline_unit = (closest_path[:, 0] - soma_voxel) /\\\n euclidean(closest_path[:, 0], soma_voxel)\n\n # determine angle between norm and streamline\n # using dot(a,b) = norm(a)*norm(b)*cos(theta)\n # and norm(cross(a,b)) = norm(a)*norm(b)*sin(theta)\n # and tan(theta) = sin(theta)/cos(theta)\n # therefore tan(theta) = norm(cross(a,b)) / dot(a,b)\n norm_cross = np.linalg.norm(np.cross(norm_unit, streamline_unit))\n dot_prod = np.dot(norm_unit, streamline_unit)\n theta = np.arctan2(norm_cross, dot_prod)\n\n tilt_angle = np.pi / 2 - theta\n\n return tilt_angle", "def raytrace_new_z(self,ralist,declist,zs_n=1.701):\n ra=np.array(ralist)\n dec=np.array(declist)\n\n out_so = cosmic_D(self.w_m, self.w_l, self.zs_o); D_so = out_so['D_A']\n out_sn = cosmic_D(self.w_m, self.w_l, zs_n); D_sn = out_sn['D_A']\n\n D_A_ls_o = ang_D12(self.w_m, self.w_l, self.zl, self.zs_o) # Angular diameter distance between the lens and the source\n D_A_ls_n = ang_D12(self.w_m, self.w_l, self.zl, zs_n) # Angular diameter distance between the lens and the new redshift plane\n\n theta_x, theta_y = self.wcs_x.world_to_pixel_values(ra, dec)\n\n # theta_x, theta_y: are the pixel poitions in the image plane\n #print(theta_x)\n #print(len(theta_x))\n theta_x = np.asarray(theta_x); theta_y = np.asarray(theta_y)\n\n # alpha_x, alpha_y: are the deflection in the x or y direction (deflection in pixels)\n alpha_x, alpha_y = [], []\n\n for k in range(len(theta_x)):\n a_x = self.x_def[int(theta_y[k]), int(theta_x[k])] * (1.0/3600.0)\n a_y = self.y_def[int(theta_y[k]), int(theta_x[k])] * (1.0/3600.0)\n\n apix_x = a_x / self.pix_scale_x; alpha_x.append(apix_x)\n apix_y = a_y / self.pix_scale_y; alpha_y.append(apix_y)\n\n #a_pix_x = np.asarray(a_pix_x); a_pix_y = np.asarray(a_pix_y)\n alpha_x = np.asarray(alpha_x); alpha_y = np.asarray(alpha_y)\n\n src_px = theta_x - alpha_x * ( (D_A_ls_n/D_sn) / (D_A_ls_o/D_so) )\n src_py = theta_y - alpha_y * ( (D_A_ls_n/D_sn) / (D_A_ls_o/D_so) )\n\n self.src_ra, self.src_dec = self.wcs_x.pixel_to_world_values(src_px, src_py)", "def fwd_proj(img_model, pix_angs, pix_dists, prop_speed, ini_t,\r\n fin_t, n_time_pts, ant_rad):\r\n\r\n # Find the number of antenna positions used in the scan\r\n n_ant_pos = pix_angs.shape[0]\r\n\r\n # Make the vector representing the time-points of the radar signals\r\n # in the time domain\r\n scan_times = np.linspace(ini_t, fin_t, n_time_pts)\r\n\r\n # Init arr to return\r\n fwd_projection = np.zeros([n_time_pts, n_ant_pos], dtype=np.complex64)\r\n\r\n # Get ROI (within antenna trajectory)\r\n roi = get_roi(roi_rad=ant_rad, ant_rad=ant_rad,\r\n m_size=np.size(img_model, axis=0))\r\n\r\n # Apply window to set pixels outside of ROI to zero\r\n img_model[np.logical_not(roi)] = 0\r\n\r\n # Find the physical width of each pixel in meters\r\n pix_dist_width = 2 * ant_rad / pix_angs.shape[0]\r\n\r\n # Convert this physical width to a time-of-response width\r\n pix_time_width = pix_dist_width / prop_speed\r\n\r\n # Find the pixels that are in front of the antenna, for each antenna\r\n # position\r\n pix_in_front_ant = np.abs(pix_angs) < 90\r\n\r\n # Find the response times of every pixel, and the upper and lower\r\n # bounds on these estimates\r\n pix_times = pix_dists * pix_in_front_ant / prop_speed\r\n\r\n # Find the upper and lower bounds on the time-of-response estimates\r\n # for each pixel\r\n upper_pix_times = pix_times + 0.5 * pix_time_width\r\n lower_pix_times = pix_times - 0.5 * pix_time_width\r\n\r\n # For every antenna position in the scan\r\n for ant_pos in range(n_ant_pos):\r\n\r\n # For every time-point in the time-domain radar signal\r\n for time_pt in range(n_time_pts):\r\n\r\n # Find the coordinates of the pixels that correspond to this\r\n # time_pt time-of-response\r\n resp_idxs = np.logical_and(scan_times[time_pt]\r\n < upper_pix_times[ant_pos, :, :],\r\n scan_times[time_pt]\r\n > lower_pix_times[ant_pos, :, :])\r\n\r\n # Find the values in the img_model that will be contributing\r\n # to the forward projection here\r\n contributing_values = img_model[resp_idxs]\r\n\r\n # Sum the contributing values after applying any correction\r\n # factors\r\n fwd_projection[time_pt, ant_pos] += np.sum(contributing_values)\r\n\r\n return fwd_projection", "def get_camera_matrix(width, height, fov):\n\txc = (width - 1.0) / 2.0\n\tzc = (height - 1.0) / 2.0\n\tf = (width / 2.0) / np.tan(np.deg2rad(fov / 2.0))\n\tcamera_matrix = utils.Foo(xc=xc, zc=zc, f=f)\n\treturn camera_matrix" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function creates an ray transfer matrix for refraction in a flat interface n1 = initial refractive index n2 = final refractive index
def refraflat(n1 ,n2): arr03 = array([ [1, 0], [0, n1/n2] ], float) print("The ray transfer matrix for refraction in a flat interface is ") print(arr03)
[ "def refflatmirror():\n arr05 = array([\n [1, 0],\n [0, 1]\n ], float)\n print(\"The ray transfer matrix for reflaction in a flat interface is \")\n print(arr05)", "def refracurvemirror(Re):\n arr06 = array([\n [1, 0],\n [-2/Re, 1]\n ], float)\n print(\"The ray transfer matrix for refraction at a curved mirror is \")\n print(arr06)", "def ray_trace_full_set_jones(tstep=5, runtime=24, m0=(2*np.pi)/250, plots=True):\n ladcp, ctd, bathy = data_load.load_data()\n U, V, z_grid = oc.loadLADCP(ladcp)\n S, T, p, lat, lon = oc.loadCTD(ctd)\n N2 = oc.gswN2(S, T, p, lat, lon)\n for i, cast in enumerate(N2.T):\n N2[:,i] = oc.verticalBoxFilter1(cast, p[:,i])\n # Load Data\n lambdaH = pd.read_excel('lambdaH.xlsx')\n kh = pd.read_excel('Kh_masked.xlsx')\n omega = pd.read_excel('omega_masked.xlsx')\n # Depth grid stored as index in pandas dataframes\n depths = np.array(omega.index)\n X = pd.DataFrame(index=depths, columns=np.arange(0,21))\n Z = pd.DataFrame(index=depths, columns=np.arange(0,21))\n OM = pd.DataFrame(index=depths, columns=np.arange(0,21))\n m = pd.DataFrame(index=depths, columns=np.arange(0,21))\n# time = np.arange(0, runtime, tstep)\n x_all = []\n z_all = []\n Om_all = []\n starts = []\n count=0\n for i in range(kh.shape[1]):\n \n \n for k in range(kh.shape[0]):\n depth = depths[k]\n if np.isfinite(kh.loc[depth][i]) and np.isfinite(omega.loc[depth][i]):\n X.loc[depth][i], Z.loc[depth][i],\\\n OM.loc[depth][i], m.loc[depth][i]\\\n = ray_trace_jones_top_down(U[:,i], V[:,i], z_grid,\\\n N2[:,i], p[:,i], kh.loc[depth][i],\\\n m0, depth, omega.loc[depth][i], lat[:,i],\\\n tstep=tstep, runtime=runtime)\n starts.append([i+1, depth])\n x_all.append(X.loc[depth][i])\n z_all.append(Z.loc[depth][i])\n Om_all.append(OM.loc[depth][i])\n \n else:\n X.loc[depth][i] = np.nan\n OM.loc[depth][i] = np.nan\n Z.loc[depth][i] = np.nan\n m.loc[depth][i] = np.nan\n count +=1\n print(count)\n \n \n x_all = np.vstack(x_all)\n z_all = np.vstack(z_all)\n Om_all = np.vstack(Om_all)\n starts = np.vstack(starts)\n \n np.savetxt('x_ray_trace.csv', x_all)\n np.savetxt('z_ray_trace.csv', z_all)\n np.savetxt('Om_ray_trace.csv', Om_all)\n np.savetxt('starts_ray_trace.csv', starts)\n \n \n \n \n # Plotting Data\n if plots:\n fig = plt.figure()\n for i in range(kh.shape[1]):\n for k in range(kh.shape[0]):\n depth = depths[k]\n idx = i\n plt.plot(X.loc[depth][idx],Z.loc[depth][idx])\n plt.xlabel('Horizontal Distance (km)')\n plt.ylabel('depth (m)')\n plt.gca().invert_yaxis()\n \n \n fig = plt.figure()\n for i in range(kh.shape[1]):\n for k in range(kh.shape[0]):\n depth = depths[k]\n idx = i\n plt.plot(X.loc[depth][idx],m.loc[depth][idx]/(2*np.pi))\n plt.xlabel('Horizontal Distance (km)')\n plt.ylabel('vertical wavenumber')\n \n \n fig = plt.figure()\n for i in range(kh.shape[1]):\n for k in range(kh.shape[0]):\n depth = depths[k]\n idx = i\n plt.plot(X.loc[depth][idx],OM.loc[depth][idx])\n plt.xlabel('Horizontal Distance (km)')\n plt.ylabel('frequency ')\n \n \n \n \n \n return x_all, z_all, Om_all, starts", "def tri_matrix(n, c):\n small = int(n / (c+2)) # trailing edges at both ends of the filter vector\n n = n + 2*small\n indices = linear_scale(n, c)\n vectorlist = []\n for i in range(c):\n vectorlist.append(tri(n, indices[i], indices[i + 2]))\n return np.array(vectorlist)[:, small:-small].T", "def StructuredGrid(n,incident_direction=[1,0,0]):\n\n nsq = (n+1)*(n+1)\n directions = np.zeros((6*nsq,3))\n\n # 2D grid for each plane\n ax1,ax2 = np.meshgrid(np.linspace(-1,1,n+1),np.linspace(-1,1,n+1))\n ax1 = ax1.reshape(-1,)\n ax2 = ax2.reshape(-1,)\n\n # x = +1\n directions[0*nsq:1*nsq,0] = -1*np.ones((nsq,))\n directions[0*nsq:1*nsq,1] = ax1\n directions[0*nsq:1*nsq,2] = ax2\n\n # x = -1\n directions[1*nsq:2*nsq,0] = +1*np.ones((nsq,))\n directions[1*nsq:2*nsq,1] = ax1\n directions[1*nsq:2*nsq,2] = ax2\n\n # y = +1\n directions[2*nsq:3*nsq,0] = ax1\n directions[2*nsq:3*nsq,1] = -1*np.ones((nsq,))\n directions[2*nsq:3*nsq,2] = ax2\n\n # y = -1\n directions[3*nsq:4*nsq,0] = ax1\n directions[3*nsq:4*nsq,1] = +1*np.ones((nsq,))\n directions[3*nsq:4*nsq,2] = ax2\n\n # z = +1\n directions[4*nsq:5*nsq,0] = ax1\n directions[4*nsq:5*nsq,1] = ax2\n directions[4*nsq:5*nsq,2] = -1*np.ones((nsq,))\n\n # z = -1\n directions[5*nsq:6*nsq,0] = ax1\n directions[5*nsq:6*nsq,1] = ax2\n directions[5*nsq:6*nsq,2] = +1*np.ones((nsq,))\n\n # Remove duplicates\n # n.b. this does not preserve the order of the points\n directions = np.array([np.array(x) for x in set(tuple(x) for x in directions)])\n\n # Normalise directions\n for i in xrange(directions.shape[0]):\n mag = np.sqrt(np.sum(directions[i]**2))\n directions[i] /= mag\n \n directions=directions.T\n \n # Rotate\n def rotation_matrix(axis,theta):\n axis = axis/np.sqrt(np.dot(axis,axis))\n a = np.cos(theta/2)\n b,c,d = -axis*np.sin(theta/2)\n return np.array([[a*a+b*b-c*c-d*d, 2*(b*c-a*d), 2*(b*d+a*c)],\n [2*(b*c+a*d), a*a+c*c-b*b-d*d, 2*(c*d-a*b)],\n [2*(b*d-a*c), 2*(c*d+a*b), a*a+d*d-b*b-c*c]])\n A = rotation_matrix(np.array([0.0,1.0,0.0]),-np.pi/4)\n B = rotation_matrix(np.array([0.0,0.0,1.0]),np.arcsin(1/np.sqrt(3)))\n rotation_matrix = np.dot(B,A)\n directions = np.dot(rotation_matrix,directions)\n \n directions /= np.sqrt(np.sum(directions**2,axis=0)) # Normalise\n \n return directions", "def setup_shift_of_ray_bundle(seq_model, start_offset):\n\n s1 = seq_model.ifcs[1]\n s0 = seq_model.ifcs[0]\n g0 = gap.Gap(start_offset, seq_model.gaps[0].medium)\n r, t = trns.reverse_transform(s0, g0, s1)\n return r, t", "def transition_function(grid, neighbourstates, neighbourcounts, grid_attribs):\n\n on_fire = grid == 2\n fireable = grid == 1\n\n cells_grid_attribs_on_fire = grid_attribs[on_fire]\n \n\n N_grid_attribs = np.roll(grid_attribs, 1)\n S_grid_attribs = np.roll(grid_attribs, -1)\n E_grid_attribs = np.rollaxis(grid_attribs, 1, 1)\n W_grid_attribs = np.rollaxis(grid_attribs, 1, -1)\n\n NW_grid_attribs = np.rollaxis(N_grid_attribs, 1, -1)\n NE_grid_attribs = np.rollaxis(N_grid_attribs, 1, 1)\n SW_grid_attribs = np.rollaxis(S_grid_attribs, 1, -1)\n SE_grid_attribs = np.rollaxis(S_grid_attribs, 1, 1)\n\n\n NW, N, NE, W, E, SW, S, SE = neighbourstates\n\n is_firable(grid, N_grid_attribs, NE_grid_attribs, E_grid_attribs, SE_grid_attribs, S_grid_attribs, SW_grid_attribs, W_grid_attribs, NW_grid_attribs, N, E, S, W,NE, SE, NW, SW, grid_attribs)\n\n print(\"neighbourstates\")\n print(neighbourstates[0][0])\n\n print(\"neighbourstates.shape\")\n print(neighbourstates.shape)\n neighboursTransposed = neighbourstates.T\n print(neighboursTransposed[0][0])\n # print(N.shape)\n print(\"neighboursTransposed.shape\")\n print(neighboursTransposed.shape)\n\n fire_close = (N == 2) | (E == 2) | (W == 2) | (S == 2)\n fire_far = (NW == 2) | (NE == 2) | (SW == 2) | (SE == 2)\n neighbour_on_fire = fire_close | fire_far\n\n # print( [N for cell in N] )\n\n cells_grid_attribs_neighbours_fireable = grid_attribs[neighbour_on_fire]\n\n print(\"\\n\\n\\n cells_grid_attribs_neighbours_fireable.shape\")\n print(cells_grid_attribs_neighbours_fireable.shape)\n\n firable_with_on_fire_neighbours = fireable & neighbour_on_fire\n print(neighbour_on_fire.shape)\n cells_grid_attribs_fireable = grid_attribs[firable_with_on_fire_neighbours]\n \n firable_sub_set = grid[firable_with_on_fire_neighbours]\n \n\n\n grid[firable_with_on_fire_neighbours] = 2 \n \n grid_attribs[on_fire] = reduce_fuel(\n cells_grid_attribs_on_fire[:, 0], cells_grid_attribs_on_fire[:, 1], cells_grid_attribs_on_fire[:, 2], cells_grid_attribs_on_fire[:, 3], cells_grid_attribs_on_fire[:, 4])\n\n\n print(grid_attribs.shape)\n\n burnt_out_mask = grid_attribs[:,:,4] == 0\n\n grid[burnt_out_mask] = 0\n # print(not_on_fire)\n\n # print(not_on_fire.shape)\n # print(grid.shape)\n # print(not_on_fire)\n # grid[not_on_fire] = 0\n\n\n # print(cells_grid_attribs_fireable[0].shape)\n # red_fuel = np.vectorize(reduce_fuel, otypes=[np.float64])\n\n # cells_grid_attribs_on_fire = red_fuel(*cells_grid_attribs_on_fire)\n # grid_attribs[on_fire] = cells_grid_attribs_on_fire\n # Update\n\n # print(neighbourstates)\n # print(neighbourstates.shape)\n # NW, N, NE, W, E, SW, S, SE = neighbourstates\n # print(\"NW\")\n\n # print(NW.shape)\n\n # in_state_3 = (grid == 3) # cells currently in state 3\n # all_corners_above_1 = (NW > 1) & (NE > 1) & (SW > 1) & (SE > 1) # corner states > 1\n # print(all_corners_above_1.shape)\n # to_one = in_state_3 & all_corners_above_1 # union the results\n # grid[to_one] = 1\n\n # g = lambda x: 1 if x > 1 else round(x, 1)\n # prod = lambda x, y: x*y\n # s = lambda x: 1 if x > 0 else 0\n # l = lambda x, y, w, z: [x, y, w, z]\n\n # #Calculate flammability for that cell\n # add_list = lambda x, y, z, g: s(g)*(x+y+z)\n\n # #Edge condition catching\n # within_bounds = lambda x, y, z: True if (x+y <= 49) and (x+z <= 49) and (x+y >= 0) and (x+z >= 0) else False\n\n # near_steps = np.array([[0,1], [1,0], [0,-1], [-1,0]])\n # dist_steps = np.array([[2,2], [2,-2], [-2,-2], [-2,2]])\n\n # #Vectorize\n # for i in range(50):\n # for j in range(50):\n\n # #TODO: More efficient way?\n # near_attribs = [ l(*grid_attribs[ i+steps[0], i+steps[1] ], grid[ i+steps[0], i+steps[1]] ) if within_bounds(i, *steps) else [0,0,0,0] for steps in near_steps]\n # dist_attribs = [ l(*grid_attribs[ i+steps[0], i+steps[1] ], grid[ i+steps[0], i+steps[1]] ) if within_bounds(i, *steps) else [0,0,0,0] for steps in dist_steps]\n\n # near_sum = 0\n # dist_sum = 0\n\n # #How burnt the cell will be\n # #So if sums of both = 0, then cell is 0\n # for k in range(4):\n # near_sum += add_list(*near_attribs[k])\n # dist_sum += add_list(*dist_attribs[k])\n\n # print((near_sum + 0.25*dist_sum))\n\n # #Round to state (0 -> 1)\n # grid[i][j] += g(near_sum + 0.25*dist_sum)\n\n return grid", "def traject(origin0,tetaOrigin0):\r\n\r\n #cf to \"Analytic ray curve tracing for outdoor sound propagation\"\r\n #to understand what follows in this function\r\n #the formulation of the ray traject in the article is true for\r\n #the local orthonormal coordinates (r,h) were h is the axis directed\r\n #by the direction of the gradient.\r\n \r\n x0,z0=origin0\r\n \r\n alpha=norm(x0,z0)\r\n Vorigin0=fV(x0,z0) \r\n correction=gradOrientation(z0)#the local coordinates are oriented according\r\n #to the direction of the gradient of V^-2\r\n #if it is the opposite of the z axis then we will need to inverse the local\r\n #polynome\r\n teta=correction*tetaOrigin0#because changing the coordinates we inverted\r\n #the vertical axis orientation and so we also change angles orientation\r\n\r\n changeSign=np.sign(teta)#to correct a mistake in the\r\n #formula of rf (sign of teta matters for the vertex position)\r\n #In case where teta=0 it does not matter because rf is equal to 0\r\n\r\n\r\n #Now we calculated the local traject with the poly1d class\r\n #to do this I calculated the coefficient a,b,c of the polynom under this form:\r\n #ar^2+br+c\r\n #it appears that c=0 (the polynome pass throught the origin of the local coordinates)\r\n #I developped rf and epsilon to simplify the expression\r\n a=alpha/(4*(np.cos(teta)/Vorigin0)**2)\r\n b=changeSign*(1/np.cos(teta)**2-1)**(1/2)\r\n #In local coordinate it gives\r\n #h=correction*np.poly1d([a,b,0])\r\n #let's define a polynome for global coordinates\r\n #the polynome is Z(r)=h(r-x0)+z0 and by manual calculating we obtain:\r\n Z=correction*np.poly1d([a,b-2*a*x0,correction*z0-b*x0+a*x0**2])\r\n return (Z)", "def compute_camera_matrix(real_XY, front_image, back_image):\n # TODO: Fill in this code.\n pass", "def arc_to_matrix(vector0, vector1):\n \n vector0 = _setDimension(vector0,2)\n vector1 = _setDimension(vector1,2)\n \n vector0, vector1 = _matchDepth(vector0, vector1)\n \n return _quaternionToMatrix(_vectorArcToQuaternion(vector0, vector1))", "def visualize_RN(self):\n\n react_dict = self.__net_dict\n N = len(react_dict)\n keys = list(react_dict.keys())\n\n # construct top of matrix\n matrix_RN = []\n matrix_RN.append(['---'])\n\n for i in range(N):\n current_complex = self.bin_to_string(keys[i])\n matrix_RN[0].append(current_complex)\n\n # construct remaining parts\n count = 0\n for i in range(N):\n row_leader = self.bin_to_string(keys[i])\n matrix_RN.append([row_leader])\n count += 1\n\n # if complex i reacts from/to complex j, entry is 1. Else entry is 0\n for j in keys:\n\n if j in react_dict[keys[i]]:\n matrix_RN[count].append(['1'])\n else:\n matrix_RN[count].append(['0'])\n\n print('\\n'.join([''.join(['{:10}'.format(str(item)) for item in row]) for row in matrix_RN]))\n\n return", "def d1_matrix(n, diff=1):\n rows = n - diff\n cols = n\n mat = np.zeros(shape=(rows, cols))\n for i in range(rows):\n for j in range(cols):\n if j - i == 0:\n mat[i, j] = -1\n elif j - i == diff:\n mat[i, j] = 1\n return mat", "def raytrace_new_z(self,ralist,declist,zs_n=1.701):\n ra=np.array(ralist)\n dec=np.array(declist)\n\n out_so = cosmic_D(self.w_m, self.w_l, self.zs_o); D_so = out_so['D_A']\n out_sn = cosmic_D(self.w_m, self.w_l, zs_n); D_sn = out_sn['D_A']\n\n D_A_ls_o = ang_D12(self.w_m, self.w_l, self.zl, self.zs_o) # Angular diameter distance between the lens and the source\n D_A_ls_n = ang_D12(self.w_m, self.w_l, self.zl, zs_n) # Angular diameter distance between the lens and the new redshift plane\n\n theta_x, theta_y = self.wcs_x.world_to_pixel_values(ra, dec)\n\n # theta_x, theta_y: are the pixel poitions in the image plane\n #print(theta_x)\n #print(len(theta_x))\n theta_x = np.asarray(theta_x); theta_y = np.asarray(theta_y)\n\n # alpha_x, alpha_y: are the deflection in the x or y direction (deflection in pixels)\n alpha_x, alpha_y = [], []\n\n for k in range(len(theta_x)):\n a_x = self.x_def[int(theta_y[k]), int(theta_x[k])] * (1.0/3600.0)\n a_y = self.y_def[int(theta_y[k]), int(theta_x[k])] * (1.0/3600.0)\n\n apix_x = a_x / self.pix_scale_x; alpha_x.append(apix_x)\n apix_y = a_y / self.pix_scale_y; alpha_y.append(apix_y)\n\n #a_pix_x = np.asarray(a_pix_x); a_pix_y = np.asarray(a_pix_y)\n alpha_x = np.asarray(alpha_x); alpha_y = np.asarray(alpha_y)\n\n src_px = theta_x - alpha_x * ( (D_A_ls_n/D_sn) / (D_A_ls_o/D_so) )\n src_py = theta_y - alpha_y * ( (D_A_ls_n/D_sn) / (D_A_ls_o/D_so) )\n\n self.src_ra, self.src_dec = self.wcs_x.pixel_to_world_values(src_px, src_py)", "def reconstruction_d_matrix(self):\n\n d_matrix = np.zeros_like(self.d_matrix)\n for n_step in np.arange(self.nsteps):\n transfer_matrix = self.transfer_matrix_from_simframe(os.path.abspath(os.path.join(os.getcwd(),\n 'quad_scan_setup_' +\n str(n_step))))\n np.savetxt(os.path.abspath(os.path.join(os.getcwd(), 'quad_scan_setup_' + str(n_step),\n \"transfer_matrix_rec_obs_VM.txt\")), transfer_matrix)\n self.calculation_d_matrix_step(transfer_matrix)\n for k in np.arange(self.d_matrix_step.shape[1]):\n d_matrix[(3 * n_step), k] = deepcopy(self.d_matrix_step[0, k])\n d_matrix[(3 * n_step) + 1, k] = deepcopy(self.d_matrix_step[1, k])\n d_matrix[(3 * n_step) + 2, k] = deepcopy(self.d_matrix_step[2, k])\n setattr(self, 'd_matrix', d_matrix)", "def _matinterface(N0, Nl, t0):\n \n rp, rs, tp, ts = fresnel2(t0, N0, Nl)\n m1p = 1./tp\n m1s = 1./ts\n m2p = rp/tp\n m2s = rs/ts\n mp = (m1p, m2p, m2p, m1p)\n ms = (m1s, m2s, m2s, m1s)\n return mp, ms", "def make_transition_matrix(links):\n n = len(links)\n transition_matrix = sp.zeros((n, n))\n for i in range(n):\n for j in range(len(links[i])):\n transition_matrix[links[i][j]][i] = 1/len(links[i])\n\n return transition_matrix", "def impmat(structure, freq):\n center = Matrix(structure.center)\n center_ = Matrix(structure.center_)\n edge_length = structure.edge_length\n\n edges_total = structure.edges_total\n triangles_total = structure.triangles_total\n speed_of_light = structure.speed_of_light\n\n wn = 2*PI*freq/speed_of_light\n Z_matrix = np.zeros(shape = (edges_total, edges_total), dtype = np.complex_)\n\n\n for tri in range(triangles_total):\n ## find the edge no for each tri, and group into plus or minus\n plus = []\n minus = []\n count = 0\n for index in range(edges_total):\n if count <= 3:\n if structure.triangle_plus[index] == tri:\n plus.append(index)\n count += 1\n elif structure.triangle_minus[index] == tri:\n minus.append(index)\n count += 1\n\n G = center_ - fill(center(tri), triangles_total, 9) ## dim = no of ttl triangles x 9 sub's\n abs(G)\n fphase = lambda R: (cos(wn*R) - 1j*sin(wn*R))/R\n G.element_wise(fphase)\n ZF=[]\n for k in range(edges_total):\n Fi = sum(G.row(structure.triangle_plus[k])) - sum(G.row(structure.triangle_minus[k]))\n ZF.append(structure.FactorFi[k] / freq * Fi / 9)\n\n Z = None\n Zi = None\n ### --- loop thru each source edge (S); for each edge, fill in the entire column\n for n in plus + minus:\n if n in plus:\n source = structure.rho__plus\n func = lambda x, y: x+y\n else:\n source = structure.rho__minus\n func = lambda x, y: x-y\n src = source[n]\n rho_p = [[each.dot(structure.rho_plus[row]) for each in src] for row in range(edges_total)]\n rho_m = [[each.dot(structure.rho_minus[row])for each in src] for row in range(edges_total)]\n # dim of rho_p and rho_m: no of triangles x 9 sub's\n\n area = []\n ### --- loop through each obverver edge (O)\n for m in range(edges_total):\n g_p = G.row(structure.triangle_plus[m])\n g_m = G.row(structure.triangle_minus[m])\n r_p = rho_p[m]\n r_m = rho_m[m]\n area_p = sum([each*g_p[index] for index, each in enumerate(r_p)])\n area_m = sum([each*g_m[index] for index, each in enumerate(r_m)])\n area.append(area_p + area_m)\n Z1 = [ each*area[index]*freq/9.0 for index, each in enumerate(structure.FactorA)]\n edge = edge_length[n]\n Zi = [ each*edge for each in map(func, Z1, ZF)]\n Z_matrix[:,n] += Zi\n\n return Z_matrix", "def add_matrix(self):\n edges_dictionary = self.edges_dictionary\n nodes_dictionary = self.nodes_dictionary\n\n pairs = ((i, j) for i in self.nodes.keys() for j in self.nodes.keys())\n sorted_index = np.array([nodes_dictionary[first_node] * len(self.nodes) + nodes_dictionary[second_node]\n for first_node in self.nodes.keys()\n for second_node in self.nodes.keys()])\n self.mapping = np.argsort(sorted_index)\n # dictionary of generators for all paths\n paths_generator = {}\n paths_dict = {}\n # number of paths between pair of nodes\n number_of_paths = {}\n\n pair_path_indptr = [0]\n link_path_indptr = [0]\n data = []\n data_tild = []\n C_tild = []\n link_path_indices = []\n path_index = 0\n link_path_index = 0\n\n pairwise_dist = self.pairs_distances\n\n for pair in tqdm(pairs):\n if pair[0] != pair[1]:\n # generates desired paths between source and target . returns a generator!\n paths_generator[pair] = self.path_gen_func(self, pair[0], pair[1])\n\n for path in paths_generator[pair]:\n data.append(pairwise_dist[pair])\n paths_dict[tuple(path)] = path_index\n link_path_indices.extend([edges_dictionary[key] for key in zip(path[:-1], path[1:])])\n data_tild.extend([1 / float(pairwise_dist[pair]) for _ in range(len(path) - 1)])\n link_path_index += len(path) - 1\n link_path_indptr.append(link_path_index)\n C_tild.append(1 / float(pairwise_dist[pair]))\n path_index += 1\n\n number_of_paths[pair] = path_index - pair_path_indptr[-1]\n data_tild[pair_path_indptr[-1]:] /= np.sqrt(number_of_paths[pair])\n C_tild[-1] /= np.sqrt(number_of_paths[pair])\n pair_path_indptr.append(path_index)\n\n else:\n number_of_paths[pair] = path_index - pair_path_indptr[-1]\n # Add a zero row to H\n pair_path_indptr.append(path_index)\n\n pair_path_indices = range(path_index)\n\n self.H = sparse.csr_matrix((data, pair_path_indices, pair_path_indptr))[self.mapping, :]\n # the columns of this matrix have the same mapping of paths to index ,with H\n self.A = sparse.csc_matrix((np.ones((len(link_path_indices),)), link_path_indices, link_path_indptr))\n self.A_tild = sparse.csc_matrix((data_tild, link_path_indices, link_path_indptr))\n # this is the vector containing of d_ij * sqrt(n_ij)\n self.C_tild = np.array(C_tild)\n self.C_tild_squared = self.C_tild ** 2\n self.total_number_of_active_paths = self.H.shape[1]\n self.number_of_paths = number_of_paths\n self.number_of_edges = self.A.shape[0]\n self.path_dictionary = paths_dict", "def estimate_indirect_connections():\n path = os.path.join(DATA_INTERMEDIATE, 'network_edges.shp')\n indirect_lut = gpd.read_file(path)\n\n output = []\n\n for idx, item in indirect_lut.iterrows():\n\n output.append({\n 'origin_id': item['origin_id'],\n 'dest_funth': item['dest_funth'],\n 'dest_func': item['dest_func'],\n 'dest_dist': item['dest_dist'],\n })\n\n output = pd.DataFrame(output)\n\n path = os.path.join(DATA_INTERMEDIATE, 'indirect_lut.csv')\n output.to_csv(path, index=False)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function creates an ray transfer matrix for reflection from a flat mirror. You don't need to create any input here.
def refflatmirror(): arr05 = array([ [1, 0], [0, 1] ], float) print("The ray transfer matrix for reflaction in a flat interface is ") print(arr05)
[ "def refracurvemirror(Re):\n arr06 = array([\n [1, 0],\n [-2/Re, 1]\n ], float)\n print(\"The ray transfer matrix for refraction at a curved mirror is \")\n print(arr06)", "def refraflat(n1 ,n2):\n arr03 = array([\n [1, 0],\n [0, n1/n2]\n ], float)\n print(\"The ray transfer matrix for refraction in a flat interface is \")\n print(arr03)", "def translation_matrix(direction):\n ndim = len(direction)\n mat = np.identity(ndim+1)\n mat[:ndim, ndim] = direction[:ndim]\n \n return mat", "def arc_to_matrix(vector0, vector1):\n \n vector0 = _setDimension(vector0,2)\n vector1 = _setDimension(vector1,2)\n \n vector0, vector1 = _matchDepth(vector0, vector1)\n \n return _quaternionToMatrix(_vectorArcToQuaternion(vector0, vector1))", "def reconstruction_d_matrix(self):\n\n d_matrix = np.zeros_like(self.d_matrix)\n for n_step in np.arange(self.nsteps):\n transfer_matrix = self.transfer_matrix_from_simframe(os.path.abspath(os.path.join(os.getcwd(),\n 'quad_scan_setup_' +\n str(n_step))))\n np.savetxt(os.path.abspath(os.path.join(os.getcwd(), 'quad_scan_setup_' + str(n_step),\n \"transfer_matrix_rec_obs_VM.txt\")), transfer_matrix)\n self.calculation_d_matrix_step(transfer_matrix)\n for k in np.arange(self.d_matrix_step.shape[1]):\n d_matrix[(3 * n_step), k] = deepcopy(self.d_matrix_step[0, k])\n d_matrix[(3 * n_step) + 1, k] = deepcopy(self.d_matrix_step[1, k])\n d_matrix[(3 * n_step) + 2, k] = deepcopy(self.d_matrix_step[2, k])\n setattr(self, 'd_matrix', d_matrix)", "def to_matrix(vector0, vector1, aim_axis=0, up_axis=1, extrapolate=False): \n \n vector0 = _setDimension(vector0,2)\n vector1 = _setDimension(vector1,2)\n aim_axis = _setDimension(aim_axis,1,dtype=np.int32) % 3\n up_axis = _setDimension(up_axis,1,dtype=np.int32) % 3\n \n vector0, vector1, aim_axis, up_axis = _matchDepth(vector0, vector1, aim_axis, up_axis)\n \n return _vectorToMatrix(vector0, vector1, aim_axis, up_axis)", "def ray_reflection(rays, normal):\n ray_direction = rays.p1 - tf.multiply(normal, tf.expand_dims(tf.reduce_sum(normal * rays.p1, 1), 1)) * 2.\n # if directional vector small enough, then assume 0.\n ray_direction = tf.where(tf.greater(tf.abs(ray_direction), epsilon), ray_direction, tf.zeros_like(ray_direction))\n\n return ray_direction", "def build_matrix(self):\n # Note that by nature, a camera perspective inverts everything\n # So we negate everything and also do it in reverse\n\n # Overrides PositionMatrix, reverse everything, ignore scale \n m = Matrix44.identity()\n m = Matrix44.from_translation(-1 * Vector3(self.position)) * m\n m = Matrix44.from_z_rotation(-math.radians(self.roll)) * m\n m = Matrix44.from_y_rotation(-math.radians(self.yaw)) * m\n m = Matrix44.from_x_rotation(-math.radians(self.pitch)) * m\n if self.tp:\n # Third person enabled\n m = Matrix44.from_translation([0,0,-self.tp_distance]) * m\n \n self.m = m\n self.mvp = numpy.array(self.p * self.m).astype(\"f4\")", "def reflect_surface(vertices, faces, axis=0):\n reflect_matrix = np.eye(4)\n reflect_matrix[axis, axis] = -1\n return perform_rigid_transform(vertices, reflect_matrix), faces", "def compute_camera_matrix(real_XY, front_image, back_image):\n # TODO: Fill in this code.\n pass", "def rotation_matrix_decompose(r):\n return numpy.array( (math.atan2(r[2][1],r[2][2]),\\\n math.atan2(-r[2][0],math.sqrt(r[2][1]*r[2][1]+r[2][2]*r[2][2])),\\\n math.atan2(r[1][0],r[0][0])))", "def compute_instrument_transformation_matrix(rx_offset, ry_offset, rz_offset):\n angle_zr = np.radians(rz_offset)\n angle_yr = np.radians(ry_offset)\n angle_xr = np.radians(rx_offset)\n Rz = np.array([[np.cos(angle_zr), -np.sin(angle_zr), 0], [np.sin(angle_zr), np.cos(angle_zr), 0], [0, 0, 1]])\n Ry = np.array([[np.cos(angle_yr), 0, np.sin(angle_yr)], [0, 1, 0], [-np.sin(angle_yr), 0, np.cos(angle_yr)]])\n Rx = np.array([[1, 0, 0], [0, np.cos(angle_xr), -np.sin(angle_xr)], [0, np.sin(angle_xr), np.cos(angle_xr)]])\n T = Rz.dot(np.dot(Ry, Rx))\n return T", "def make_transition_matrix(links):\n n = len(links)\n transition_matrix = sp.zeros((n, n))\n for i in range(n):\n for j in range(len(links[i])):\n transition_matrix[links[i][j]][i] = 1/len(links[i])\n\n return transition_matrix", "def calc_reflection(self, phit, normal, dist_from_origin, db) -> \"Ray\":\n ray = Vec3(*(-(normal * (self.direction.dot(normal) * 2)).sub(self.direction)))\n return Ray(phit, ray, dist_from_origin, db)", "def create_cam2world_matrix(forward_vector: torch.Tensor, origin: torch.Tensor,\n up: torch.Tensor) -> torch.Tensor:\n\n forward_vector = normalize_vecs(forward_vector)\n up_vector = up.type(torch.float).expand_as(forward_vector)\n right_vector = -normalize_vecs(\n torch.cross(up_vector, forward_vector, dim=-1))\n up_vector = normalize_vecs(\n torch.cross(forward_vector, right_vector, dim=-1))\n\n rotation_matrix = torch.eye(\n 4, device=origin.device).unsqueeze(0).repeat(forward_vector.shape[0],\n 1, 1)\n rotation_matrix[:, :3, :3] = torch.stack(\n (right_vector, up_vector, forward_vector), axis=-1)\n\n translation_matrix = torch.eye(\n 4, device=origin.device).unsqueeze(0).repeat(forward_vector.shape[0],\n 1, 1)\n translation_matrix[:, :3, 3] = origin\n cam2world = (translation_matrix @ rotation_matrix)[:, :, :]\n assert (cam2world.shape[1:] == (4, 4))\n return cam2world", "def transfer_matrix_from_simframe(self, directory):\n transfer_matrix = np.zeros((4, 4))\n transfer_matrix_rec_point = np.zeros_like(transfer_matrix)\n transfer_matrix_obs_point = np.zeros_like(transfer_matrix)\n\n twiss_object = read_twiss_file.twiss()\n\n for file_mat in os.listdir(directory):\n if file_mat.endswith('.mat'):\n file_sdds = deepcopy(os.path.join(directory, file_mat))\n else:\n continue\n twiss_object.read_sdds_file(file_sdds, ascii=False)\n index_rec = np.where(twiss_object['elegant']['ElementName'] == 'CLA-S02-DIA-SCR-02')[0][0]\n index_obs = np.where(twiss_object['elegant']['ElementName'] == 'CLA-S02-DIA-SCR-03')[0][0]\n\n for key in twiss_object['elegant'].keys():\n if key.startswith('R'):\n number = deepcopy(int(key.replace('R', '')))\n i = int(number / 10)\n j = np.remainder(number, 10)\n if (i <= 4) and (j <= 4):\n transfer_matrix[i - 1, j - 1] = float(twiss_object['elegant'][key][index_obs])\n transfer_matrix_rec_point[i - 1, j - 1] = float(twiss_object['elegant'][key][index_rec])\n else:\n continue\n else:\n continue\n return np.dot(transfer_matrix, np.linalg.inv(transfer_matrix_rec_point))", "def ListMirrorPlanes(self):\n lde = self.TheSystem.LDE\n nSurf = lde.NumberOfSurfaces\n surfList = []\n for n in range(0,nSurf):\n surf = lde.GetSurfaceAt(n)\n if surf.Material == 'MIRROR':\n surfList.append(n)\n return(surfList)", "def forward_transform(matrix):\n\n ft = np.zeros(matrix.shape, dtype='complex_')\n N = matrix.shape[0]\n\n for u in range(matrix.shape[0]):\n for v in range(matrix.shape[1]):\n # print(\"\\t\\tU = \", u, \" V = \", v)\n s = 0\n\n for i in range(matrix.shape[0]):\n for j in range(matrix.shape[1]):\n # print(\"i = \", i, \" j = \", j)\n cos = np.round(math.cos(((2 * math.pi) / N) * (u * i + v * j)), decimals=5)\n sin = np.round(math.sin(((2 * math.pi) / N) * (u * i + v * j)), decimals=5)\n s += matrix[i, j] * complex(cos, -sin)\n # print(((2 * math.pi) / 2) * (u * i + v * j), cos, sin, s)\n\n ft[u, v] = s\n # print(\"[\", u, \",\", v, \"]\", ft[u, v])\n # print(\"\\n\")\n return ft", "def calculateMirrorData(srcNode, targetNode, flip=False):\n # type: (Transform, Transform, bool) -> List[MirrorEntry]\n\n results = []\n\n # mirror attribute of source\n for attrName in anim_utils.listAttrForMirror(srcNode):\n\n full_path = \"{}.{}\".format(srcNode.name(), attrName)\n if node_utils.is_proxy_attribute(full_path):\n continue\n\n # whether does attribute \"invTx\" exists when attrName is \"tx\"\n invCheckName = anim_utils.getInvertCheckButtonAttrName(attrName)\n if not pm.attributeQuery(invCheckName,\n node=srcNode,\n shortName=True,\n exists=True,\n keyable=True):\n\n # if not exists, straight\n inv = 1\n\n else:\n # if exists, check its value\n invAttr = srcNode.attr(invCheckName)\n if invAttr.get():\n inv = -1\n else:\n inv = 1\n\n # whether does attribute \"invTx\" exists when attrName is \"tx\"\n pivotCheckName = getPivotCheckButtonAttrName(attrName)\n if not pm.attributeQuery(pivotCheckName,\n node=srcNode,\n shortName=True,\n exists=True,\n keyable=True):\n\n # if not exists, straight\n pivot = 0.\n\n else:\n # if exists, check its value\n pivotAttr = srcNode.attr(pivotCheckName)\n pivot = pivotAttr.get()\n\n # if attr name is side specified, record inverted attr name\n if anim_utils.isSideElement(attrName):\n invAttrName = anim_utils.swapSideLabel(attrName)\n else:\n invAttrName = attrName\n\n # if flip enabled record self also\n if flip:\n flipVal = targetNode.attr(attrName).get()\n if isinstance(flipVal, float):\n entry = MirrorEntry(srcNode, invAttrName, (flipVal + pivot) * inv)\n else:\n entry = MirrorEntry(srcNode, invAttrName, (flipVal) * inv)\n\n results.append(entry)\n\n if isinstance(srcNode.attr(attrName).get(), float):\n entry = MirrorEntry(targetNode, invAttrName, (srcNode.attr(attrName).get() + pivot) * inv)\n else:\n entry = MirrorEntry(targetNode, invAttrName, (srcNode.attr(attrName).get()) * inv)\n results.append(entry)\n\n return results" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function creates an ray transfer matrix for refraction in a curved mirror. You just need to enter effective radius of curvature, Re in the bracket.
def refracurvemirror(Re): arr06 = array([ [1, 0], [-2/Re, 1] ], float) print("The ray transfer matrix for refraction at a curved mirror is ") print(arr06)
[ "def refflatmirror():\n arr05 = array([\n [1, 0],\n [0, 1]\n ], float)\n print(\"The ray transfer matrix for reflaction in a flat interface is \")\n print(arr05)", "def traject(origin0,tetaOrigin0):\r\n\r\n #cf to \"Analytic ray curve tracing for outdoor sound propagation\"\r\n #to understand what follows in this function\r\n #the formulation of the ray traject in the article is true for\r\n #the local orthonormal coordinates (r,h) were h is the axis directed\r\n #by the direction of the gradient.\r\n \r\n x0,z0=origin0\r\n \r\n alpha=norm(x0,z0)\r\n Vorigin0=fV(x0,z0) \r\n correction=gradOrientation(z0)#the local coordinates are oriented according\r\n #to the direction of the gradient of V^-2\r\n #if it is the opposite of the z axis then we will need to inverse the local\r\n #polynome\r\n teta=correction*tetaOrigin0#because changing the coordinates we inverted\r\n #the vertical axis orientation and so we also change angles orientation\r\n\r\n changeSign=np.sign(teta)#to correct a mistake in the\r\n #formula of rf (sign of teta matters for the vertex position)\r\n #In case where teta=0 it does not matter because rf is equal to 0\r\n\r\n\r\n #Now we calculated the local traject with the poly1d class\r\n #to do this I calculated the coefficient a,b,c of the polynom under this form:\r\n #ar^2+br+c\r\n #it appears that c=0 (the polynome pass throught the origin of the local coordinates)\r\n #I developped rf and epsilon to simplify the expression\r\n a=alpha/(4*(np.cos(teta)/Vorigin0)**2)\r\n b=changeSign*(1/np.cos(teta)**2-1)**(1/2)\r\n #In local coordinate it gives\r\n #h=correction*np.poly1d([a,b,0])\r\n #let's define a polynome for global coordinates\r\n #the polynome is Z(r)=h(r-x0)+z0 and by manual calculating we obtain:\r\n Z=correction*np.poly1d([a,b-2*a*x0,correction*z0-b*x0+a*x0**2])\r\n return (Z)", "def get_reflections(r, dr, beads, R_func, Nx, Ny, L):\n\n # Initialize\n r = np.array(r)\n dr = np.array(dr)\n reflected = False\n internal_trajectory = []\n\n def P(i):\n return beads[i, :2]\n\n # Cycle through beads locations\n distances = np.full(Nx * Ny, np.inf)\n for i in range(Nx * Ny):\n reachable, _, distance = get_bead_intersection(r, dr, P(i), R_func(P(i)[0]))\n if reachable:\n distances[i] = distance\n\n # Start with the closest one\n i = np.argmin(distances)\n # print('Dists', distances, i)\n reachable, intersection, distance = get_bead_intersection(r, dr, P(i), R_func(P(i)[0]))\n\n if reachable:\n # calculate the new dr (direction)\n reflected = True\n\n radial_vec = intersection - P(i)\n cos_value = (dr * radial_vec).sum() / norm(dr) / norm(radial_vec)\n\n # Correct for round-off error\n if cos_value > 1:\n cos_value = 1\n elif cos_value < -1:\n cos_value = -1\n\n incidence_angle = np.pi - np.arccos(cos_value) # incidence angle\n # print('acos', dr, radial_vec, (dr * radial_vec).sum() / norm(dr) / norm(radial_vec))\n # print('incidence_angle, grad', incidence_angle / np.pi * 180)\n phi = np.pi - 2 * incidence_angle # rotation angle\n with np.errstate(divide='ignore'):\n reflection_angle = np.pi / 2 + np.arctan(radial_vec[1] / radial_vec[0])\n # print('reflection angle', reflection_angle)\n reflection_matrix = np.array(\n [[np.cos(2 * reflection_angle), np.sin(2 * reflection_angle)], [np.sin(2 * reflection_angle), -np.cos(2 * reflection_angle)]])\n\n dr_before_intersct = intersection - r\n dr_after_intersct = r + dr - intersection\n new_dr_after = reflection_matrix @ dr_after_intersct.transpose()\n # print('a', reflection_matrix, dr_after_intersct.transpose(), new_dr_after)\n internal_trajectory.append([*r, *dr_before_intersct])\n\n # Call function again to check for other reflections\n _, new_r, new_dr_after, internal_trajectory2, _ = get_reflections(\n r=intersection, dr=new_dr_after, beads=beads, R_func=R_func, Nx=Nx, Ny=Ny, L=L)\n # new_r = intersection + new_dr_after\n internal_trajectory += internal_trajectory2\n\n else:\n # Check if reaching the border\n # print('Calling boundary intersection with ', r, dr, L)\n leaving, old_intersection, intersection, new_dr_after = get_boundary_intersection(r, dr, L)\n # print('boundary', r, dr, L, \">>>\", leaving, intersection, new_dr_after)\n\n dr_to_intersection = old_intersection - r\n\n if leaving:\n internal_trajectory.append([*r, *dr_to_intersection])\n _, _, new_dr_after, internal_trajectory2, _ = get_reflections(\n intersection, new_dr_after, beads, R_func, Nx, Ny, L)\n new_r = intersection + new_dr_after\n internal_trajectory += internal_trajectory2\n reflected = True\n # new_dr = new_r - r\n else:\n reflected = False\n intersection = np.nan\n new_r = r + dr\n new_dr_after = dr\n internal_trajectory.append([*r, *dr])\n # new_dr = dr\n dr_after_intersection = new_dr_after\n # print('int', internal_trajectory)\n new_dr = np.asarray(internal_trajectory)[:, 2:4].sum(axis=0)\n # new_dr =\n\n return reflected, new_r, dr_after_intersection, internal_trajectory, new_dr", "def RREF(self): # m.rref \"(1,2,3;4,5,6;7,8,9)\"\n matrix = self.array\n \n r = 0\n for i in range(len(matrix)): # Prochazim radky\n pivot = matrix[i][r]\n\n i_next = i + 1\n while pivot == 0 and i_next < len(matrix): # Pokud je na pivotu 0, prohodim aktualni a nasledujci radek\n matrix[i],matrix[i_next] = matrix[i_next],matrix[i_next]\n pivot = matrix[i][r]\n i_next += 1\n\n if pivot == 0:\n break\n\n for k in range(len(matrix[i])): # Na pozici aktulniho pivota dam 1\n matrix[i][k] = matrix[i][k] / pivot\n\n pivot = matrix[i][r] # = 1\n if pivot != 1:\n raise Exception(\"Pivot is not one\")\n\n for j in range(len(matrix)): # Prochazim vsechny radky krom aktualniho\n if j == i:\n continue\n ratio = matrix[j][r] / pivot\n for k in range(len(matrix[i])): # Prochazim sloupce\n matrix[j][k] = matrix[j][k] - ratio * matrix[i][k] \n \n if r + 1 < len(matrix[i]):\n r += 1\n\n return self", "def rel_pose_from_coord_change_to_camera_change(R_cur_rel_to_prev, t_cur_rel_to_prev):\n R_prev_rel_to_cur = np.transpose(R_cur_rel_to_prev)\n t_prev_rel_to_cur = -1 * np.matmul(\n R_prev_rel_to_cur, t_cur_rel_to_prev.reshape((3, 1))\n )\n\n return R_prev_rel_to_cur, t_prev_rel_to_cur", "def revolve(radius=\"string\", rebuild=bool, polygon=int, startSweep=int, endSweep=int, radiusAnchor=float, degree=int, axis=\"string\", pivotY=\"string\", object=bool, range=bool, pivotX=\"string\", caching=bool, tolerance=\"string\", name=\"string\", bridge=bool, autoCorrectNormal=bool, axisChoice=int, useLocalPivot=bool, axisY=\"string\", pivot=\"string\", pivotZ=\"string\", sections=int, computePivotAndAxis=int, useTolerance=bool, nodeState=int, axisX=\"string\", axisZ=\"string\", constructionHistory=bool):\n pass", "def get_circle_edgematrix(center_x, center_y, radius, step=30):\n return Generator.get_polygon_edgematrix(\n center_x, center_y, radius, step)", "def circular_trajectory_3d(geometry):\n rays = np.zeros([geometry.number_of_projections, 3])\n angular_increment = geometry.angular_range / geometry.number_of_projections\n for i in range(geometry.number_of_projections):\n rays[i] = [np.cos(i * angular_increment), np.sin(i * angular_increment),0]\n return rays", "def get_light_curve(\n self,\n orbit=None,\n r=None,\n t=None,\n texp=None,\n return_num_eval=False,\n light_delay=False,\n **kwargs\n ):\n if orbit is None:\n raise ValueError(\"missing required argument 'orbit'\")\n if r is None:\n raise ValueError(\"missing required argument 'r'\")\n if t is None:\n raise ValueError(\"missing required argument 't'\")\n\n r = tt.as_tensor_variable(r)\n r = tt.reshape(r, (r.size,))\n t = tt.as_tensor_variable(t)\n\n def pad(arg):\n return arg\n # return tt.shape_padleft(arg, t.ndim) + tt.shape_padright(\n # tt.zeros_like(t), arg.ndim\n # )\n\n rgrid = pad(r)\n if texp is None:\n coords = orbit.get_relative_position(t, light_delay=light_delay)\n b = tt.sqrt(coords[0] ** 2 + coords[1] ** 2)\n b = tt.reshape(b, rgrid.shape)\n los = tt.reshape(coords[2], rgrid.shape)\n return limbdark(\n self.c_norm, b / orbit.r_star, rgrid / orbit.r_star, los\n )[0]\n\n n = pad(orbit.n)\n sini = pad(orbit.sin_incl)\n cosi = pad(orbit.cos_incl)\n # texp = tt.as_tensor_variable(texp) + tt.zeros_like(rgrid)\n\n if orbit.ecc is None:\n aome2 = pad(-orbit.a)\n e = 0.0\n sinw = 0.0\n cosw = 0.0\n kwargs[\"circular\"] = True\n else:\n aome2 = pad(-orbit.a * (1 - orbit.ecc ** 2))\n e = pad(orbit.ecc)\n sinw = pad(orbit.sin_omega)\n cosw = pad(orbit.cos_omega)\n kwargs[\"circular\"] = False\n\n # Apply the time integrated op\n tgrid = tt.transpose(orbit._warp_times(t) - orbit.tref)\n texp = tt.as_tensor_variable(texp) + tt.zeros_like(tgrid)\n kwargs[\"Nc\"] = kwargs.get(\"Nc\", self.num_cl)\n op = IntegratedLimbDarkOp(**kwargs)\n res = op(\n self.c_norm,\n texp,\n tgrid,\n rgrid / orbit.r_star,\n n,\n aome2,\n sini,\n cosi,\n e,\n sinw,\n cosw,\n )\n if return_num_eval:\n return res[0], res[1]\n return res[0]", "def refraflat(n1 ,n2):\n arr03 = array([\n [1, 0],\n [0, n1/n2]\n ], float)\n print(\"The ray transfer matrix for refraction in a flat interface is \")\n print(arr03)", "def create(\n cameraMatrix=...,\n minDepth=...,\n maxDepth=...,\n maxDepthDiff=...,\n maxPointsPart=...,\n iterCounts=...,\n minGradientMagnitudes=...,\n transformType=...,\n ) -> retval:\n ...", "def get_rays(self, pre_perturb, num_circles=3, resolution=6, wavelength=green):\n # Below, u,v,w will denote local right-handed axis system, with *w*\n # pointing in direction of self.v\n debug = True\n radius = self.radius\n M = self.T.dot(pre_perturb)\n assert M.shape == (4,4), f\"bad shape T={self.T}, pre_perturb={pre_perturb}\"\n rays = []\n pairs = []\n def emit(u,v):\n ray = Ray.of_q_v(point(u,v,0), kk, wavelength=wavelength).transform(M)\n if debug:\n print(f\"emitting {ray.v_q}\")\n rays.append(ray)\n for i in range(0, num_circles+1):\n rays_so_far = len(rays)\n r = radius * (i / num_circles)\n num_points = max(1, resolution * i)\n for theta in np.arange(num_points) * (2 * np.pi / num_points):\n emit(r * np.cos(theta), r * np.sin(theta))\n for i in range(num_points):\n pairs.append((rays_so_far + i, rays_so_far + (i + 1) % num_points))\n # Add a couple more line segments...\n if num_circles >= 1:\n pairs.append((0,1))\n # Let's say we have 1 point in center, 6 points around that, then 12 points\n # around that; we want the 4th point of those 12; so it should have 1 + 6 + (12 / 4)\n # points before it.\n if num_circles >= 2:\n pairs.append((0, 1 + resolution + (resolution // 2)))\n if debug:\n print(f\"pairs={pairs}\")\n print(f\"first few ray points = {[ ray.q() for ray in rays[:3]]}\")\n return rays, pairs", "def __init__(self, R, sigma_T):\n self.sigma_T = sigma_T\n self.R = R\n self.L = R * self.points_per_m #Number of array cells in a radius\n self.side = 2 * self.pad_factor * self.L\n #Number of cells in the padded aperture array\n self.aperture = np.fromfunction(lambda i, j:\n self.taper(i, j,\n self.sigma_T *\n self.points_per_m,\n 2 * self.L),\n (2 * self.L,\n 2 * self.L), dtype=complex)\n #Above line generates a square array where each cell has the\n #value obtained by calling taper on that x,y coordinate\n\n y,x = np.ogrid[-self.L : self.L,\n -self.L : self.L]\n mask = x*x + y*y >= self.L ** 2\n self.aperture[mask] = 0\n #Set cells at radius > R to 0\n\n #Embed in padded array\n padded = np.zeros([self.side, self.side], dtype=complex)\n padded[self.side / 2 - self.L: self.side / 2 + self.L,\n self.side / 2 - self.L: self.side / 2 + self.L] = \\\n self.aperture\n self.aperture = padded", "def CCM(wl, R_V=3.1):\n\n\n a = np.zeros(np.shape(wl))\n b = np.zeros(np.shape(wl))\n F_a = np.zeros(np.shape(wl))\n F_b = np.zeros(np.shape(wl))\n x = np.zeros(np.shape(wl))\n y = np.zeros(np.shape(wl))\n q = np.zeros(np.shape(wl))\n\n x = 10000. / wl\n y = 10000. / wl - 1.82\n\n # Far-Ultraviolet: 8 <= x <= 10 ; 1000 -> 1250 Angs\n i = np.bitwise_and(x >= 8, x <= 10)\n\n a[i] = -1.073 - 0.628 * (x[i] - 8.) + 0.137 * (x[i] - 8.)**2 - 0.070 * (x[i] - 8.)**3\n b[i] = 13.670 + 4.257 * (x[i] - 8.) - 0.420 * (x[i] - 8.)**2 + 0.374 * (x[i] - 8.)**3\n\n # Ultraviolet: 3.3 <= x <= 8 ; 1250 -> 3030 Angs\n i = np.bitwise_and(x >= 5.9, x < 8)\n F_a[i] = -0.04473 * (x[i] - 5.9)**2 - 0.009779 * (x[i] - 5.9)**3\n F_b[i] = 0.2130 * (x[i] - 5.9)**2 + 0.1207 * (x[i] - 5.9)**3\n\n i = np.bitwise_and(x >= 3.3, x < 8)\n\n a[i] = 1.752 - 0.316 * x[i] - 0.104 / ((x[i] - 4.67)**2 + 0.341) + F_a[i]\n b[i] = -3.090 + 1.825 * x[i] + 1.206 / ((x[i] - 4.62)**2 + 0.263) + F_b[i]\n\n # Optical/NIR: 1.1 <= x <= 3.3 ; 3030 -> 9091 Angs ;\n i = np.bitwise_and(x >= 1.1, x < 3.3)\n\n a[i] = 1.+ 0.17699 * y[i] - 0.50447 * y[i]**2 - 0.02427 * y[i]**3 + \\\n 0.72085 * y[i]**4 + 0.01979 * y[i]**5 - 0.77530 * y[i]**6 + 0.32999 * y[i]**7\n b[i] = 1.41338 * y[i] + 2.28305 * y[i]**2 + 1.07233 * y[i]**3 - \\\n 5.38434 * y[i]**4 - 0.62251 * y[i]**5 + 5.30260 * y[i]**6 - 2.09002 * y[i]**7\n\n\n # Infrared: 0.3 <= x <= 1.1 ; 9091 -> 33333 Angs ;\n i = np.bitwise_and(x >= 0.3, x < 1.1)\n\n a[i] = 0.574 * x[i]**1.61\n b[i] = -0.527 * x[i]**1.61\n\n q = a + b / R_V\n\n return q", "def qr_householder(A):\r\n s = lambda x: 1 if x >= 0 else -1\r\n\r\n m,n = A.shape\r\n R = A.copy().astype(float)\r\n #create m x m identity matrix\r\n Q = np.eye(m)\r\n for k in range(0,n):\r\n u = R[k:,k].copy().astype(float)\r\n #u[0] will be the first entry of u\r\n u[0] = u[0] + s(u[0]) * la.norm(u)\r\n #normalize u\r\n u = u/la.norm(u)\r\n #apply reflection to R\r\n R[k:,k:] = R[k:,k:] - np.outer(2*u,(u.T@R[k:,k:]))\r\n #apply reflection to Q\r\n Q[k:,:] = Q[k:,:] - np.outer(2*u,(u.T@Q[k:,:]))\r\n return Q.T,R", "def generar_matriz_R(self, tp):\n # modulo del campo en el plano xy\n B1 = np.array([self.Bx, self.By])\n B1 = np.linalg.norm(B1, axis=0)\n\n # tres componentes de la direccion de rotacion. Cada U es un array de\n # n elementos, uno por cada sitio. Uz son ceros porque el campo en z\n # NO excita los spines.\n Ux = self.Bx/B1\n Uy = self.By/B1\n Uz = np.zeros_like(Ux)\n \n angulo = B1*tp\n \n # array de ceros y unos de tamano nx1\n zeros = np.zeros_like(Ux)\n ones = np.ones_like(Ux)\n \n # para definir la matriz uso la formula de Rodrigues:\n # https://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle\n U_matrix = np.array([[ zeros, -Uz , Uy ],\n [ Uz , zeros, -Ux ],\n [-Uy , Ux , zeros]]\n )\n \n Uxy, Uxz, Uyz = [Ux*Uy, Ux*Uz, Uy*Uz]\n U2_matrix = np.array([[Ux*Ux, Uxy , Uxz ],\n [Uxy , Uy*Uy, Uyz ],\n [Uxz , Uyz , Uz*Uz]]\n )\n \n I = np.array([[ones, zeros, zeros], [zeros, ones, zeros], [zeros, zeros, ones]])\n \n R = np.cos(angulo) * I + np.sin(angulo) * U_matrix + (1-np.cos(angulo)) * U2_matrix\n # convierto en array nx3x3\n R = np.moveaxis(R,2,0)\n return R", "def redshift(self):\n return self.radial_velocity.to('', equivalencies=RV_RS_EQUIV)", "def raytrace_new_z(self,ralist,declist,zs_n=1.701):\n ra=np.array(ralist)\n dec=np.array(declist)\n\n out_so = cosmic_D(self.w_m, self.w_l, self.zs_o); D_so = out_so['D_A']\n out_sn = cosmic_D(self.w_m, self.w_l, zs_n); D_sn = out_sn['D_A']\n\n D_A_ls_o = ang_D12(self.w_m, self.w_l, self.zl, self.zs_o) # Angular diameter distance between the lens and the source\n D_A_ls_n = ang_D12(self.w_m, self.w_l, self.zl, zs_n) # Angular diameter distance between the lens and the new redshift plane\n\n theta_x, theta_y = self.wcs_x.world_to_pixel_values(ra, dec)\n\n # theta_x, theta_y: are the pixel poitions in the image plane\n #print(theta_x)\n #print(len(theta_x))\n theta_x = np.asarray(theta_x); theta_y = np.asarray(theta_y)\n\n # alpha_x, alpha_y: are the deflection in the x or y direction (deflection in pixels)\n alpha_x, alpha_y = [], []\n\n for k in range(len(theta_x)):\n a_x = self.x_def[int(theta_y[k]), int(theta_x[k])] * (1.0/3600.0)\n a_y = self.y_def[int(theta_y[k]), int(theta_x[k])] * (1.0/3600.0)\n\n apix_x = a_x / self.pix_scale_x; alpha_x.append(apix_x)\n apix_y = a_y / self.pix_scale_y; alpha_y.append(apix_y)\n\n #a_pix_x = np.asarray(a_pix_x); a_pix_y = np.asarray(a_pix_y)\n alpha_x = np.asarray(alpha_x); alpha_y = np.asarray(alpha_y)\n\n src_px = theta_x - alpha_x * ( (D_A_ls_n/D_sn) / (D_A_ls_o/D_so) )\n src_py = theta_y - alpha_y * ( (D_A_ls_n/D_sn) / (D_A_ls_o/D_so) )\n\n self.src_ra, self.src_dec = self.wcs_x.pixel_to_world_values(src_px, src_py)", "def circularFillet(surfacesurface, positionTolerance=float, curveOnSurface=bool, object=bool, secondaryRadius=\"string\", nodeState=int, tangentTolerance=float, primaryRadius=\"string\", constructionHistory=bool, caching=bool, name=\"string\"):\n pass" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function creates an ray transfer matrix for single prism. You just need to enter k,d,n here, k = cos(a)/cos(b) > You have to calculate this. a = the angle of refraction(in radian) b = the angle of incidence(in radian) d = Prism path length n = Refractive index of the prism material
def sinpri(k, d, n): arr07 = array([ [k, d/(n*k)], [0, 1/k] ], float) print("The ray transfer matrix for a single prism is: ") print(arr07)
[ "def traject(origin0,tetaOrigin0):\r\n\r\n #cf to \"Analytic ray curve tracing for outdoor sound propagation\"\r\n #to understand what follows in this function\r\n #the formulation of the ray traject in the article is true for\r\n #the local orthonormal coordinates (r,h) were h is the axis directed\r\n #by the direction of the gradient.\r\n \r\n x0,z0=origin0\r\n \r\n alpha=norm(x0,z0)\r\n Vorigin0=fV(x0,z0) \r\n correction=gradOrientation(z0)#the local coordinates are oriented according\r\n #to the direction of the gradient of V^-2\r\n #if it is the opposite of the z axis then we will need to inverse the local\r\n #polynome\r\n teta=correction*tetaOrigin0#because changing the coordinates we inverted\r\n #the vertical axis orientation and so we also change angles orientation\r\n\r\n changeSign=np.sign(teta)#to correct a mistake in the\r\n #formula of rf (sign of teta matters for the vertex position)\r\n #In case where teta=0 it does not matter because rf is equal to 0\r\n\r\n\r\n #Now we calculated the local traject with the poly1d class\r\n #to do this I calculated the coefficient a,b,c of the polynom under this form:\r\n #ar^2+br+c\r\n #it appears that c=0 (the polynome pass throught the origin of the local coordinates)\r\n #I developped rf and epsilon to simplify the expression\r\n a=alpha/(4*(np.cos(teta)/Vorigin0)**2)\r\n b=changeSign*(1/np.cos(teta)**2-1)**(1/2)\r\n #In local coordinate it gives\r\n #h=correction*np.poly1d([a,b,0])\r\n #let's define a polynome for global coordinates\r\n #the polynome is Z(r)=h(r-x0)+z0 and by manual calculating we obtain:\r\n Z=correction*np.poly1d([a,b-2*a*x0,correction*z0-b*x0+a*x0**2])\r\n return (Z)", "def refracurvemirror(Re):\n arr06 = array([\n [1, 0],\n [-2/Re, 1]\n ], float)\n print(\"The ray transfer matrix for refraction at a curved mirror is \")\n print(arr06)", "def refflatmirror():\n arr05 = array([\n [1, 0],\n [0, 1]\n ], float)\n print(\"The ray transfer matrix for reflaction in a flat interface is \")\n print(arr05)", "def mulpri(n, B, *k):\n M = 1\n for i in range(n):\n k = float(input(\"Enter the beam expansion factor, k=\", ))\n M = k*M\n\n arr08 = array([\n [M, B],\n [0, 1/M]\n ], float)\n \n print(\"The ray transfer matrix for a multiple prism is: \")\n print(arr08)", "def refraflat(n1 ,n2):\n arr03 = array([\n [1, 0],\n [0, n1/n2]\n ], float)\n print(\"The ray transfer matrix for refraction in a flat interface is \")\n print(arr03)", "def circular_trajectory_3d(geometry):\n rays = np.zeros([geometry.number_of_projections, 3])\n angular_increment = geometry.angular_range / geometry.number_of_projections\n for i in range(geometry.number_of_projections):\n rays[i] = [np.cos(i * angular_increment), np.sin(i * angular_increment),0]\n return rays", "def get_plane_sweep_homographies(K, relative_pose, inv_depths):\n\n homographies = None\n\n \"\"\" YOUR CODE STARTS HERE \"\"\"\n homographies = np.zeros((len(inv_depths), 3, 3))\n\n R = (relative_pose[:, :-1]).reshape((3, 3))\n C = relative_pose[:, -1].reshape((3, 1))\n n_tm = np.array([0, 0, 1]).reshape((1, 3))\n K_inv = np.linalg.inv(K)\n token = (C @ n_tm)\n\n for i, inv_depth in enumerate(inv_depths):\n homographies[i] = K @ (R + (token * inv_depth)) @ K_inv\n\n \"\"\" YOUR CODE ENDS HERE \"\"\"\n\n return homographies", "def get_rays(self, pre_perturb, num_circles=3, resolution=6, wavelength=green):\n # Below, u,v,w will denote local right-handed axis system, with *w*\n # pointing in direction of self.v\n debug = True\n radius = self.radius\n M = self.T.dot(pre_perturb)\n assert M.shape == (4,4), f\"bad shape T={self.T}, pre_perturb={pre_perturb}\"\n rays = []\n pairs = []\n def emit(u,v):\n ray = Ray.of_q_v(point(u,v,0), kk, wavelength=wavelength).transform(M)\n if debug:\n print(f\"emitting {ray.v_q}\")\n rays.append(ray)\n for i in range(0, num_circles+1):\n rays_so_far = len(rays)\n r = radius * (i / num_circles)\n num_points = max(1, resolution * i)\n for theta in np.arange(num_points) * (2 * np.pi / num_points):\n emit(r * np.cos(theta), r * np.sin(theta))\n for i in range(num_points):\n pairs.append((rays_so_far + i, rays_so_far + (i + 1) % num_points))\n # Add a couple more line segments...\n if num_circles >= 1:\n pairs.append((0,1))\n # Let's say we have 1 point in center, 6 points around that, then 12 points\n # around that; we want the 4th point of those 12; so it should have 1 + 6 + (12 / 4)\n # points before it.\n if num_circles >= 2:\n pairs.append((0, 1 + resolution + (resolution // 2)))\n if debug:\n print(f\"pairs={pairs}\")\n print(f\"first few ray points = {[ ray.q() for ray in rays[:3]]}\")\n return rays, pairs", "def arc_to_matrix(vector0, vector1):\n \n vector0 = _setDimension(vector0,2)\n vector1 = _setDimension(vector1,2)\n \n vector0, vector1 = _matchDepth(vector0, vector1)\n \n return _quaternionToMatrix(_vectorArcToQuaternion(vector0, vector1))", "def Vandermonde3D(N, r, s, t):\n\n print 'Np computed as ', ((N+1)*(N+2)*(N+3))//6\n\n V3D = np.zeros((len(r),((N+1)*(N+2)*(N+3))//6))\n\n # Transfer to (a, b) coordinates\n a, b, c = rsttoabc(r, s, t)\n\n # build the Vandermonde matrix\n sk = 0\n\n for i in range(N+1):\n for j in range(N+1-i):\n for k in range(N+1-i-j):\n V3D[:, sk] = Simplex3DP(a, b, c, i, j, k)\n sk = sk+1\n return V3D", "def sector(r,t,nr,nt,h=0.,diag=None):\n r = float(r)\n t = float(t)\n p = Formex(regularGrid([0.,0.,0.],[r,0.,0.],[nr,0,0]).reshape(-1,3))\n if h != 0.:\n p = p.shear(2,0,h/r)\n q = p.rotate(t/nt)\n if diag == 'up':\n F = connect([p,p,q],bias=[0,1,1]) + \\\n connect([p,q,q],bias=[1,2,1])\n elif diag == 'down':\n F = connect([q,p,q],bias=[0,1,1]) + \\\n connect([p,p,q],bias=[1,2,1])\n else:\n F = connect([p,p,q,q],bias=[0,1,1,0])\n\n F = Formex.concatenate([F.rotate(i*t/nt) for i in range(nt)])\n return F", "def get_reflections(r, dr, beads, R_func, Nx, Ny, L):\n\n # Initialize\n r = np.array(r)\n dr = np.array(dr)\n reflected = False\n internal_trajectory = []\n\n def P(i):\n return beads[i, :2]\n\n # Cycle through beads locations\n distances = np.full(Nx * Ny, np.inf)\n for i in range(Nx * Ny):\n reachable, _, distance = get_bead_intersection(r, dr, P(i), R_func(P(i)[0]))\n if reachable:\n distances[i] = distance\n\n # Start with the closest one\n i = np.argmin(distances)\n # print('Dists', distances, i)\n reachable, intersection, distance = get_bead_intersection(r, dr, P(i), R_func(P(i)[0]))\n\n if reachable:\n # calculate the new dr (direction)\n reflected = True\n\n radial_vec = intersection - P(i)\n cos_value = (dr * radial_vec).sum() / norm(dr) / norm(radial_vec)\n\n # Correct for round-off error\n if cos_value > 1:\n cos_value = 1\n elif cos_value < -1:\n cos_value = -1\n\n incidence_angle = np.pi - np.arccos(cos_value) # incidence angle\n # print('acos', dr, radial_vec, (dr * radial_vec).sum() / norm(dr) / norm(radial_vec))\n # print('incidence_angle, grad', incidence_angle / np.pi * 180)\n phi = np.pi - 2 * incidence_angle # rotation angle\n with np.errstate(divide='ignore'):\n reflection_angle = np.pi / 2 + np.arctan(radial_vec[1] / radial_vec[0])\n # print('reflection angle', reflection_angle)\n reflection_matrix = np.array(\n [[np.cos(2 * reflection_angle), np.sin(2 * reflection_angle)], [np.sin(2 * reflection_angle), -np.cos(2 * reflection_angle)]])\n\n dr_before_intersct = intersection - r\n dr_after_intersct = r + dr - intersection\n new_dr_after = reflection_matrix @ dr_after_intersct.transpose()\n # print('a', reflection_matrix, dr_after_intersct.transpose(), new_dr_after)\n internal_trajectory.append([*r, *dr_before_intersct])\n\n # Call function again to check for other reflections\n _, new_r, new_dr_after, internal_trajectory2, _ = get_reflections(\n r=intersection, dr=new_dr_after, beads=beads, R_func=R_func, Nx=Nx, Ny=Ny, L=L)\n # new_r = intersection + new_dr_after\n internal_trajectory += internal_trajectory2\n\n else:\n # Check if reaching the border\n # print('Calling boundary intersection with ', r, dr, L)\n leaving, old_intersection, intersection, new_dr_after = get_boundary_intersection(r, dr, L)\n # print('boundary', r, dr, L, \">>>\", leaving, intersection, new_dr_after)\n\n dr_to_intersection = old_intersection - r\n\n if leaving:\n internal_trajectory.append([*r, *dr_to_intersection])\n _, _, new_dr_after, internal_trajectory2, _ = get_reflections(\n intersection, new_dr_after, beads, R_func, Nx, Ny, L)\n new_r = intersection + new_dr_after\n internal_trajectory += internal_trajectory2\n reflected = True\n # new_dr = new_r - r\n else:\n reflected = False\n intersection = np.nan\n new_r = r + dr\n new_dr_after = dr\n internal_trajectory.append([*r, *dr])\n # new_dr = dr\n dr_after_intersection = new_dr_after\n # print('int', internal_trajectory)\n new_dr = np.asarray(internal_trajectory)[:, 2:4].sum(axis=0)\n # new_dr =\n\n return reflected, new_r, dr_after_intersection, internal_trajectory, new_dr", "def tracePeaceOfRay(origin0,direction0):\r\n\r\n x0,z0=origin0\r\n xd,zd=direction0\r\n validityRange=d(x0,z0)\r\n tetaDirection=np.arctan(zd/xd)#we need an angle to compute the trajectory\r\n Z=traject(origin0,tetaDirection)\r\n x1=limitatingPoint(origin0,validityRange,Z)#x1 is the limitating point by taking\r\n #account of the validity range only\r\n derivatZ=Z.deriv()#to get the new direction we will need to evaluate the\r\n #derivate of the trajectory at the next origin position\r\n reflexion=0\r\n ####first case if there is no possible reflexion on the ground####\r\n \r\n if z0-validityRange>0:#with this condition, it is impossible to encounter\r\n #the ground before de sphere of validity\r\n #so the next point is x1\r\n \r\n deriValue=derivatZ(x1)\r\n direction1=(1,deriValue)#the next direction vector\r\n \r\n z1=Z(x1)\r\n\r\n origin1=x1,z1\r\n \r\n ####second case if there is a potential reflexion####\r\n \r\n else:#we can have a reflexion and we have to determine if it happens or not\r\n reflexionPoints=Z.r #it gives all the roots of the polynome describing\r\n #the peace of ray. In an other way it is all the intersections between \r\n #the peace of ray and the ground\r\n \r\n for xsol in reflexionPoints:#maybe solutions are given in order and we dont need to browse the list\r\n if np.isreal(xsol) and xsol > x0 and xsol<=x1:#there will be reflexion\r\n #on the ground if there is a real intersection point which is\r\n #horizontally after the starting point of the peace of ray but\r\n #before x1 (abscisse of the intersection with the sphere of validity)\r\n x1=xsol.real#x1 is not the intersection with the circle anymore\r\n reflexion=1\r\n \r\n if reflexion:\r\n \r\n deriValue=derivatZ(x1)\r\n direction1=(1,-deriValue)#the new vector of direction need to\r\n #symetric to the normal of the ground\r\n \r\n origin1=x1,10**(-10) #we fix z to 10**-10 because if we don't\r\n #do this, approximations can lead to a wrong reflexion\r\n #we are a little over 0 to evitate that approximation of the solver\r\n #leads to an other reflexion\r\n \r\n \r\n else:\r\n deriValue=derivatZ(x1)\r\n direction1=(1,deriValue)#the next direction vector\r\n\r\n z1=Z(x1)\r\n origin1=x1,z1\r\n \r\n return(origin1,direction1,Z,reflexion)", "def projectionMatrix(n,f,fov,ar):\n\n n = float(n)\n f = float(f)\n\n fov = float(fov)\n ar = float(ar)\n print 'ar', ar\n\n #r = 0.5 * w\n #t = 0.5 * h\n #perspective, w-h\n #return np.asarray([\n # [n/r,0,0,0],\n # [0,n/t,0,0],\n # [0,0,(f+n)/(f-n),-2*f*n/(f-n)],\n # [0,0,1,0]\n # ])\n #orthographic\n# return np.asarray([\n# [1./r,0,0,0],\n# [0,1./t,0,0],\n# [0,0,-2./(f-n),-(f+n)/(f-n)],\n# [0,0,0,1]\n# ])\n #perspective, fov-aspect\n #tan(fov/2) = (1/2)*w / n\n #1 / tan(fov/2) = 2n / w\n return np.asarray([\n [1/(ar*np.tan(fov/2)), 0, 0, 0],\n [0, 1/np.tan(fov/2), 0, 0],\n [0, 0, (f+n)/(f-n), -2*f*n/(f-n)],\n [0, 0, 1, 0]\n ])", "def createPlane(r=0.5, dr=0.1):\r\n bounds = np.array([[-r, -r, 0], [r, r, 0]]) / dr\r\n bounds = np.stack((np.floor(bounds[0]), np.ceil(bounds[1]))) * dr\r\n nx, ny, nz = np.ceil((bounds[1] - bounds[0]) / dr).astype(int)\r\n # print(nx,ny)\r\n xyz = np.reshape([[[[i, j, 0], [i + 1, j, 0], [i, j + 1, 0],\r\n [i, j + 1, 0], [i + 1, j, 0], [i + 1, j + 1, 0]] for i in range(nx - 1)] for j in\r\n range(ny - 1)], (-1, 3))\r\n xyz = (xyz - ((nx - 1) / 2, (ny - 1) / 2, 0)) * dr\r\n # xyz, bounds, (nx, ny, nz) = create_grid(bounds, dr)\r\n # print(nx, ny, nz)\r\n triangles = np.arange(xyz.shape[0]).reshape((-1, 3))\r\n plane = o3d.geometry.TriangleMesh(o3d.utility.Vector3dVector(\r\n xyz), o3d.utility.Vector3iVector(triangles))\r\n # assign checkerboard color pattern\r\n c0 = (0.323, 0.78, 0.321) # first color\r\n c1 = (0.863, 0.62, 0.343) # second color\r\n colors = np.reshape([[np.tile(c0 if (i + j) % 2 else c1, (6, 1)) for i in range(nx - 1)] for j in range(ny - 1)],\r\n (-1, 3))\r\n plane.vertex_colors = o3d.utility.Vector3dVector(colors)\r\n plane.compute_triangle_normals()\r\n return plane", "def cartan_matrix(t):\n t = cartan_type.CartanType(t)\n dynkin_diagram = t.dynkin_diagram()\n index_set = t.index_set()\n MS = MatrixSpace(ZZ, len(index_set), sparse=True)\n m = MS(0)\n for i in range(len(index_set)):\n for j in range(len(index_set)):\n m[i,j] = dynkin_diagram[index_set[i],index_set[j]]\n return m", "def createRays(pts, K_inv):\n # We simply need to multiply per K_inv, this way we get a 3D direction.\n # We can get the points of the ray multiplying the direction with a scalar.\n return [np.matmul(K_inv, p) for p in pts]", "def por_v_raym(data):\n tdata = dc(data)\n\n try:\n vp_b = tdata['vp_b']\n vp_s = tdata['vp_s']\n vp_f = tdata['vp_f']\n except NameError:\n raise\n\n tvp_b = np.array(vp_b, dtype=float, copy=True, ndmin=1)\n\n tvp_b[tvp_b < vp_f] = vp_f\n tvp_b[tvp_b > vp_s] = vp_s\n por_ = (-np.sqrt(4*vp_s*(tvp_b-vp_f)+vp_f**2)+2*vp_s-vp_f)/(2*vp_s)\n por_[por_ < 0.] = 0.\n\n return por_", "def distance(d):\n arr01 = array([\n [1, d],\n [0, 1] \n ], float)\n print(\"The ray transfer matrix for your setup at d distance is\", )\n print(arr01)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function creates an ray transfer matrix for multiple prism. You just need to enter n, B in the bracket. here, n = the number of prism you are using B = the total optical propagation distance of the multiple prism expander After inputing the first two argument in the code, the program will ask you to put the value of k.
def mulpri(n, B, *k): M = 1 for i in range(n): k = float(input("Enter the beam expansion factor, k=", )) M = k*M arr08 = array([ [M, B], [0, 1/M] ], float) print("The ray transfer matrix for a multiple prism is: ") print(arr08)
[ "def sinpri(k, d, n):\n arr07 = array([\n [k, d/(n*k)],\n [0, 1/k]\n ], float)\n print(\"The ray transfer matrix for a single prism is: \")\n print(arr07)", "def generate_k_star_system(n, k):\n dag = np.zeros((n,n))\n r = int(math.ceil(n/k))\n host = 0 \n nodes = np.arange(n)\n np.random.shuffle(nodes)\n\n for i in range(n):\n if i%r == 0:\n host = i\n else:\n #start undirected\n dag[nodes[host], nodes[i]] = 1\n\n return dag", "def generate_parking_mdp(n, distance_rewards, name):\n assert(len(distance_rewards) == n)\n num_actions = 2 # drive, park\n rewards = []\n\n # state organization. always drive from state j to j + 1, clockwise\n for i in range(n - 1, -1, -1): # n - 1, n - 2, ..., 0\n # A[i], unoccupied, unparked = state 4i\n rewards.append(-1) # cost of time passing\n # A[i], occupied, unparked = state 4i + 1\n rewards.append(-1) # cost of time passing\n # A[i], occupied, parked = state 4i + 2\n rewards.append(distance_rewards[i] - 101) # cost of time passing + cost of crash\n # A[i], unoccupied, parked = state 4i + 3\n rewards.append(distance_rewards[i] - 1) # reward for parking + cost of time passing\n for i in range(n): # 0, 1, 2, ..., n - 1\n # B[i], unoccupied, unparked = state 4n + 4i\n rewards.append(-1) # cost of time passing\n # B[i], occupied, unparked = state 4n + 4i + 1\n rewards.append(-1) # cost of time passing\n # B[i], occupied, parked = state 4n + 4i + 2\n rewards.append(distance_rewards[i] - 101) # cost of time passing + cost of crash\n # B[i], unoccupied, parked = state 4n + 4i + 3\n rewards.append(distance_rewards[i] - 1) # reward for parking + cost of time passing\n rewards.append(0) # sink state\n rewards[4 * n - 1] -= 50 # for parking in handicapped A[1]\n rewards[4 * n - 2] -= 50 # for parking in handicapped A[1]\n rewards[4 * n + 2] -= 50 # for parking in handicapped B[1]\n rewards[4 * n + 3] -= 50 # for parking in handicapped B[1]\n b_offset = 4 * n\n\n transitions = [] # transitions[actions][start state][end state]\n\n # initialize all transitions to empty - 8n + 1 states (2n spots * 2 for occupied/not * 2 for parked/not + 1 terminal)\n for a in range(num_actions):\n transitions.append([])\n for i in range((n * 8) + 1):\n transitions[len(transitions) - 1].append([0 for i in range(n * 8 + 1)])\n\n # assign actual values to the transition matrices\n # drive action\n # if state is parked, go to terminal state\n # otherwise, move to next state occupied with p, move to next state unoccupied with p-1 (swapped for B[])\n transitions[0][n * 8][n * 8] = 1.0 # if terminal, stay terminal\n for i in range(n):\n # probability of spot A[i+1] being open, or B[i+1] being taken\n if i == n - 1: # same probability repeated, both top spots are equal\n p = 1.0 / (i + 2.0)\n else:\n p = 1.0 / (i + 3.0)\n\n # row A, higher i = closer\n # transitions from unoccupied, unparked, state 4i\n transitions[0][4 * i][4 * (i + 1)] = p # probability of next spot being open\n transitions[0][4 * i][4 * (i + 1) + 1] = 1.0 - p # probably next spot is occupied\n # transitions from occupied, unparked, state 4i + 1... same as above\n transitions[0][4 * i + 1][4 * (i + 1)] = p # probability of next spot being open\n transitions[0][4 * i + 1][4 * (i + 1) + 1] = 1.0 - p # probably next spot is occupied\n # transitions from parked states always go to terminal state\n transitions[0][4 * i + 2][n * 8] = 1.0\n transitions[0][4 * i + 3][n * 8] = 1.0\n\n # row B, higher i = farther\n if i == n - 1: # last spot, must wrap around\n p = 1.0 / (n - i + 1)\n # transitions from unoccupied, unparked, state 4i\n transitions[0][b_offset + 4 * i][0] = p # probability of next spot being open\n transitions[0][b_offset + 4 * i][1] = 1.0 - p # probably next spot is occupied\n # transitions from occupied, unparked, state 4i + 1... same as above\n transitions[0][b_offset + 4 * i + 1][0] = p # probability of next spot being open\n transitions[0][b_offset + 4 * i + 1][1] = 1.0 - p # probably next spot is occupied\n else:\n p = 1.0 / (n - i)\n # transitions from unoccupied, unparked, state 4i\n transitions[0][b_offset + 4 * i][b_offset + 4 * (i + 1)] = p # probability of next spot being open\n transitions[0][b_offset + 4 * i][b_offset + 4 * (i + 1) + 1] = 1.0 - p # probably next spot is occupied\n # transitions from occupied, unparked, state 4i + 1... same as above\n transitions[0][b_offset + 4 * i + 1][b_offset + 4 * (i + 1)] = p # probability of next spot being open\n transitions[0][b_offset + 4 * i + 1][b_offset + 4 * (i + 1) + 1] = 1.0 - p # probably next spot is occupied\n\n # transitions from parked states always go to terminal state\n transitions[0][b_offset + 4 * i + 2][n * 8] = 1.0\n transitions[0][b_offset + 4 * i + 3][n * 8] = 1.0\n\n # park action\n transitions[1][n * 8][n * 8] = 1.0 # if terminal, stay terminal\n for i in range(n):\n # row A, higher i = closer\n # transitions from unoccupied, unparked, state 4i\n transitions[1][4 * i][4 * i + 3] = 1.0 # parking in unoccupied\n # transitions from occupied, unparked, state 4i + 1... same as above\n transitions[1][4 * i + 1][4 * i + 2] = 1.0 # parking in occupied...ouch\n # transitions from parked states always go to terminal state\n transitions[1][4 * i + 2][n * 8] = 1.0\n transitions[1][4 * i + 3][n * 8] = 1.0\n\n # row B, higher i = farther\n # transitions from unoccupied, unparked, state 4i\n transitions[1][b_offset + 4 * i][b_offset + 4 * i + 3] = 1.0 # parking in unoccupied\n # transitions from occupied, unparked, state 4i + 1... same as above\n transitions[1][b_offset + 4 * i + 1][b_offset + 4 * i + 2] = 1.0 # parking in occupied...ouch\n # transitions from parked states always go to terminal state\n transitions[1][b_offset + 4 * i + 2][n * 8] = 1.0\n transitions[1][b_offset + 4 * i + 3][n * 8] = 1.0\n\n # write everything out to file\n with open(name + \".txt\", \"w\") as out_file:\n out_file.write(str(8 * n + 1) + \"\\n\")\n out_file.write(str(num_actions) + \"\\n\")\n out_file.write(\" \".join([str(x) for x in rewards]))\n out_file.write(\"\\n\")\n for a in range(num_actions):\n out_file.write(\"\\n\".join([\" \".join([str(cell) for cell in line]) for line in transitions[a]]))\n out_file.write(\"\\n\")", "def get_plane_sweep_homographies(K, relative_pose, inv_depths):\n\n homographies = None\n\n \"\"\" YOUR CODE STARTS HERE \"\"\"\n homographies = np.zeros((len(inv_depths), 3, 3))\n\n R = (relative_pose[:, :-1]).reshape((3, 3))\n C = relative_pose[:, -1].reshape((3, 1))\n n_tm = np.array([0, 0, 1]).reshape((1, 3))\n K_inv = np.linalg.inv(K)\n token = (C @ n_tm)\n\n for i, inv_depth in enumerate(inv_depths):\n homographies[i] = K @ (R + (token * inv_depth)) @ K_inv\n\n \"\"\" YOUR CODE ENDS HERE \"\"\"\n\n return homographies", "def build_knn(distances,k):\n\trow,col = distances.shape\n\treturn _lib.build_mst(distances,row,col,eps)", "def refraflat(n1 ,n2):\n arr03 = array([\n [1, 0],\n [0, n1/n2]\n ], float)\n print(\"The ray transfer matrix for refraction in a flat interface is \")\n print(arr03)", "def MultipleScatteringMatrix(self,k):\n return", "def twoSiteGate(self, m, n, tau):\n\n if n < m:\n mpo1 = self._mpo[n][-1, :, :, :]\n mpo2 = self._mpo[m][:, 0, :, :]\n nl = n\n mr = m\n if n > m:\n mpo1 = self._mpo[m][-1, :, :, :]\n mpo2 = self._mpo[n][:, 0, :, :]\n nl = m\n nr = n\n assert (mpo1.shape[0] == mpo2.shape[0])\n d1 = mpo1.shape[1]\n d2 = mpo2.shape[1]\n if nl != 0 and nr != (self._N - 1):\n h = np.kron(mpo1[0, :, :] / 2.0, mpo2[0, :, :])\n for s in range(1, mpo1.shape[0] - 1):\n h += np.kron(mpo1[s, :, :], mpo2[s, :, :])\n h += np.kron(mpo1[-1, :, :], mpo2[-1, :, :] / 2.0)\n\n elif nl != 0 and nr == (self._N - 1):\n h = np.kron(mpo1[0, :, :] / 2.0, mpo2[0, :, :])\n for s in range(1, mpo1.shape[0]):\n h += np.kron(mpo1[s, :, :], mpo2[s, :, :])\n elif nl == 0 and nr != (self._N - 1):\n h = np.kron(mpo1[0, :, :], mpo2[0, :, :])\n for s in range(1, mpo1.shape[0] - 1):\n h += np.kron(mpo1[s, :, :], mpo2[s, :, :])\n h += np.kron(mpo1[-1, :, :], mpo2[-1, :, :] / 2.0)\n Gate = np.reshape(sp.linalg.expm(tau * h), (d1, d2, d1, d2))\n #Gate=np.reshape(np.eye(4),(d1,d2,d1,d2))\n\n return Gate", "def compute_B_matrix(s_data, t_data, s_branches, t_branches):\n\n\tdef compute_branch_mapping_cost(s_branch, t_branch, s_data, t_data):\n\t\t\"\"\" Gets the cost of mapping branch s to branch t. (i.e. Q(s_b, t_b))\n\t\t\tActually no -> It \"knows\" that a branch must be mapped to a certain other branch, i.e. the function\n\t\t\tchecks that the mapping of the two branches has the smallest cost.\n\t\t\tThis must be called at every branch comparison.\n\t\t\"\"\"\n\n\n\t\tdef compute_node_mapping_cost(s_node, t_node, s_branch, t_branch, s_data, t_data):\n\t\t\t\"\"\" Computes the cost of mapping a node of branch_s to a node of branch_t. (i.e. K(s_n, t_n))\n\t\t\t\tThis must be called at every node comparison between two branches.\n\t\t\t\"\"\"\n\n\t\t\t# Set the weight coefficients\n\t\t\ta1 = 1.0\n\t\t\ta2 = 2.0\n\t\t\ta3 = 0.2\n\t\t\ta4 = 1.0\n\t\t\t\n\n\t\t\t# Compute each K\n\t\t\tKpos = get_k_pos(s_node, t_node, s_data, t_data)\n\t\t\tKperc = get_k_perc(s_node, t_node, s_branch, t_branch, s_data, t_data)\n\t\t\tKdeg = get_k_deg(s_node, t_node, s_data, t_data)\n\t\t\tKbet = get_k_bet(s_node, s_data)\n\n\n\t\t\tK = a1*Kpos + a2*Kperc + a3*Kdeg - a4*Kbet\n\t\t\t#print(str(Kpos)+\" \"+str(Kperc)+\" \"+str(Kdeg)+\" \"+str(Kbet))\n\t\t\treturn K\n\n\n\t\tdef find_optimal_nodes(costmatrix, s_branches, t_branches):\n\t\t\t\"\"\" This function gets the minimal value in each row, \n\t\t\t\ti.e. the minimal value for the nodes of the source skeleton to be mapped.\n\t\t\t\"\"\"\n\t\t\tcosts = []\n\t\t\tmapping = []\n\t\t\tinf = float('inf')\n\n\t\t\tprint(s_branches)\n\t\t\tprint(t_branches)\n\t\t\t# print(len(costmatrix))\n\t\t\t# print(len(costmatrix[0]))\n\t\t\tprint(costmatrix)\n\t\t\t# print(len(costmatrix)==len(s_branches))\n\t\t\t# print(len(costmatrix[0]) == len(t_branches))\n\n\t\t\tfor i in range(len(costmatrix)):\n\t\t\t\tmin_cost = inf\n\t\t\t\tsrc = ''\n\t\t\t\tdst = ''\n\t\t\t\tfor j in range(len(costmatrix[0])):\n\t\t\t\t\tif costmatrix[i][j] < min_cost:\n\t\t\t\t\t\tmin_cost = costmatrix[i][j]\n\t\t\t\t\t\tsrc = s_branches[i]\n\t\t\t\t\t\tdst = t_branches[j]\n\t\t\t\tmapping.append([src,dst])\n\t\t\t\tprint([src, dst])\n\t\t\t\tcosts.append(min_cost)\n\n\t\t\ttotal_cost = sum(costs)\n\t\t\t# print(mapping)\n\t\t\treturn mapping, total_cost\n\n\n\n\t\t\n\n\t\t# Initialize the N matrix (containing node mapping costs, within a pair of branches)\n\t\tinf = float('inf')\n\t\tN = [[inf for x in range(len(t_branch))] for x in range(len(s_branch))]\n\n\t\t# Save the cost of mapping a node in the source branch to a node in the target branch, in N\n\t\tfor i in range(len(s_branch)):\n\t\t\tfor j in range(len(t_branch)):\n\t\t\t\ts_n = s_branch[i]\n\t\t\t\tt_n = t_branch[j]\n\t\t\t\tnode_cost = compute_node_mapping_cost(s_n, t_n, s_branch, t_branch, s_data, t_data)\n\t\t\t\tN[i][j] = node_cost\n\n\n\t\t\n\t\tbranch_mapping, branch_cost = find_optimal_nodes(N, s_branch, t_branch)\n\n\t\t# Nnp = np.array(N)\n\n\t\t# min_costs = np.amin(Nnp, axis=1)\n\t\t# sum_costs = np.sum(min_costs)\n\n\t\treturn branch_mapping, branch_cost\n\n\n\n\n\t# Initialize the B matrix (containing branch mapping costs), and another containing node pairs mappings\n\tinf = float('inf')\n\tB_costs = [[inf for x in range(len(t_branches))] for x in range(len(s_branches))]\n\tB_mappings = [[[] for x in range(len(t_branches))] for x in range(len(s_branches))]\n\n\t# Save the cost of mapping a branch in the source to a branch in the target, in B\n\tfor i in range(len(s_branches)):\n\t\tfor j in range(len(t_branches)):\n\t\t\ts_b = s_branches[i]\n\t\t\tt_b = t_branches[j]\n\t\t\tbranch_mapping, branch_cost = compute_branch_mapping_cost(s_b, t_b, s_data, t_data)\n\t\t\tB_costs[i][j] = branch_cost\n\t\t\tB_mappings[i][j] = branch_mapping \n\n\tB_dict = {'costs':B_costs, 'mappings':B_mappings}\n\n\t# Bnp = np.array(B)\n\n\treturn B_dict", "def Vandermonde3D(N, r, s, t):\n\n print 'Np computed as ', ((N+1)*(N+2)*(N+3))//6\n\n V3D = np.zeros((len(r),((N+1)*(N+2)*(N+3))//6))\n\n # Transfer to (a, b) coordinates\n a, b, c = rsttoabc(r, s, t)\n\n # build the Vandermonde matrix\n sk = 0\n\n for i in range(N+1):\n for j in range(N+1-i):\n for k in range(N+1-i-j):\n V3D[:, sk] = Simplex3DP(a, b, c, i, j, k)\n sk = sk+1\n return V3D", "def build_mknn(distances,k):\n\trow,col = distances.shape\n\treturn _lib.build_mst(distances,row,col,eps)", "def TransportMatrix(self,k):\n return", "def rk4_mass_spring_system(amp,omega,k_spr_m,n_balls,t_f,delta_t):\n\n t_steps = int(t_f/delta_t)\n\n t = np.arange(0,t_f,delta_t)\n x = np.empty([n_balls, t_steps])\n v = np.empty([n_balls, t_steps])\n\n #k factors of Runge Kutta 4\n kx = np.empty([4,n_balls])\n kv = np.empty([4,n_balls])\n\n #Initial Conditions\n x[:,0] = 0.0\n v[:,0] = 0.0\n\n #Motion of the 0 mass\n x[0,:] = amp*np.sin(omega*t)*(1-0.5*(np.sign(t-5)+1.0))\n # v[0,:] = omega*amp*np.sin(omega*t)\n\n #Only the proportion between k_spr and m appears, not k_spr or m_b alone\n # k_spr_m = k_spr/m_b\n\n for jt in range(t_steps-1):\n\n #k1 factors\n for n in range(1,n_balls):\n if n <= (n_balls-2):\n kx[0,n] = delta_t*v[n,jt]\n kv[0,n] = delta_t*(k_spr_m)*f_n_in(x[n,jt], x[n+1,jt], x[n-1,jt])\n elif n == (n_balls-1):\n kx[0,n] = delta_t*v[n,jt]\n kv[0,n] = delta_t*(k_spr_m)*f_n_out(x[n,jt], x[n-1,jt])\n\n #k2 factors\n for n in range(1,n_balls):\n if n <= (n_balls-2):\n kx[1,n] = delta_t*(v[n,jt]+kv[0,n])\n kv[1,n] = delta_t* (k_spr_m)*f_n_in(x[n,jt]+0.5*kx[0,n], x[n+1,jt]+0.5*kx[0,n+1], x[n-1,jt]+0.5*kx[0,n-1])\n elif n == (n_balls-1):\n kx[1,n] = delta_t*(v[n,jt]+kv[0,n])\n kv[1,n] = delta_t*(k_spr_m)*f_n_out(x[n,jt]+0.5*kx[0,n], x[n-1,jt]+0.5*kx[0,n-1])\n\n #k3 factors\n for n in range(1,n_balls):\n if n <= (n_balls-2):\n kx[2,n] = delta_t*(v[n,jt]+kv[1,n])\n kv[2,n] = delta_t* (k_spr_m)*f_n_in(x[n,jt]+0.5*kx[1,n], x[n+1,jt]+0.5*kx[1,n+1], x[n-1,jt]+0.5*kx[1,n-1])\n elif n == (n_balls-1):\n kx[2,n] = delta_t*(v[n,jt]+kv[1,n])\n kv[2,n] = delta_t* (k_spr_m)*f_n_out(x[n,jt]+0.5*kx[1,n],x[n-1,jt]+0.5*kx[1,n-1])\n\n #k4 factors\n for n in range(1,n_balls):\n if n <= (n_balls-2):\n kx[3,n] = delta_t*(v[n,jt]+kv[2,n])\n kv[3,n] = delta_t* (k_spr_m)*f_n_in(x[n,jt]+kx[2,n],x[n+1,jt]+0.5*kx[2,n+1],x[n-1,jt]+0.5*kx[2,n-1])\n elif n == (n_balls-1):\n kx[3,n] = delta_t* (v[n,jt]+kv[2,n])\n kv[3,n] = delta_t* (k_spr_m)*f_n_out(x[n,jt]+kx[2,n],x[n-1,jt]+kx[2,n-1])\n\n #next position/velocity\n\n for n in range(1,n_balls):\n x[n,jt+1] = x[n,jt] + (kx[0,n]+2*kx[1,n]+2*kx[2,n]+kx[3,n])/6.0\n v[n,jt+1] = v[n,jt] + (kv[0,n]+2*kv[1,n]+2*kv[2,n]+kv[3,n])/6.0\n\n del(kx,kv,v)\n return t_steps,t,x", "def kstairs(n, k):\n if n == 0:\n return 0\n if n <= k:\n return 2**(n-1)\n return sum([kstairs(n - i, k) for i in range(1, k + 1)])", "def build_B(B_, eq_names, var_names, m, eq_n):\n B_mtrx = init_matrix(m, eq_n)\n s_factor = 1e-4\n\n # Pairs up all equations and components\n for eq_var_pair in range(eq_n - 1):\n B_mtrx[eq_var_pair][eq_var_pair] = B_\n\n B_mtrx[eq_n - 1][eq_n - 1] = B_ * s_factor\n\n return B_mtrx", "def __init__(self, k=K, n=N, mu=0, sigma1=1, sigma2=1):\n\t\tself.k = k\n\t\tself.n = n\n\t\tself._mu = mu\n\t\tself._sigma1 = sigma1\n\t\tself._sigma2 = sigma2\n\t\tself._bandits = [KArmedTestbed(k, mu, sigma1, sigma2) for x in range(k)]\n\n\t\tself._current_state = 0 # start at first state", "def build_filter_bank(k, a, L, N, R):\n \n rotations = np.linspace(0,180,R+1)[:-1]\n\n fbank = np.zeros((len(rotations),N,N))\n kernel = build_kernel(k, a, L, N)\n for i, r in enumerate(rotations):\n fbank[i] = ndimage.rotate(kernel, r, reshape=False, mode='nearest')\n return fbank", "def designMatrix(x, y, k=5):\n \n xb = np.ones((x.size, 1))\n \n for i in range(1, k+1):\n for j in range(i+1):\n xb = np.c_[xb, (x**(i-j))*(y**j)]\n\n xb[:, 0] = 1\n return xb", "def dki_design_matrix(gtab):\n b = gtab.bvals\n bvec = gtab.bvecs\n\n B = np.zeros((len(b), 22))\n B[:, 0] = -b * bvec[:, 0] * bvec[:, 0]\n B[:, 1] = -2 * b * bvec[:, 0] * bvec[:, 1]\n B[:, 2] = -b * bvec[:, 1] * bvec[:, 1]\n B[:, 3] = -2 * b * bvec[:, 0] * bvec[:, 2]\n B[:, 4] = -2 * b * bvec[:, 1] * bvec[:, 2]\n B[:, 5] = -b * bvec[:, 2] * bvec[:, 2]\n B[:, 6] = b * b * bvec[:, 0]**4 / 6\n B[:, 7] = b * b * bvec[:, 1]**4 / 6\n B[:, 8] = b * b * bvec[:, 2]**4 / 6\n B[:, 9] = 4 * b * b * bvec[:, 0]**3 * bvec[:, 1] / 6\n B[:, 10] = 4 * b * b * bvec[:, 0]**3 * bvec[:, 2] / 6\n B[:, 11] = 4 * b * b * bvec[:, 1]**3 * bvec[:, 0] / 6\n B[:, 12] = 4 * b * b * bvec[:, 1]**3 * bvec[:, 2] / 6\n B[:, 13] = 4 * b * b * bvec[:, 2]**3 * bvec[:, 0] / 6\n B[:, 14] = 4 * b * b * bvec[:, 2]**3 * bvec[:, 1] / 6\n B[:, 15] = b * b * bvec[:, 0]**2 * bvec[:, 1]**2\n B[:, 16] = b * b * bvec[:, 0]**2 * bvec[:, 2]**2\n B[:, 17] = b * b * bvec[:, 1]**2 * bvec[:, 2]**2\n B[:, 18] = 2 * b * b * bvec[:, 0]**2 * bvec[:, 1] * bvec[:, 2]\n B[:, 19] = 2 * b * b * bvec[:, 1]**2 * bvec[:, 0] * bvec[:, 2]\n B[:, 20] = 2 * b * b * bvec[:, 2]**2 * bvec[:, 0] * bvec[:, 1]\n B[:, 21] = np.ones(len(b))\n\n return B" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test _SystemWriter utility class
def test_system_writer(self): class BaseWriter(object): def flush(self): return 'flush called' def write_comment(self, comment): return 'write comment ' + comment s = modelcif.dumper._SystemWriter(BaseWriter(), {}, {}) # These methods are not usually called in ordinary operation, but # we should provide them for Writer compatibility self.assertEqual(s.flush(), 'flush called') self.assertEqual(s.write_comment('foo'), 'write comment foo')
[ "def test_generate_global_info(self):\n\t\tassert False, \"Write Test\"", "def write_tool_methods():\n if not os.path.exists(TOOLS_PATH):\n with open(TOOLS_PATH, 'w+'):\n pass\n template_str = 'from ..utils import cfl\\nimport os\\nimport subprocess\\nimport tempfile as tmp\\n\\n'\n template_str += \"BART_PATH=os.environ['TOOLBOX_PATH'] + '/bart'\\n\"\n template_str += \"DEBUG=False\\n\"\n template_str += \"NAME=tmp.NamedTemporaryFile().name\\n\\n\"\n template_str += \"def set_debug(status):\\n\\tglobal DEBUG\\n\\tDEBUG=status\\n\\n\\n\"\n tool_lst = get_tools()[4:]\n for tool in tool_lst:\n template_str += create_template(tool)\n template_str += '\\n\\n'\n template_str = re.sub('\\t', ' ', template_str)\n with open(TOOLS_PATH, 'w+') as f:\n f.write(template_str)", "def test_writeResults(self):\n stringIO = StringIO()\n result = DistReporter(Reporter(stringIO))\n runner = self.getRunner()\n runner.writeResults(result)\n self.assertTrue(stringIO.tell() > 0)", "def testReadWriteFile(self):\n tools = Tools(self.out)\n tools.PrepareOutputDir(None)\n data = 'some context here' * 2\n\n fname = tools.GetOutputFilename('bang')\n tools.WriteFile(fname, data)\n\n # Check that the file looks correct.\n compare = tools.ReadFile(fname)\n self.assertEqual(data, compare)", "def __enter__(self):\n self.tmp_path = super(MockSysCharInterface, self).__enter__()\n self.sys_path = os.path.join(self.tmp_path, 'sys/dev/char')\n self.dev_path = os.path.join(self.tmp_path, 'dev')\n os.makedirs(self.sys_path)\n os.mkdir(self.dev_path)\n for device_type in set(['video', 'other', self.device_basename]):\n for device_id in [str(i) for i in range(5)]:\n path_sym_target = os.path.join(self.sys_path, '../../device',\n device_type, device_id,\n device_type + device_id)\n os.makedirs(os.path.join(path_sym_target, 'device'))\n os.symlink(path_sym_target, os.path.join(self.sys_path,\n device_type+device_id))\n with open(os.path.join(path_sym_target, 'device/uevent'),\n 'w') as file_uevent:\n file_uevent.write(self.uevent_never_match)\n if (device_id == self.device_id\n and device_type == self.device_basename):\n file_uevent.truncate(0)\n file_uevent.write(self.uevent_line)\n with open(os.path.join(self.dev_path, self.device_basename\n + self.device_id), 'w'):\n pass\n return self", "def write_system_info():\n\n # get system information, and write them into the log file\n system, node, release, version, machine, processor = platform.uname()\n\n if system in ['Linux']:\n # find how many physical processers\n p = subprocess.Popen('grep \"physical id\" /proc/cpuinfo|sort|uniq|wc -l',\n shell=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT)\n processor_number = int(p.stdout.readlines()[0])\n\n # find the model name of the processors\n p = subprocess.Popen('grep \"model name\" /proc/cpuinfo|uniq', shell=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT)\n processor = '; '.join([row.decode('utf-8').split(':')[1].strip()\n for row in p.stdout.readlines()])\n\n # find how many cores\n p = subprocess.Popen('grep \"cpu cores\" /proc/cpuinfo|uniq',shell=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT)\n cores = int(p.stdout.readlines()[0].decode('utf-8').split(':')[1])\n\n # get the memory\n p = subprocess.Popen('free -mh',shell=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT)\n row = p.stdout.readlines()[1]\n info = row.split()\n memory = '%s (total); %s (used); %s (free)'%(info[1],info[2],info[3])\n else:\n processor_number = 0\n processor = processor\n cores = 0\n memory = 'Unknown'\n\n\n distribution = ' '.join(platform.dist())\n username = getpass.getuser()\n node = platform.node()\n abspath = os.path.abspath(os.curdir)\n python_version = platform.python_version()\n\n info = ['Start reduction.',\n 'Node: %s'%node,\n 'Processor: %d x %s (%d cores)'%(processor_number, processor, cores),\n 'System: %s %s %s'%(system, release, machine),\n 'Distribution: %s'%distribution,\n 'Memory: %s'%memory,\n 'Username: %s'%username,\n 'Python version: %s'%python_version,\n 'Working directory: %s'%abspath,\n ]\n separator = os.linesep + ' '\n logger.info(separator.join(info))", "def test_cannot_write_file(self):\n self.api.write_data('/some-fake/path/to-create-file/', 'some-string')", "def testOutputDir(self):\n tools = self.tools\n\n # First check basic operation, creating and deleting a tmpdir.\n tools.PrepareOutputDir(None)\n fname = tools.GetOutputFilename('fred')\n tools.WriteFile(fname, 'You are old, Father William, the young man said')\n dirname = tools.outdir\n tools.FinalizeOutputDir()\n self.assertFalse(os.path.exists(fname))\n self.assertFalse(os.path.exists(dirname))\n\n # Try preserving it.\n tools.PrepareOutputDir(None, True)\n fname = tools.GetOutputFilename('fred')\n tools.WriteFile(fname, 'and your hair has become very white')\n dirname = tools.outdir\n tools.FinalizeOutputDir()\n self.assertTrue(os.path.exists(fname))\n self.assertTrue(os.path.exists(dirname))\n shutil.rmtree(dirname)\n\n # Use our own directory, which is always preserved.\n testdir = '/tmp/tools-test.test'\n tools.PrepareOutputDir(testdir)\n fname = tools.GetOutputFilename('fred')\n tools.WriteFile(fname, 'and yet you incessantly stand on your head')\n dirname = tools.outdir\n tools.FinalizeOutputDir()\n self.assertTrue(os.path.exists(fname))\n self.assertTrue(os.path.exists(dirname))\n shutil.rmtree(dirname)\n\n # Try creating an invalid directory.\n testdir = '/sys/cannot/do/this/here'\n self.assertRaises(CmdError, tools.PrepareOutputDir, testdir)\n fname = tools.GetOutputFilename('fred')\n self.assertRaises(IOError, tools.WriteFile, fname,\n 'do you think at your age it is right?')\n dirname = tools.outdir\n tools.FinalizeOutputDir()", "def test_print_2(self):\n writer = StringIO()\n netflix_print(writer, 'abc')\n self.assertEqual(writer.getvalue(), \"abc\\n\")", "def test_write(self):\n reqs = Requirementz.from_lines(TEST_LINES)\n reqs.write(filename=TEST_FILE)", "def testWriteHeader(self):\n expected_header = (\n 'date,time,timezone,MACB,source,sourcetype,type,user,host,short,desc,'\n 'version,filename,inode,notes,format,extra\\n')\n\n self._formatter.WriteHeader()\n\n header = self._output_writer.ReadOutput()\n self.assertEqual(header, expected_header)", "def _write(self, *args, **kwargs):\n raise NotImplementedError('Writing VASP standard streams files is not supported.')", "def test_write():\n\n with open(FILE_DIR+FILE_NAME, mode='w', encoding='utf8')as f:\n f.write(DATA)", "def test_tub_like_driver(self):\n os.makedirs(self.tempfolder)\n meta = [\"location:Here2\", \"task:sometask2\"]\n th = TubHandler(self.tempfolder)\n tub = th.new_tub_writer(inputs=self.inputs, types=self.types, user_meta=meta)\n t2 = Tub(tub.path)\n assert tub.meta == t2.meta\n assert tub.meta['location'] == \"Here2\"\n assert t2.meta['inputs'] == self.inputs\n assert t2.meta['location'] == \"Here2\"", "def test_file_write(self):\n\n args = self.parser.parse_args([self.str_len, '--file', '--raw-output'])\n\n self.randstr_output(args).process_parsed_args()\n output = sys.stdout.getvalue()\n\n filename = os.path.join(self.test_dir, args.file)\n with open(filename, 'r') as f:\n random_string = f.read()\n\n self.assertIn(random_string, output)", "def test_create_writable_protocol():\n f = _WritableFile()\n WeldxFile(f, tree=dict(test=\"yes\"), mode=\"rw\")\n new_file = TestWeldXFile.make_copy(f.to_wrap)\n assert WeldxFile(new_file)[\"test\"] == \"yes\"", "def test_sysconfig_put(self):\n pass", "def test_output_was(self):\n print('Some output')\n self._io.assert_output_was('Some output')\n print('Some more output')\n self._io.assert_output_was('Some more output')", "def test_write_software_tag():\n data = random_data('uint8', (2, 219, 301))\n software = \"test_tifffile.py\"\n with TempFileName('software_tag') as fname:\n imwrite(fname, data, software=software)\n assert_valid(fname)\n with TiffFile(fname) as tif:\n assert len(tif.pages) == 2\n assert tif.pages[0].software == software\n assert 'Software' not in tif.pages[1].tags\n assert__str__(tif)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test ChemCompDumper with invalid value for ccd
def test_chem_comp_dumper_bad_ccd(self): system = modelcif.System() c1 = ihm.NonPolymerChemComp('C1', name='C1') c1.ccd = 'garbage' e1 = modelcif.Entity([c1]) system.entities.append(e1) dumper = modelcif.dumper._ChemCompDumper() self.assertRaises(KeyError, _get_dumper_output, dumper, system)
[ "def test_create_cpd_info():\n\tdf_master = pd.DataFrame(['C([C@@H]1[C@H]([C@@H]([C@H](C(O1)O)O)O)O)O',\n\t\t 'C([C@@H]1[C@@H]([C@@H]([C@H]([C@H](O1)O)O)O)O)O',\n\t\t 'C([C@H]([C@H]([C@@H](C(=O)CO)O)O)O)O',\n\n'C[C@@H]1CC[C@H]2C[C@@H](/C(=C/C=C/C=C/[C@H](C[C@H](C(=O)[C@@H]([C@@H](/C(=C/[C@H](C(=O)C[C@H](OC(=O)[C@@H]3CCCCN3C(=O)C(=O)[C@@]1(O2)O)[C@H](C)C[C@@H]4CC[C@H]([C@@H](C4)OC)O)C)/C)O)OC)C)C)/C)OC']\n, columns=['SMILES'])\n\ttest = cheminform.create_cpd_info(df_master)\n\n\tassert test['n_C'][0] == 6, \"ValueError: Carbon count is incorrect\"\n\tassert test['DoU'][3] == 13, \"ValueError: Degree of Unsaturation in inaccurate\"\n\tassert type(test['MW'][2]) == type(test['n_C'][0]), \"TypeError: MW should be float\"\n\tassert type(test['n_H'][3]) == type(test['n_C'][0]), \"TypeError: All data should be float\"\n\n\treturn '3/3 Tests successful'", "def test_141003_missing(self):\n prod = cliparser(get_file(\"CLIFFC.txt\"))\n self.assertEqual(prod.data[0]['data']['temperature_maximum_normal'],\n 78)", "def test_comp_CDO(self):\n A = 8\n CL = 1\n e = 0.8\n CD = 0.4\n # Got value from a hand computation\n self.assertAlmostEqual(Aircraft.comp_CD0(CL, A, e, CD), 0.3503, places=4)", "def test_cpd_inform():\n\trapamycin = 'C[C@@H]1CC[C@H]2C[C@@H](/C(=C/C=C/C=C/[C@H](C[C@H](C(=O)[C@@H]([C@@H](/C(=C/[C@H](C(=O)C[C@H](OC(=O)[C@@H]3CCCCN3C(=O)C(=O)[C@@]1(O2)O)[C@H](C)C[C@@H]4CC[C@H]([C@@H](C4)OC)O)C)/C)O)OC)C)C)/C)OC'\n\ttest = cheminform.cpd_inform(rapamycin)\n\tassert test[0] == 51, \"Carbon count is incorrect\"\n\tassert test[1] == 79, \"Hydrogen count is incorrect\"\n\tassert type(test[-1]) == type(1.0), \"TypeError: Molecular Weight should be float\"\n\treturn '3/3 Tests successful'", "def test_C_consistency():\n for p in Particle.all():\n if not (p.is_unflavoured_meson and p.three_charge == 0):\n continue\n elif _digit(p.pdgid, Location.N) == 9:\n continue\n elif p.pdgid == 22: # Special case of the photon\n assert p.C == -1\n elif p.pdgid in [130, 310]: # Special case of the KS and KL\n assert p.C == Parity.u\n else:\n assert p.C == (-1) ** (p.L + p.S)", "def testEmptyCCC(self):\n\n emptyCCC = ('<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n'\n '<ColorCorrectionCollection xmlns=\"urn:ASC:CDL:v1.01\">\\n'\n '</ColorCorrectionCollection>')\n\n # Build our ccc\n with tempfile.NamedTemporaryFile(mode='wb', delete=False) as f:\n f.write(enc(emptyCCC))\n self.filename = f.name\n\n self.assertRaises(\n ValueError,\n cdl_convert.parse_ccc,\n self.filename,\n )", "def test_cmakelint_tool_plugin_parse_invalid():\n cmltp = setup_cmakelint_tool_plugin()\n output = \"invalid text\"\n issues = cmltp.parse_output(output)\n assert not issues", "def test_missing_codons():\n\n rv, out = getstatusoutput('{} {}'.format(prg, dna))\n assert rv > 0\n assert re.match(\"usage\", out, re.IGNORECASE)", "def test_no_init(self):\n uninited = cpv.CPV.__new__(cpv.CPV)\n broken = cpv.CPV.__new__(cpv.CPV)\n with pytest.raises(cpv.InvalidCPV):\n broken.__init__(\"broken\", versioned=True)\n for thing in (uninited, broken):\n # the c version returns None, the py version does not have the attr\n getattr(thing, \"cpvstr\", None)\n repr(thing)\n str(thing)\n # The c version returns a constant, the py version raises\n try:\n hash(thing)\n except AttributeError:\n pass", "def test_chemical_composition_trivial(self):\n expected = {'U': 1/3, 'Ag':2/3}\n self.assertDictEqual(self.structure.chemical_composition, expected)", "def test_wrong_ref_power_cqt():\n CQT(file_struct, FeatureTypes.framesync, ref_power=\"caca\")", "def test_repr_value(self):\n self.assertIn(\n repr(self.pdf.pages[0]['Resources']['ColorSpace']['CS0']),\n (\n \"['ICCBased', <IndirectObject(62, 0)>]\",\n \"[u'ICCBased', <IndirectObject(62, 0)>]\",\n ))", "def testBadNotProtein(self):\n bad = (\"string\", CDSPosition.from_anchor(7, -5))\n for arg in bad:\n self.assertRaises(ValueError, cmap.c2p, arg)", "def test_cmmdc():\n assert cmmdc(1, 2) == 1\n assert cmmdc(0, 2) == 2\n assert cmmdc(3, 0) == 3\n assert cmmdc(-10, 100) == 0\n assert cmmdc(-1, -2) == 0\n assert cmmdc(625, 25) == 25\n assert cmmdc(1024, 6) == 2\n assert cmmdc(3, 33) == 3\n assert cmmdc(11, 11) == 11\n assert cmmdc(11, 41) == 1", "def cfcheck(**das):\n return True", "def verify_csdata(self) -> None:", "def test_invalid_spec(self):\n invalid_spec = {\n \"target\": \"abc\",\n \"modes\": 2,\n \"compiler\": [\"Xcov\"],\n }\n with pytest.raises(\n ValueError, match=r\"missing the following keys: \\['gate_parameters', 'layout'\\]\"\n ):\n Device(spec=invalid_spec)", "def test_parse_cpe_name_broken(cpe):\n assert core._parse_cpe_name(cpe) == {}", "def test_show_value_error(self, fake_run_cmd):\n with self.assertRaises(ValueError):\n self.fw.show(table='NoTable')" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }