query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Plot shear profiles This function can be called by either passing in an instance of `GalaxyCluster` or as an attribute of an instance of a `GalaxyCluster` object assuming that that instance has had a shear profile computed and saved as a `.profile` attribute. This function can also be called by passing in `rbins` along with the respective shears. We require at least `rbins` information and `tangential_component` information.
def plot_profiles(cluster=None, rbins=None, tangential_component=None, tangential_component_error=None, cross_component=None, cross_component_error=None, r_units=None, table_name='profile', xscale='linear',yscale='linear'): # If a cluster object was passed, use these arrays if cluster is not None and hasattr(cluster, table_name): cluster_profile = getattr(cluster,table_name) rbins = cluster_profile['radius'] r_units = cluster_profile.meta['bin_units'] if tangential_component != 'gt': ValueError("The function requires a column called 'gt' to run.") if cross_component != 'gx': ValueError("The function requires a column called 'gx' to run.") if 'gt' not in cluster_profile.colnames: ValueError("The function requires a column called 'gt' to run.") if 'gx' not in cluster_profile.colnames: ValueError("The function requires a column called 'gx' to run.") if type(tangential_component)==str: tangential_component = cluster_profile[tangential_component] else: tangential_component = cluster_profile['gt'] try: if type(tangential_component_error)==str: tangential_component_error = cluster_profile[tangential_component_error] else: tangential_component_error = cluster_profile['gt_err'] except: pass try: if type(cross_component)==str: cross_component = cluster_profile[cross_component] else: cross_component = cluster_profile['gx'] except: pass try: if type(cross_component_error)==str: cross_component_error = cluster_profile[cross_component_error] else: cross_component_error = cluster_profile['gx_err'] except: pass # Plot the tangential shears fig, axes = plt.subplots() axes.errorbar(rbins, tangential_component, yerr=tangential_component_error, fmt='bo-', label="Tangential component") # Plot the cross shears try: axes.errorbar(rbins, cross_component, yerr=cross_component_error, fmt='ro-', label="Cross component") except: pass axes.set_xscale(xscale) axes.set_yscale(yscale) axes.legend() axes.set_xlabel(f'Radius [{r_units}]') axes.set_ylabel(r'$\gamma$') return fig, axes
[ "def applyShear(self, *args, **kwargs):\n if len(args) == 1:\n if kwargs:\n raise TypeError(\"Error, gave both unnamed and named arguments to applyShear!\")\n if not isinstance(args[0], galsim.Shear):\n raise TypeError(\"Error, unnamed argument to applyShear is not a Shear!\")\n shear = args[0]\n elif len(args) > 1:\n raise TypeError(\"Error, too many unnamed arguments to applyShear!\")\n else:\n shear = galsim.Shear(**kwargs)\n self.SBProfile.applyShear(shear._shear)\n self.__class__ = GSObject", "def profile_asterix(data, center=None, nprofiles=5, clim=None):\n fig = plt.figure(figsize=(17,11))\n ax1 = fig.add_subplot(121)\n im = plt.imshow(data,cmap=plt.cm.jet)\n cb = plt.colorbar()\n if clim:\n plt.clim(clim)\n plt.xlabel('col #')\n plt.ylabel('row #')\n\n ax2 = fig.add_subplot(122)\n plt.axhline(0,c='k')\n plt.title('profiles')\n plt.ylabel('deformation')\n plt.xlabel('pixel')\n\n nrow, ncol = data.shape\n if center:\n r0, c0 = center\n else:\n r0 = nrow/2\n c0 = ncol/2\n\n #profiles = {}\n #colors = ['b', 'g', 'r', 'c', 'm','y','k']\n slopes = np.linspace(0, np.pi, nprofiles)\n for i,rad in enumerate(slopes[:-1]): #don't repeat 0 & pi\n # Add profile line to interferogram\n #print i, rad, colors[i]\n #special case division by zeros\n if rad == 0: #could also do m=np.inf\n start = (0, r0)\n end = (ncol, r0)\n elif rad == np.pi/2:\n start = (c0, 0)\n end = (c0, nrow)\n else:\n m = np.tan(rad)\n leftIntercept = r0 + m*-c0 #NOTE: imshow takes care of axes flipping automatically!\n rightIntercept = r0 + m*(ncol-c0)\n start = (0, leftIntercept)\n end = (ncol, rightIntercept)\n ax1.plot([start[0],end[0]], [start[1],end[1]], scalex=0, scaley=0)\n\n # Add profile to adjacent plot\n #NOTE: mean, probably more representative\n length = np.floor(np.hypot(start[0]-end[0], start[1]-end[1])) #sample each pixel line passes through\n cols = np.linspace(start[0], end[0]-1, length) #NOTE end-2 to make sure indexing works\n rows = np.linspace(start[1], end[1]-1, length)\n\n # Radial-plot\n radii = np.hypot(cols-c0, rows-r0)\n\n # East Positive (to check for E-W symmetry)\n if rad == np.pi/2: #special case for vertical profile\n radii[np.where(rows>r0)] *= -1\n else:\n radii[np.where(cols<c0)] *= -1\n\n # North Positive\n #if rad == 0:\n # radii[np.where(cols<c0)] *= -1\n #else:\n # radii[np.where(rows>r0)] *= -1\n\n # not sure why there are indexing errors:\n good = (rows <= data.shape[0]) & (cols <= data.shape[1])\n rows = rows[good]\n indrows = rows.astype(np.int)\n cols = cols[good]\n indcols = cols.astype(np.int)\n pPoints = data[indrows, indcols]\n ax2.plot(radii[good], pPoints, marker='.')\n\n #ax1.plot(c0,r0, marker='s', mec='k', mew=2, mfc='none', scalex=0, scaley=0)\n ax1.plot(c0,r0,'ko', ms=2, scalex=0, scaley=0)", "def shear(self, shear, angle=0): \n if not isinstance(shear, (int,float)):\n raise TypeError('shear factor must be numeric')\n if not isinstance(angle, (int,float)):\n raise TypeError('angle must be numeric')\n \n angle = _math.pi*angle/180.\n p = self._localToGlobal(self._reference)\n trans = _Transformation((1.,0.,0.,1.)+p.get())\n rot = _Transformation((_math.cos(angle),_math.sin(angle),\n -_math.sin(angle),_math.cos(angle),0.,0.))\n rotinv = rot.inv()\n sh = _Transformation((1.,-shear,0.,1.,0.,0.))\n \n self._transform = trans*(rotinv*(sh*(rot*(trans.inv()*self._transform))))\n self._objectChanged(True,False,False)", "def plot_shear_force(self, reverse_x=False, reverse_y=False,\n switch_axes=False, fig=None, row=None, col=None):\n\n xlabel = 'Beam Length'\n ylabel = 'Shear Force'\n xunits = self._units['length']\n yunits = self._units['force']\n title = \"Shear Force Plot\"\n color = \"aqua\"\n\n fig = self.plot_analytical(\n 'sf',\n color,\n title,\n xlabel,\n ylabel,\n xunits,\n yunits,\n reverse_x,\n reverse_y,\n switch_axes,\n fig=fig,\n row=row,\n col=col\n )\n\n return fig", "def make_profile(self, z, station_counts):\n\n # figure with multiline\n TOOLS = \"box_zoom, pan, xwheel_zoom, reset, tap\" \n (max_z, min_z), (min_c, max_c) = compute_profile_axis_ranges(z, station_counts)\n p = figure(plot_width=PROFILE_WIDTH, plot_height=PROFILE_HEIGHT, x_range=(min_c,max_c), y_range=(max_z,min_z),\n x_axis_label=PROFILE_X_LABEL, y_axis_label=PROFILE_Y_LABEL, title=PROFILE_TITLE, tools=TOOLS)\n p.title.text_font_size = TITLE_TEXT_SIZE\n p.multi_line(source=self.profile_datasource, xs='cs', ys='zs', line_width=2, line_alpha=0.5,\n line_color=PROFILE_LINE_COLOR, hover_line_alpha=1, hover_line_color=PROFILE_LINE_COLOR)\n\n hover = HoverTool(tooltips=[\n ('depth', '$y m'),\n ('count', '$x'),\n ('species', '@tax[$index]'),\n ('annotation', '@ann[$index]'),\n ])\n\n p.add_tools(hover)\n\n return p", "def plot_wake_profiles(z_H=0.0, save=False, show=False, savedir=\"Figures\",\n quantities=[\"mean_u\", \"k\"], figsize=(7.5, 3.25),\n savetype=\".pdf\", subplots=True, label_subplots=True):\n tow_speeds = np.arange(0.4, 1.3, 0.2)\n cm = plt.cm.coolwarm\n colors = [cm(int(n/4*256)) for n in range(len(tow_speeds))]\n markers = [\"--v\", \"s\", \"<\", \"-o\", \"^\"]\n letters = list(string.ascii_lowercase)[:len(quantities)]\n if subplots:\n fig, ax = plt.subplots(figsize=figsize, nrows=1, ncols=len(quantities))\n else:\n ax = [None]*len(quantities)\n label_subplots = False\n for a, q, letter in zip(ax, quantities, letters):\n if not subplots:\n fig, a = plt.subplots(figsize=figsize)\n for U, marker, color in zip(tow_speeds, markers, colors):\n plot_trans_wake_profile(ax=a, quantity=q, U_infty=U, z_H=z_H,\n marker=marker, color=color)\n if q == quantities[0] or not subplots:\n a.legend(loc=\"lower left\")\n if q == \"mean_upvp\":\n a.set_ylim((-0.015, 0.025))\n fig.tight_layout()\n if label_subplots:\n label_subplot(ax=a, text=\"({})\".format(letter))\n if save and not subplots:\n fig.savefig(os.path.join(savedir, q + \"_profiles\" + savetype))\n if save and subplots:\n fig.savefig(os.path.join(savedir,\n \"_\".join(quantities) + \"_profiles\" + savetype))", "def plot_profile(self):\n\n # Create local variables.\n dp = self.data_point\n dp_scaled = self.data_point_scaled\n ax = self.profile_ax\n\n # Plot the bars representing the feature values.\n ax.barh(dp.index, dp_scaled, alpha=1, color='#E0E0E0', edgecolor='#E0E0E0')\n ax.set_xticklabels([]) # remove x-values\n ax.set_yticklabels([]) # remove y labels (they are in the shap plot)\n ax.set_xlim([0,1.08]) # ensure the scale is always the same, and fits the text (+0.08)\n ax.invert_yaxis() # put first feature at the top\n ax.set_title('These are all the feature values of this profile.', \n loc='left', fontsize=12)\n \n # Add feature value at the end of the bar.\n for i, dp_bar in enumerate(ax.containers[0].get_children()):\n ax.text(dp_bar.get_width()+0.01, dp_bar.get_y()+dp_bar.get_height()/2.,\n '{:.4g}'.format(dp[i]), ha='left', va='center')\n\n # Set local ax back to class ax\n self.profile_ax = ax", "def plot_island_profile(ax, pts_set, MHW, MTL):\n # Get prep values\n tran, idmaxz, maxz, mz_xy, mz_dist, bend, btop = get_beachplot_values(pts_set)\n maxz = maxz+MHW\n btop = btop+MHW\n\n # Axes limits\n xllim = -tran.WidthFull*0.038\n xulim = tran.WidthFull + tran.WidthFull*0.038\n yllim = MTL-0.2\n yulim = maxz++1.25\n\n # Subplot Labels\n ax.set_xlabel('Distance from shore (m)', fontsize = 12)\n ax.set_ylabel('Elevation (m)', fontsize = 12)\n ax.set_title('Island cross-section, transect {:.0f}'.format(tran.sort_ID))\n\n # Plot line\n # ax.plot(pts_set['Dist_Seg'], pts_set['ptZmhw']+MHW, color='gray', linestyle='-', linewidth = 1)\n ax.fill_between(pts_set['Dist_Seg'], pts_set['ptZmhw']+MHW, y2=yllim, facecolor='grey', alpha=0.5)\n plt.annotate('Elevation', xy=(tran.WidthFull-50, float(pts_set['ptZmhw'].tail(1))+0.6), color='gray')\n ax.axvspan(xmin=pts_set['Dist_Seg'].max(), xmax=xulim, color='grey', alpha=0.1)\n plt.annotate('ELEVATION UNKNOWN', xy=(np.mean([pts_set['Dist_Seg'].max(), tran.WidthFull]), np.mean([maxz, MTL])), color='gray')\n\n # #Island widths\n plt.plot([0, tran.WidthPart],[MHW+0.2, MHW+0.2], color='green', linestyle='-', linewidth = 2, alpha=0.5)\n plt.annotate('WidthPart: {:.1f}'.format(tran.WidthPart), xy=(tran.WidthFull*0.83, MHW+0.24), color='green')\n plt.plot([0, tran.WidthFull],[MHW+0.06, MHW+0.06], color='green', linestyle='-', linewidth = 2, alpha=0.5)\n plt.annotate('WidthFull: {:.1f}'.format(tran.WidthFull), xy=(tran.WidthFull*0.83, MHW-0.12), color='green')\n\n # #Beach points\n plt.scatter(tran.DistDL, tran.DL_z, color='orange')\n plt.scatter(tran.DistDH, tran.DH_z, color='red')\n plt.scatter(tran.DistArm, tran.Arm_z, color='black')\n\n # #Upper beach width and height\n plt.plot([MHW, tran.uBW],[MHW, MHW], color='orange', linestyle='-', linewidth = 1.5)\n plt.plot([tran.uBW, tran.uBW],[MHW, MHW + tran.uBH], color='orange', linestyle='-', linewidth = 1.5, marker='|')\n\n # #ax.axis('scaled')\n ax.set_xlim([xllim, xulim])\n ax.set_ylim([yllim, yulim])\n ax.axhspan(ymin=-0.5, ymax=MTL, xmin=xllim, xmax=xulim, alpha=0.2, color='blue')\n plt.annotate('MTL', xy=(-tran.WidthFull*0.02, MTL-0.15), color='blue')\n ax.axhspan(ymin=-0.5, ymax=MHW, xmin=xllim, xmax=xulim, alpha=0.2, color='blue')\n plt.annotate('MHW', xy=(-tran.WidthFull*0.02, MHW-0.15), color='blue', alpha=0.7)", "def _plot_profiles(example_dict, example_indices, plot_shortwave):\n\n heating_rate_matrix_k_day01 = example_utils.get_field_from_dict(\n example_dict=example_dict,\n field_name=\n example_utils.SHORTWAVE_HEATING_RATE_NAME if plot_shortwave\n else example_utils.LONGWAVE_HEATING_RATE_NAME\n )\n\n figure_object = None\n axes_object = None\n\n for i in example_indices:\n this_colour = numpy.random.uniform(low=0., high=1., size=3)\n\n figure_object, axes_object = profile_plotting.plot_one_variable(\n values=heating_rate_matrix_k_day01[i, :],\n heights_m_agl=example_dict[example_utils.HEIGHTS_KEY],\n use_log_scale=True, line_colour=this_colour,\n figure_object=figure_object\n )\n\n axes_object.set_xlabel(r'Heating rate (K day$^{-1}$)')\n\n return figure_object, axes_object", "def Plot_Profile(profile_dataframe, line_color, xmin, xmax, ymin, ymax, aspect, shade):\r\n fig = plt.figure()\r\n \r\n plt.plot(profile_dataframe['Distance'], profile_dataframe['Z'], color = line_color)\r\n \r\n plt.xlabel('Distance (m)')\r\n plt.ylabel('Elevation (m)')\r\n \r\n plt.xlim(0, max(profile_dataframe['Distance']) + 5)\r\n plt.ylim(ymin, ymax)\r\n plt.tight_layout(pad=0)\r\n \r\n plt.gca().spines['right'].set_visible(False)\r\n plt.gca().spines['top'].set_visible(False)\r\n\r\n plt.gca().set_aspect(aspect)\r\n \r\n # This is key to getting the x limits to work with a set aspect ratio!\r\n plt.gca().set_adjustable(\"box\")\r\n \r\n # If statement for shading beneath profile line\r\n if shade:\r\n plt.gca().fill_between(profile_dataframe['Distance'], profile_dataframe['Z'], 0, facecolor= line_color, alpha = 0.1)\r\n \r\n return fig", "def plot_profiles(self, fig=None, figsize=(10, 10), title=None):\n saved_figsize = plt.rcParams['figure.figsize']\n saved_fontsize = plt.rcParams['font.size']\n try:\n if fig is None:\n plt.rcParams['figure.figsize'] = figsize\n plt.rcParams['font.size'] = 10\n fig = plt.figure()\n frame_axes = fig.add_subplot(111, frameon=False)\n if title is None:\n title = os.path.basename(self.fitsfile)\n outcome = \"tearing detected\" if self.has_tearing() else \"no tearing\"\n frame_axes.set_title(title + \": \" + outcome)\n frame_axes.set_xlabel('\\ny-pixel', fontsize=12)\n frame_axes.set_ylabel('ratio of counts for outer two columns\\n\\n',\n fontsize=12)\n frame_axes.get_xaxis().set_ticks([])\n frame_axes.get_yaxis().set_ticks([])\n for amp in self:\n prof1, prof2 = self[amp].ratio_profiles\n ratios1, ratios2 = self[amp].ratios\n stdevs1, stdevs2 = self[amp].stdevs\n ax = fig.add_subplot(4, 4, amp)\n plt.errorbar(range(len(prof1)), prof1, fmt='.', color='green',\n alpha=0.3, label='first edge', zorder=1)\n plt.errorbar(range(len(prof2)), prof2, fmt='.', color='blue',\n alpha=0.3, label='last edge', zorder=1)\n plt.errorbar(self[amp].ylocs, ratios1, yerr=stdevs1,\n xerr=3*[self[amp].dy], fmt='.', color='black',\n zorder=10, markersize=1)\n plt.errorbar(self[amp].ylocs, ratios2, yerr=stdevs2,\n xerr=3*[self[amp].dy], fmt='.', color='black',\n zorder=10, markersize=1)\n ax.annotate('amp %d' % amp, (0.65, 0.9),\n xycoords='axes fraction', fontsize='small')\n plt.tight_layout()\n finally:\n plt.rcParams['figure.figsize'] = saved_figsize\n plt.rcParams['font.size'] = saved_fontsize", "def plot(self, skeleton_data: np.ndarray, ax: plt.Axes, **kwargs) -> None:\n\n skeleton_data = skeleton_data.reshape(-1, 3)\n palm = skeleton_data[self.skeleton['palm']]\n ax.scatter(palm[0], palm[1], palm[2], c=\"g\", s=3)\n\n for p in self.get_skeleton_paths(skeleton_data):\n c = kwargs.get('color', 'b')\n ax.plot(xs=p[:, 0], ys=p[:, 1], zs=p[:, 2], c=c)\n\n ax.view_init(azim=-90.0, elev=-90.0)\n ax.set_xlim(0.0, 1.0)\n ax.set_ylim(0.0, 1.0)\n ax.set_zlim(0.0, 1.0)\n ax.axis('off')\n ax.grid(b=None)", "def profile_swath(data, val, npix=3, ax=0):\n nrow, ncol = data.shape\n fig = plt.figure(figsize=(11,8.5))\n #im = plt.imshow(data, cmap=plt.cm.jet)\n\n if ax == 1:\n plt.axvline(color='gray',linestyle='dashed')\n data = data[:,val-npix:val+npix]\n else:\n plt.axhline(color='gray',linestyle='dashed')\n data = data[val-npix:val+npix,:]\n\n swath_mean = np.mean(data, axis=ax)\n #swath_median = np.median(data, axis=ax)\n swath_std = np.std(data, axis=ax)\n\n ax = fig.add_subplot(111)\n ax.plot(swath_mean, 'k-', lw=2, label='mean')\n ax.plot(swath_mean + swath_std, 'k--', label='+/- 1std')\n ax.plot(swath_mean - swath_std, 'k--')\n\n plt.show()\n\n return swath_mean", "def plot_profiles(self):\n # if 'xportCoef' not in self.data['solpsData']:\n # print('Transport coefficients not yet calculated!! Calculating them using defaults')\n # self.calcXportCoef(plotit = False,debug_plots = False)\n\n headroom = 1.04\n \n # Load SOLPS profiles and transport coefficients\n\n psi_solps = self.data['solpsData']['psiSOLPS']\n neold = self.data['solpsData']['last10']['ne']\n dold = self.data['solpsData']['last10']['dn']\n teold = self.data['solpsData']['last10']['te']\n keold = self.data['solpsData']['last10']['ke']\n tiold = self.data['solpsData']['last10']['ti']\n kiold = self.data['solpsData']['last10']['ki']\n \n # Load experimental profiles\n\n psi_data_fit = self.data['pedData']['fitPsiProf']\n neexp = 1.0e20 * self.data['pedData']['fitProfs']['neprof']\n teexp = 1.0e3*self.data['pedData']['fitProfs']['teprof']\n tiexp = 1.0e3*self.data['pedData']['fitVals']['tisplpsi']['y']\n tiexppsi = self.data['pedData']['fitVals']['tisplpsi']['x']\n\n\n dnew_ratio = self.data['solpsData']['xportCoef']['dnew_ratio']\n kenew_ratio = self.data['solpsData']['xportCoef']['kenew_ratio']\n kinew = self.data['solpsData']['xportCoef']['kinew']\n\n\n # Find limits of Te, Ti for plots\n TS_inds_in_range = np.where(psi_data_fit > np.min(psi_solps))[0]\n Ti_inds_in_range = np.where(tiexppsi > np.min(psi_solps))[0]\n max_ne = np.max([np.max(neold), np.max(neexp[TS_inds_in_range])]) / 1.0e19\n max_Te = np.max([np.max(teold), np.max(teexp[TS_inds_in_range])])\n max_Ti = np.max([np.max(tiold), np.max(tiexp[Ti_inds_in_range])])\n\n\n f, ax = plt.subplots(2, sharex = 'all')\n ax[0].plot(psi_data_fit, neexp / 1.0e19, '--bo', lw = 1, label = 'Experimental Data')\n ax[0].plot(psi_solps, neold / 1.0e19, 'xr', lw = 2, mew=2, ms=8, label = 'SOLPS')\n ax[0].set_ylabel('n$_e$ (10$^{19}$ m$^{-3}$)')\n ax[0].legend(loc = 'best')\n ax[0].set_ylim([0, max_ne * headroom])\n ax[0].grid('on')\n\n # ax[1, 0].plot(psi_solps, dold, '-xr', lw = 2)\n # ax[1, 0].plot(psi_solps, dnew_ratio, '-ok', lw = 2, label = 'Data')\n # ax[1, 0].set_ylabel('D')\n # ax[1, 0].set_xlabel('$\\psi_N$')\n # ax[1, 0].grid('on')\n\n ax[1].plot(psi_data_fit, teexp, '--bo', lw = 1, label = 'Experimental Data')\n ax[1].plot(psi_solps, teold, 'xr', lw = 2, mew=2, ms=8, label = 'SOLPS')\n ax[1].set_ylabel('T$_e$ (eV)')\n ax[1].set_ylim([0, max_Te * headroom])\n ax[1].set_yticks(np.arange(0, max_Te * headroom + 200, 200))\n ax[1].grid('on')\n ax[1].set_xlabel('$\\psi_N$')\n\n # ax[1, 1].plot(psi_solps, keold, '-xr', lw = 2)\n # ax[1, 1].plot(psi_solps, kenew_ratio, '-ok', lw = 2, label = 'Data')\n # ax[1, 1].set_ylabel('$\\chi_e$')\n # ax[1, 1].set_xlabel('$\\psi_N$')\n # ax[1, 1].set_xlim([np.min(psi_solps) - 0.01, np.max(psi_solps) + 0.01])\n # ax[1, 1].grid('on')\n\n # ax[0, 2].plot(psi_solps, tiold, 'xr', lw = 2, label = 'SOLPS')\n # ax[0, 2].plot(tiexppsi, tiexp, '--bo', lw = 1, label = 'Data')\n # ax[0, 2].set_ylabel('T$_i$ (eV)')\n # ax[0, 2].set_ylim([0, max_Ti * headroom])\n # ax[0, 2].grid('on')\n\n # ax[1, 2].plot(psi_solps, kiold, '-xr', lw = 2)\n # ax[1, 2].plot(psi_solps, kinew, '-ok', lw = 2, label = 'Data')\n # ax[1, 2].set_ylabel('$\\chi_i$')\n # ax[1, 2].set_xlabel('$\\psi_N$')\n # ax[1, 2].set_xlim([np.min(psi_solps) - 0.01, np.max(psi_solps) + 0.01])\n # ax[1, 2].grid('on')\n\n ax[0].set_xticks(np.arange(0.84, 1.05, 0.04))\n ax[0].set_xlim([np.min(psi_solps) - 0.01, np.max(psi_solps) + 0.01])\n plt.tight_layout()\n\n plt.show(block = False)", "def plotHistInCluster(axes, clst, spectra_mask, number, hist_params,\n param_list, params, nbins, missing):\n axs_twin = axes.twinx()\n for param in hist_params:\n param_idx = param_list.index(param)\n color = CSS4_COLORS[list(CSS4_COLORS)[param_idx+20]]\n hist_params = params[param_idx][spectra_mask]\n peakname = '_'.join(param.split('_')[:-1])\n parametername = param.split(\"_\")[-1]\n label = peaknames[peakname][parametername]['name'].split(' ')[-1]\n axs_twin.hist(hist_params[hist_params != missing], label=label,\n bins=nbins, histtype='step', color=color)\n axs_twin.yaxis.tick_left()\n axs_twin.tick_params(axis='y', labelsize=7)\n\n axes.yaxis.set_major_locator(MaxNLocator(prune='both', nbins=3))\n axs_twin.yaxis.set_major_locator(MaxNLocator(prune='both', nbins=3,\n integer=True))\n axs_twin.set_ylabel('Spectra')\n axs_twin.yaxis.set_label_position('left')\n axs_twin.text(0.05, 0.85, f'C {number}, {len(clst)} S',\n transform=axes.transAxes, fontsize=8,\n bbox=dict(color='white', alpha=0.75, pad=3))\n __, y_max_val = axs_twin.get_ylim()\n if y_max_val < 1:\n axs_twin.yaxis.set_ticks([])\n axs_twin.set_ylabel('')\n\n return axs_twin", "def shear(self):\r\n return (self.shear_Voigt + self.shear_Reuss) / 2", "def add_shear_z(fit,cov):\n J = np.array([[ 1, 0, 0, 0, 0, 0, 0, 0],\n [ 0, 1, 0, 0, 0, 0, 0, 0],\n [ 0, 0, 1, 0, 0, 0, 0, 0],\n [ 0, 0, 0, 1, 0, 0, 0, 0],\n [ 0, 0, 0, 0, 1, 0, 0, 0],\n [ 0, 0, 0, -1, -1, 0, 0, 0],\n [ 0, 0, 0, 0, 0, 1, 0, 0],\n [ 0, 0, 0, 0, 0, 0, 1, 0],\n [ 0, 0, 0, 0, 0, 0, 0, 1]])\n\n return J.dot(fit), J.dot(cov.dot(J.T))", "def line_profile_update_plot(self):\n\t\tself.rgb_plot.clear()\n\n\t\t# Extract image data from ROI\n\t\tdata, coords = self.roi.getArrayRegion(self.image_array, self.img_item, returnMappedCoords=True)\n\t\tif data is None:\n\t\t\treturn\n\n\t\tif self.ui.vertical_radioButton.isChecked():\n\t\t\tx_values = coords[0,:,0]\n\t\telif self.ui.horizontal_radioButton.isChecked():\n\t\t\tx_values = coords[1,0,:]\n\n\t\tif self.ui.pixera_radioButton.isChecked() or (self.ui.spot_radioButton.isChecked() and not self.ui.resize_image_checkBox.isChecked()):\n\t\t\tx_values = x_values * self.scaling_factor\n\t\t\n\t\t#calculate average along columns in region\n\t\tif len(data.shape) <= 2: #if grayscale, average intensities \n\t\t\tif self.ui.vertical_radioButton.isChecked():\n\t\t\t\tavg_to_plot = np.mean(data, axis=-1)\n\t\t\telif self.ui.horizontal_radioButton.isChecked():\n\t\t\t\tavg_to_plot = np.mean(data, axis=0)\n\t\t\ttry:\n\t\t\t\tself.rgb_plot.plot(x_values, avg_to_plot)\n\t\t\texcept:\n\t\t\t\tpass\n\t\telif len(data.shape) > 2: #if rgb arrays, plot individual components\n\t\t\tr_values = data[:,:,0]\n\t\t\tg_values = data[:,:,1]\n\t\t\tb_values = data[:,:,2]\n\t\t\tif self.ui.vertical_radioButton.isChecked():\n\t\t\t\tr_avg = np.mean(r_values, axis=-1) #average red values across columns\n\t\t\t\tg_avg = np.mean(g_values, axis=-1) #average green values\n\t\t\t\tb_avg = np.mean(b_values, axis=-1) #average blue values\n\t\t\telif self.ui.horizontal_radioButton.isChecked():\n\t\t\t\tr_avg = np.mean(r_values, axis=0)\n\t\t\t\tg_avg = np.mean(g_values, axis=0)\n\t\t\t\tb_avg = np.mean(b_values, axis=0)\n\t\t\ttry:\n\t\t\t\tself.rgb_plot.plot(x_values, r_avg, pen='r')\n\t\t\t\tself.rgb_plot.plot(x_values, g_avg, pen='g')\n\t\t\t\tself.rgb_plot.plot(x_values, b_avg, pen='b')\n\t\t\texcept Exception as e:\n\t\t\t\tpass", "def _plot_hess(self, synth_path, plot_path, name, cmd,\n log_age=None, z=None,\n format=\"png\", dpi=300,\n figsize=(4, 4), aspect='auto'):\n fig = Figure(figsize=figsize)\n canvas = FigureCanvas(fig)\n gs = gridspec.GridSpec(1, 1,\n left=0.17, right=0.95, bottom=0.15, top=0.95,\n wspace=None, hspace=None,\n width_ratios=None, height_ratios=None)\n ax = fig.add_subplot(gs[0])\n plot_synth_hess(ax, synth_path, cmd,\n log_age=log_age, z=z)\n gs.tight_layout(fig, pad=1.08, h_pad=None, w_pad=None, rect=None)\n canvas.print_figure(plot_path + \".\" + format, format=format, dpi=dpi)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
names/quotes are list of tuples of indices of names & quotes
def removeNamesInQuotes(names,quotes): for quote in Expand(quotes): for name in Expand(names): for i in name: if i in quote: names.remove((name[0],name[-1])) break return names
[ "def quote_names(self):\n return \"\"\"--quote-names\"\"\"", "def quoted_terms(term_list):\n return [MULTIWORD_PAT.sub(r'\"\\1 \\2\"', t) for t in term_list]", "def process_names(raw_names):\n names = []\n for name in raw_names:\n name = name.lower()\n if ' ' in name:\n name = '0'.join(name.split())\n if '-' in name:\n name = '1'.join(name.split('-'))\n name += '2'\n names.append(name)\n return names", "def getTaxid(namelist): \n accessid = []\n for i in namelist:\n name2taxid = ncbi.get_name_translator([i])\n if name2taxid == {}:\n print(\"Wrong Taxon name: \" + i + \"!\")\n exit()\n return\n else:\n accessid.append(name2taxid)\n return accessid", "def parse_name_ancestris(record):\n name_tuple = split_name(record.value)\n return name_tuple", "def get_name_indices(self, names: Sequence[str]):\n order_dict = dict()\n for i, v in enumerate(self.channel_names):\n order_dict.update({v: i})\n return [order_dict[n] for n in names]", "def generate_names(args):\n index = 0\n for _, decl in args:\n index += 1\n yield decl.name or 'arg{0}'.format(index)", "def ArgumentNames(self) -> _n_2_t_0[str]:", "def get_named_ent_txts_2(raw_texts):\n named_ent_txts_2 = []\n for text in raw_texts:\n curr_named_ent = get_named_entities_2(text)\n text_to_append = nltk.Text(curr_named_ent)\n named_ent_txts_2.append(text_to_append)\n return named_ent_txts_2", "def sorted(self, names: tuple or list or 'Shape') -> Tuple[str]:\n names: Tuple[str] = names.names if isinstance(names, Shape) else names\n positions = {}\n pos = 0\n for name in names:\n if name in self.names:\n pos = self.index(name)\n positions[name] = pos\n return tuple(sorted(names, key=lambda n: positions[n]))", "def _quote_free_identifiers(self, *ids):\n return tuple([self.quote_identifier(i) for i in ids if i is not None])", "def get_named_ent_txts_1(raw_texts):\n named_ent_txts_1 = []\n for text in raw_texts:\n curr_named_ent = get_named_entities_1(text, types_included_1)\n text_to_append = nltk.Text(curr_named_ent)\n named_ent_txts_1.append(text_to_append)\n return named_ent_txts_1", "def genenames_from10x(genelist):\n genesymbol=[]\n #ensemblid=[]\n for i in range(len(genelist)):\n curgene=genelist[i]\n starts=[]\n for x in re.finditer('_',curgene):\n starts.append(x.start()+1)\n genesymbol.append(curgene[starts[-1]:])\n \n return genesymbol#,ensemblid", "def genenames_from10x_mod(genelist):\n genesymbol=[]\n #ensemblid=[]\n for i in range(len(genelist)):\n curgene=genelist[i]\n starts=[]\n for x in re.finditer('_',curgene):\n starts.append(x.start()+1)\n genesymbol.append(curgene[starts[0]:])\n \n return genesymbol#,ensemblid", "def name_in_order(names):\n bruno_pos = 0\n mars_pos = 0\n for i in range(len(names)):\n \tif names[i]=='Bruno':\n \t\tbruno_pos = i\n \t\tfor j in range(len(names)-i):\n \t\t\tif names[i+j]=='Mars':\n \t\t\t\tmars_pos = i+j\n \t\t\t\tif names[i+1]!='Mars':\n \t\t\t\t\ttemp = names[i+1]\n \t\t\t\t\tnames[i+1] = names[j+i]\n \t\t\t\t\tnames[j+i] = temp\n \t\t\t\t\t\n return names", "def get_header(hdr_tuples, name):\n # TODO: support quoted strings\n return [v.strip() for v in sum(\n [l.split(',') for l in\n [i[1] for i in hdr_tuples if i[0].lower() == name]\n ]\n , [])\n ]", "def get_names_c(self):\n names=['\"'+f.get_name()+'\"' for f in self.fields]\n names = '{' + ','.join(names)+'}'\n return names", "def test_parse_token_multi_element_name(self):\n\n # Parse the token.\n list = parse_token('N,CA')\n\n # Check the list elements.\n self.assertEqual(len(list), 2)\n self.assertEqual(list[0], 'N')\n self.assertEqual(list[1], 'CA')", "def expandAcronym(acronymDict, tokens, POStags):\n newTweet = []\n newToken = []\n count = 0\n for i in range(len(tokens)):\n # word = tokens[i].lower().strip(specialChar)\n word = tokens[i].lower()\n if word:\n if word in acronymDict:\n count += 1\n newTweet += acronymDict[word][0]\n newToken += acronymDict[word][1]\n\n else:\n newTweet += [tokens[i]]\n newToken += [POStags[i]]\n return newToken,newTweet, count\n # return tokens, POStags, count" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case verifies that the task add form page loads with expected fields if the user is authenticated
def test_add_task_form(self): # Issue a GET request logged_out_response = self.client.get(reverse("check_mate:task_add")) # Confirm that the response does not have any content self.assertFalse(logged_out_response.content) # Confirm that the user is redirected to the login page if they are not authenticated self.assertEqual(logged_out_response.status_code, 302) # Log the user in self.client.login(username="test_user", password="secret") # TODO: Figure out how to pass ticket information in the form # TODO: Write check for response content once final styling and formatting is added
[ "def test_add_task(self):\n\n # Log the user in\n self.client.login(username=\"test_user\", password=\"secret\")\n\n # Issue a POST request with a new task\n response = self.client.post(reverse(\"check_mate:task_add\"), {\"task_name\": \"New Task\", \"task_description\": \"Test task\", \"task_status\": \"Not Started\", \"task_due\": \"2019-05-02\", \"ticket\": \"1\", \"task_assigned_user\": \"1\"})\n\n # Confirm that the response redirects to the ticket detail page\n self.assertEqual(response.status_code, 302)\n\n # TODO: Add test for submitting incorrect or incomplete data\n\n # TODO: Check content on ticket detail page to ensure that new task is listed", "def test_edit_task_form(self):\n\n # Issue a GET request\n logged_out_response = self.client.get(reverse(\"check_mate:task_edit\", args=(1,)))\n\n # Confirm that the response does not have associated content\n self.assertFalse(logged_out_response.content)\n\n # Confirm that the user is redirected to the login page if they are not authenticated\n self.assertEqual(logged_out_response.status_code, 302)\n\n # Log the user in\n self.client.login(username=\"test_user\", password=\"secret\")\n\n # Issue a GET request\n response = self.client.get(reverse(\"check_mate:task_edit\", args=(1,)))\n\n # Confirm that the response is 200\n self.assertEqual(response.status_code, 200)\n\n # TODO: Write check for the response content once final styling and formatting is added", "def test_add_plant_page_logged_in(self):\n\n result = self.client.get(\"/addplant\")\n self.assertEqual(result.status_code, 200)\n self.assertIn(b\"part shade\", result.data)\n self.assertNotIn(b\"Login\", result.data)\n self.assertIn(b\"Logout\", result.data)", "def test_submit_create_form_valid(self, **kwargs):\n self.app.set_user(TESTUSER_EMAIL)\n create_page = self.app.get(reverse('user_as_add'))\n self._fill_form(create_page.form, **kwargs)\n response = create_page.form.submit()\n\n user_as = UserAS.objects.filter(owner=get_testuser()).last()\n self.assertEqual(response.status_code, 302)\n self.assertEqual(response.location,\n reverse('user_as_detail', kwargs={'pk': user_as.pk}))\n self.assertEqual(response.follow().status_code, 200)\n\n # submit the form again, forwards to the next AS:\n response_2 = create_page.form.submit()\n user_as_2 = UserAS.objects.filter(owner=get_testuser()).last()\n self.assertEqual(response_2.status_code, 302)\n self.assertEqual(response_2.location,\n reverse('user_as_detail', kwargs={'pk': user_as_2.pk}))\n self.assertEqual(response_2.follow().status_code, 200)", "def test_project_form_fields_required(self, mock_tas_get_user, mock_tas_fields):\n with open(\"projects/test_fixtures/fields.json\") as f:\n mock_tas_fields.return_value = json.loads(f.read())\n\n with open(\"projects/test_fixtures/user.json\") as f:\n mock_tas_get_user.return_value = json.loads(f.read())\n\n self.client.login(username=\"jdoe1\", password=\"password\")\n response = self.client.get(reverse(\"projects:create_project\"))\n\n self.assertContains(\n response,\n '<textarea class=\"form-control\" cols=\"40\" id=\"id_justification\" '\n 'name=\"justification\" placeholder=\"Resource Justification\" '\n 'required=\"required\" rows=\"10\" title=\"Provide supplemental detail on how you '\n \"intend to use Chameleon to accomplish your research goals. This text will \"\n \"not be publicly viewable and may include details that you do not wish to \"\n 'publish.\">',\n )", "def test_show_add_post_form(self):\n with app.test_client() as client:\n resp = client.get(f'/users/{self.user1_id}/posts/new')\n html = resp.get_data(as_text=True)\n\n self.assertEqual(resp.status_code, 200)\n self.assertIn('<h1>Add Post for', html)", "def test_new_submit_logged_in_required(self):\n\n # login to the website\n self.utils.account.login_as(self.username,self.password)\n\n po = self.catalog.load_pageobject('SupportTicketNewPage')\n po.goto_page()\n\n # name, email and description are required\n data = {\n 'name' : self.username,\n 'email' : 'hubchecktest@hubzero.org',\n 'problem' : \"hubcheck test ticket\\n%s\" % (self.fnbase),\n }\n\n # submit the ticket\n po.submit_ticket(data)\n\n po = self.catalog.load_pageobject('SupportTicketSavePage')\n self.ticket_number = po.get_ticket_number()\n\n info = po.get_error_info()\n assert len(info) == 0, \"received unexpected error: %s\" % (info)\n assert self.ticket_number is not None, \"no ticket number returned\"\n assert int(self.ticket_number) > 0, \\\n \"invalid ticket number returned: %s\" % (self.ticket_number)", "def test_access_new_user_form(self):\r\n with self.client as client:\r\n \r\n response = client.get('/users/new')\r\n html = response.get_data(as_text=True)\r\n \r\n self.assertIn('id=\"create-user\"', html)", "def test_form_page_view(self):\n\n # if user is not authenticate\n response = self.client.get(reverse('hello:contact_form'))\n self.assertEqual(response.status_code, 302)\n\n # after authentication\n self.client.login(username='admin', password='admin')\n response = self.client.get(reverse('hello:contact_form'))\n self.assertTemplateUsed(response, 'contact_form.html')\n self.assertIn(self.contact.name, response.content)\n self.assertIn(self.contact.surname, response.content)\n self.assertIn(self.contact.date_of_birth.strftime('%Y-%m-%d'),\n response.content)\n self.assertIn(self.contact.email, response.content)\n self.assertIn(self.contact.jabber, response.content)", "def test_web_task_edit_status_to_in_progress(\n webapp, new_user, new_task_done_three_tags\n):\n webapp.homepage()\n webapp.sign_in(new_user.username, new_user.password)\n task = webapp.taskboard.find_task(new_task_done_three_tags.title)\n assert task.done is True\n task.edit(done=False)\n assert task.done is False", "def test_api_create_task_requires_auth(self):\n\n self.assertEqual(\n reverse('select_template_api:select_template_create'), '/api/select-template/')\n\n response = self.client.post(\n reverse('select_template_api:select_template_create'),\n self.template_task_data,\n format=\"json\"\n )\n self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)", "def test_show_form_errors(self):\n self.prep_test()\n response = self.client.post(reverse('recommend-enroll'), {\n 'first_name': '', 'last_name': '', 'email': '', \n 'consumer_zip_postal': '1', 'primary_phone_number': '1',\n 'password1': '1', 'password2': '1', 'ad_rep_url': '',\n 'terms_of_use': False})\n self.assert_test_get(response)\n self.assertContains(response, 'enter a valid email')\n self.assertContains(response, \"Passwords must contain at least 6\")\n self.assertContains(response, \"10 digit phone number\")\n self.assertContains(response, \"Please choose a website name\")\n self.assertContains(response, \"agree to the three documents listed\")", "def test_success_todo_details(self):\n self.login()\n\n response = self.client.get(url_for('alaya_todo.todo', id=get_max_todo_id(), page=1))\n self.assert200(response, 'The todo details page must return a 200 HTTP Code.')\n self.assertTemplateUsed('todo.html')\n\n self.logout()", "def test_department_form(self):\r\n\r\n response = self.client.get(reverse('agileHR:departmentadd'))\r\n\r\n # verify that the content of the response has the required input fields.\r\n self.assertIn('input type=\"text\" name=\"dept_name\" class=\"form-control\"'.encode(), response.content)\r\n self.assertIn('<input type=\"number\" name=\"dept_budget\" class=\"form-control\"'.encode(), response.content)", "def test_new_post_form(self):\n with app.test_client() as client:\n res = client.get(f\"/users/{self.user_id}/posts/new\")\n user = User.query.filter_by(id=self.user_id).first()\n fname = user.first_name\n lname = user.last_name\n html = res.get_data(as_text=True)\n\n self.assertEqual(res.status_code, 200)\n self.assertIn(f\"<h1>Add Post for {fname} {lname}\", html)", "def test_web_task_edit_option_only_for_own_tasks(\n webapp, new_user, new_task, new_task_default_user\n):\n webapp.homepage()\n webapp.sign_in(new_user.username, new_user.password)\n for task in webapp.taskboard.tasks():\n assert (\"edit\" in task.options) == (task.owner == new_user.username)", "def test_UserFormViewPermissionForSelf(self):\n response = self.app.get(\n reverse('employees:UserFormView', args=['regular.user']),\n headers={'X_AUTH_USER': 'regular.user@gsa.gov'}\n )\n self.assertEqual(response.status_code, 200)\n # Check that inital data for UserDate Populates\n self.assertEqual(\n response.html.find('input', {'id': 'id_start_date'})['value'],\n '2014-01-01')\n self.assertEqual(\n response.html.find('input', {'id': 'id_end_date'})['value'],\n '2016-01-01')", "def test_api_create_task_with_auth(self):\n\n tasks_before = SelectTemplateTask.objects.count()\n\n create_response = self.submit_default_task_with_auth()\n\n LOG.info(\"create.response.json: %s\", create_response.json())\n\n json_data = create_response.json()\n self.assertIn('uuid', json_data)\n task_uuid = json_data['uuid']\n\n tasks_after = SelectTemplateTask.objects.count()\n\n self.assertEqual(tasks_after, tasks_before + 1)\n\n task_from_db = SelectTemplateTask.objects.get(uuid=task_uuid)\n\n self.assertEqual(task_from_db.query_sequence,\n self.template_task_data['query_sequence'])\n\n self.assertEqual(create_response.status_code, status.HTTP_201_CREATED)", "def test_testform(self):\n response = self.client.get(reverse(\"foods:testform\"))\n self.assertEqual(response.status_code, 200)\n self.assertIn(\"form\", response.context)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case verifies that you can add a new task and it successfully saves
def test_add_task(self): # Log the user in self.client.login(username="test_user", password="secret") # Issue a POST request with a new task response = self.client.post(reverse("check_mate:task_add"), {"task_name": "New Task", "task_description": "Test task", "task_status": "Not Started", "task_due": "2019-05-02", "ticket": "1", "task_assigned_user": "1"}) # Confirm that the response redirects to the ticket detail page self.assertEqual(response.status_code, 302) # TODO: Add test for submitting incorrect or incomplete data # TODO: Check content on ticket detail page to ensure that new task is listed
[ "def test_add_task(self):\n\n\t\texisting = Task({'id': 1})\n\t\tnew = Task({'name': 'new'})\n\n\t\tproject = Project({'id': 2, 'workspace': {'id': 3}})\n\n\t\tproject.add_task(existing)\n\n\t\tself.assertIn(\n\t\t\t('post', 'tasks/1/addProject', {'data': {'project': 2}}),\n\t\t\tself.api.requests\n\t\t)\n\n\t\tproject.add_task(new)\n\n\t\tself.assertIn(\n\t\t\t('post', 'tasks', {'data': {'projects': [2], 'name': 'new', 'workspace': 3}}),\n\t\t\tself.api.requests\n\t\t)", "def test_create_task():\n response = client.post(\n '/task/',\n json={\n 'description': 'Some description',\n 'completed': False\n })\n assert response.status_code == 200", "def test_duplicate_task(self):\n pass", "def test_success_todo_create(self):\n self.login()\n\n task_description = \"A new task\"\n response = self.client.post('/todo/', data=dict(description=task_description))\n\n self.assertRedirectTarget(response, '/todo?page=1', redirect_message='The request must be redirect to /todo.')\n self.assertMessageFlashed('The task \"{}\" has been successfully added.'.format(task_description))\n\n todo_id = get_max_todo_id()\n todo = load_todo(todo_id)\n\n self.assertEqual(task_description, todo.description, 'The description must be equals.')\n\n delete_todo(todo_id)\n\n self.logout()", "def test_create_subtask_for_task(self):\n pass", "def test_add_project_for_task(self):\n pass", "def test_terminal_v1_tasks_create(self):\n pass", "def test_api_create_task_with_auth(self):\n\n tasks_before = SelectTemplateTask.objects.count()\n\n create_response = self.submit_default_task_with_auth()\n\n LOG.info(\"create.response.json: %s\", create_response.json())\n\n json_data = create_response.json()\n self.assertIn('uuid', json_data)\n task_uuid = json_data['uuid']\n\n tasks_after = SelectTemplateTask.objects.count()\n\n self.assertEqual(tasks_after, tasks_before + 1)\n\n task_from_db = SelectTemplateTask.objects.get(uuid=task_uuid)\n\n self.assertEqual(task_from_db.query_sequence,\n self.template_task_data['query_sequence'])\n\n self.assertEqual(create_response.status_code, status.HTTP_201_CREATED)", "def test_create_todo_item(client):\n resp = client.post(f\"{URL_PREFIX}/todo\", json={\n \"task\": \"Test sample task\",\n \"is_pending\": \"Yes\"\n })\n assert 201 == resp.status_code\n json_data = resp.get_json()\n assert \"Successfully created the todo\" in json_data[\"message\"]", "def test_create_report_task(self):\n pass", "def testPostSubmitWork(self):\n self.data.createStudent()\n\n self.task.status = 'Claimed'\n self.task.student = self.data.profile\n # set deadline to far future\n self.task.deadline = datetime.datetime.utcnow() + datetime.timedelta(days=1)\n self.task.put()\n\n no_work = self.task.workSubmissions()\n self.assertLength(no_work, 0)\n\n work_url = 'http://www.example.com/'\n work_data = {\n 'url_to_work': work_url\n }\n\n url = '%s?submit_work' %self._taskPageUrl(self.task)\n response = self.post(url, work_data)\n\n self.assertResponseRedirect(response)\n\n one_work = self.task.workSubmissions()\n self.assertLength(one_work, 1)\n\n work = one_work[0]\n self.assertEqual(work_url, work.url_to_work)", "def test_api_v3_stories_story_public_id_tasks_post(self):\n pass", "def test_add_task_form(self):\n\n # Issue a GET request\n logged_out_response = self.client.get(reverse(\"check_mate:task_add\"))\n\n # Confirm that the response does not have any content\n self.assertFalse(logged_out_response.content)\n\n # Confirm that the user is redirected to the login page if they are not authenticated\n self.assertEqual(logged_out_response.status_code, 302)\n\n # Log the user in\n self.client.login(username=\"test_user\", password=\"secret\")\n\n # TODO: Figure out how to pass ticket information in the form\n # TODO: Write check for response content once final styling and formatting is added", "def test_api_v3_stories_story_public_id_tasks_task_public_id_put(self):\n pass", "def test_web_task_edit_status_to_done(webapp, new_user, new_task):\n webapp.homepage()\n webapp.sign_in(new_user.username, new_user.password)\n task = webapp.taskboard.find_task(new_task.title)\n assert task.done is False\n task.edit(done=True)\n assert task.done is True", "def test_web_task_edit_status_to_in_progress(\n webapp, new_user, new_task_done_three_tags\n):\n webapp.homepage()\n webapp.sign_in(new_user.username, new_user.password)\n task = webapp.taskboard.find_task(new_task_done_three_tags.title)\n assert task.done is True\n task.edit(done=False)\n assert task.done is False", "def test_todo_creation(self):\n res = self.client().post('/todos/', data=self.todo)\n self.assertEqual(res.status_code, 201)\n self.assertIn('Go to Borabora', str(res.data))", "def test_subtask_process(self):\n Task = self.env['services.task'].with_context({'tracking_disable': True})\n parent_task = Task.create({\n 'name': 'Mother Task',\n 'user_id': self.user_servicesuser.id,\n 'services_id': self.services_pigs.id,\n 'partner_id': self.partner_2.id,\n 'planned_hours': 12,\n })\n child_task = Task.create({\n 'name': 'Task Child',\n 'parent_id': parent_task.id,\n 'services_id': self.services_pigs.id,\n 'planned_hours': 3,\n })\n\n self.assertEqual(parent_task.partner_id, child_task.partner_id, \"Subtask should have the same partner than its parent\")\n self.assertEqual(parent_task.subtask_count, 1, \"Parent task should have 1 child\")\n self.assertEqual(parent_task.subtask_planned_hours, 3, \"Planned hours of subtask should impact parent task\")\n\n # change services\n child_task.write({\n 'services_id': self.services_goats.id # customer is partner_1\n })\n\n self.assertEqual(parent_task.partner_id, child_task.partner_id, \"Subtask partner should not change when changing services\")", "def test_add_tag_for_task(self):\n pass" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case verifies that the task edit form pagee loads with expected fields if the user is authenticated
def test_edit_task_form(self): # Issue a GET request logged_out_response = self.client.get(reverse("check_mate:task_edit", args=(1,))) # Confirm that the response does not have associated content self.assertFalse(logged_out_response.content) # Confirm that the user is redirected to the login page if they are not authenticated self.assertEqual(logged_out_response.status_code, 302) # Log the user in self.client.login(username="test_user", password="secret") # Issue a GET request response = self.client.get(reverse("check_mate:task_edit", args=(1,))) # Confirm that the response is 200 self.assertEqual(response.status_code, 200) # TODO: Write check for the response content once final styling and formatting is added
[ "def test_add_task_form(self):\n\n # Issue a GET request\n logged_out_response = self.client.get(reverse(\"check_mate:task_add\"))\n\n # Confirm that the response does not have any content\n self.assertFalse(logged_out_response.content)\n\n # Confirm that the user is redirected to the login page if they are not authenticated\n self.assertEqual(logged_out_response.status_code, 302)\n\n # Log the user in\n self.client.login(username=\"test_user\", password=\"secret\")\n\n # TODO: Figure out how to pass ticket information in the form\n # TODO: Write check for response content once final styling and formatting is added", "def test_get_edit_form(self):\n\n with self.client as c:\n self.login(c)\n\n # UNAUTHORIZED - getting edit form for trade owned by another user\n resp = c.get('/trades/222/edit', follow_redirects=True)\n\n self.assertEqual(resp.status_code, 200)\n self.assertIn('You are unauthorized to view this page.', str(resp.data))\n self.assertNotIn('<h1 id=\"trade-text\" class=\"display-3 text-center mt-5\">Edit a trade</h1>', str(resp.data))\n\n # AUTHORIZED\n resp = c.get('/trades/111/edit')\n\n self.assertEqual(resp.status_code, 200)\n self.assertIn('<h1 id=\"trade-text\" class=\"display-3 text-center mt-5\">Edit a trade</h1>', str(resp.data))\n self.assertIn('test car', str(resp.data))", "def test_person_edit_form(self):\n person = Person.objects.get(pk=1)\n self.client.login(username=self.tester, password=self.tester)\n page_uri = '/admin/hello/person/1/'\n page = self.client.get(page_uri)\n self.assertEqual(page.context['fieldset'].form.instance, person)", "def test_show_edit_user(self):\n \n with app.test_client() as client:\n\n resp = client.get(f\"/users/{self.user_id}/edit\")\n html = resp.get_data(as_text=True)\n\n self.assertEqual(resp.status_code, 200)\n self.assertIn(\"value='Tweety'\", html)\n self.assertIn(\"value='Bird'\", html)\n self.assertIn(f\"<form action='/users/{self.user_id}/edit'\", html)", "def test_web_task_edit_status_to_in_progress(\n webapp, new_user, new_task_done_three_tags\n):\n webapp.homepage()\n webapp.sign_in(new_user.username, new_user.password)\n task = webapp.taskboard.find_task(new_task_done_three_tags.title)\n assert task.done is True\n task.edit(done=False)\n assert task.done is False", "def test_web_task_edit_option_only_for_own_tasks(\n webapp, new_user, new_task, new_task_default_user\n):\n webapp.homepage()\n webapp.sign_in(new_user.username, new_user.password)\n for task in webapp.taskboard.tasks():\n assert (\"edit\" in task.options) == (task.owner == new_user.username)", "def test_web_task_edit_status_to_done(webapp, new_user, new_task):\n webapp.homepage()\n webapp.sign_in(new_user.username, new_user.password)\n task = webapp.taskboard.find_task(new_task.title)\n assert task.done is False\n task.edit(done=True)\n assert task.done is True", "def test_edit_employees_show(self):\n\n response = self.client.get(\n reverse('employees:edit', args=(self.emp1.id,))\n )\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, 'employees/edit.html')\n self.assertIsInstance(response.context['form'], EmployeeForm)\n self.assertEqual(response.context['employee'], self.emp1)", "def test_form_page_view(self):\n\n # if user is not authenticate\n response = self.client.get(reverse('hello:contact_form'))\n self.assertEqual(response.status_code, 302)\n\n # after authentication\n self.client.login(username='admin', password='admin')\n response = self.client.get(reverse('hello:contact_form'))\n self.assertTemplateUsed(response, 'contact_form.html')\n self.assertIn(self.contact.name, response.content)\n self.assertIn(self.contact.surname, response.content)\n self.assertIn(self.contact.date_of_birth.strftime('%Y-%m-%d'),\n response.content)\n self.assertIn(self.contact.email, response.content)\n self.assertIn(self.contact.jabber, response.content)", "def test_view_edit_event(self):\n self.user.is_staff = True\n self.user.is_active = True\n self.user.save()\n\n self.client.login(username=self.username, password=self.password)\n response = self.client.get(\n '/edit_event/', {'event_id': self.event.id})\n self.assertEqual(response.status_code, HTTPStatus.OK)", "def test_UserFormViewPermissionForAdmin(self):\n response = self.app.get(\n reverse('employees:UserFormView', args=[\"regular.user\"]),\n headers={'X_AUTH_USER': 'aaron.snow@gsa.gov'},\n )\n # Check that inital data for UserDate Populates\n self.assertEqual(\n response.html.find('input', {'id': 'id_start_date'})['value'],\n '2014-01-01')\n self.assertEqual(\n response.html.find('input', {'id': 'id_end_date'})['value'],\n '2016-01-01')", "def test_user_edit(self):\n\n with app.test_client() as client:\n d = {\"first_name\": \"Jonathan\",\n \"last_name\": \"Pagac\",\n \"image_url\": \"\"}\n resp = client.post(f\"/users/{self.user_id}/edit\",\n data=d,\n follow_redirects=True)\n html = resp.get_data(as_text=True)\n\n self.assertEqual(resp.status_code, 200)\n self.assertIn(\"Jonathan\", html)\n self.assertIn(\"Pagac\", html)\n self.assertIn('id=\"user-info\"', html)", "def test_user_edit_page(self):\n url = reverse(\"admin:user_user_change\", args=[self.user.id])\n response = self.client.get(url)\n\n self.assertEquals(response.status_code, 200)", "def test_show_post_edit_form(self):\n with app.test_client() as client:\n resp = client.get(f'/posts/{self.post1_id}/edit')\n html = resp.get_data(as_text=True)\n\n self.assertEqual(resp.status_code, 200)\n self.assertIn('<h1>Edit Post</h1>', html)", "def test_edit_valid(self):\n f = GradGoalEditForm({\n 'text':\"Students will comprehend detailed instructions.\",\n 'active': True\n })\n self.assertTrue(f.is_valid())", "def test_task_edit_view_reachable_from_event_person_and_role_of_task(self):\n\n correct_task = self.fixtures['test_task_1']\n\n url_kwargs = {'task_id': correct_task.id}\n\n response = self.client.get(reverse('task_edit',\n kwargs=url_kwargs))\n\n assert response.context['task'].pk == correct_task.pk", "def test_album_edit_route_get_logged_in_has_edit_form(self):\n album_id = self.bob.albums.first().id\n self.client.login(username='bob', password='password')\n response = self.client.get(reverse_lazy('album_edit', kwargs={'id': album_id}))\n self.assertIn(b'Edit Album</h1>', response.content)", "def test_success_todo_details(self):\n self.login()\n\n response = self.client.get(url_for('alaya_todo.todo', id=get_max_todo_id(), page=1))\n self.assert200(response, 'The todo details page must return a 200 HTTP Code.')\n self.assertTemplateUsed('todo.html')\n\n self.logout()", "def test_photo_edit_route_get_logged_in_has_edit_form(self):\n photo_id = self.bob.photos.first().id\n self.client.login(username='bob', password='password')\n response = self.client.get(reverse_lazy('photo_edit', kwargs={'id': photo_id}))\n self.assertIn(b'Edit Photo</h1>', response.content)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case verifies that you can delete a task if the user is authenticated and certain conditions are met
def test_delete_task(self): # Issue a GET request logged_out_response = self.client.get(reverse("check_mate:task_delete", args=(1,))) # Confirm that the response does not have any content self.assertFalse(logged_out_response.content) # Confirm that the user is redirected to the login page if they are not authenticated self.assertEqual(logged_out_response.status_code, 302) # Log the user in self.client.login(username="test_user", password="secret") # Issue a GET request for a task that cannot be deleted get_delete = self.client.get(reverse("check_mate:task_delete", args=(2,))) # Confirm that the response is 200 self.assertEqual(get_delete.status_code, 200) # Confirm that the context has "can delete" set to False self.assertEqual(get_delete.context["task"].delete_status, False) # Issue another GET request for a task that can be deleted get_delete_true = self.client.get(reverse("check_mate:task_delete", args=(1,))) # Confirm that the response is 200 self.assertEqual(get_delete_true.status_code, 200) # Confirm that the context has "can_delete" set to True self.assertEqual(get_delete_true.context["task"].delete_status, True) # TODO: Write tests for content that displays on the page # TODO: Writee tests for post functionality of delete
[ "def test_api_can_delete_task(self):\n\n task = self.template_task\n task.save()\n\n token = self.get_auth_token()\n self.client.credentials(HTTP_AUTHORIZATION='Token '+token)\n\n response = self.client.delete(\n reverse('select_template_api:select_template_status',\n kwargs={'uuid': task.uuid}),\n format='json',\n follow=True)\n\n self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)", "def test_authorization_delete(self):\n pass", "def test_delete_run_as_user(self):\n pass", "def test_auth_delete_participant(self):\n pass", "def test_delete_task_delete(self):\n url = self.url+'/{task_id}?board={board_id}'.format(\n task_id=self.task.id, board_id=self.board.id)\n response = self.client.get(url)\n print(response.status_code, response.content)\n self.assertEqual(200, response.status_code)\n\n response = self.client.delete(url)\n print(response.status_code, response.content)\n self.assertEqual(204, response.status_code)\n self.assertEqual(b'', response.content)", "def task_delete(request, task_id):\r\n task = get_object_or_404(Task, id=task_id)\r\n if request.user == task.creator and task.status == 'PLAN':\r\n task.delete()\r\n messages.success(request, \"The task is deleted successfully!\")\r\n # After deleting task redirect user to index page with success message\r\n return redirect('task_manager:index')\r\n else:\r\n # User is not creator of task, raise PermissionDenied\r\n raise PermissionDenied", "def test_api_v3_stories_story_public_id_tasks_task_public_id_delete(self):\n pass", "def test_delete_account_permission_using_delete(self):\n pass", "def test_delete_task_from_valid_uuid():\n post_response = client.post(\n '/task/',\n json={\n 'description': 'Some description',\n 'completed': False\n })\n assert post_response.status_code == 200\n uuid_ = post_response.json()\n\n response = client.delete(f'/task/{uuid_}')\n assert response.status_code == 200\n assert response.json() == None", "def test_delete(self):\n\n with self.client as c:\n self.login(c)\n\n # UNAUTHORIZED - deleting trade owned by user 222, as user 111\n resp = c.post('/trades/222/delete', follow_redirects=True)\n\n self.assertEqual(resp.status_code, 200)\n self.assertIn('You are unauthorized to perform this action.', str(resp.data))\n trade = Trade.query.get(222)\n self.assertIsNotNone(trade)\n\n # AUTHORIZED\n resp = c.post('/trades/111/delete', follow_redirects=True)\n\n self.assertEqual(resp.status_code, 200)\n self.assertIn('Trade successfully deleted', str(resp.data))\n trade = Trade.query.get(111)\n self.assertIsNone(trade)", "def test_login_required_destroy(self):\n user = create_user('username2', 'password')\n item = create_sample_item(\n create_sample_cateory(user, 'cat1'), 'item')\n\n res = self.client.delete(get_todo_item_detail_url(item.id))\n\n self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)", "def test_terminal_v1_tasks_delete(self):\n pass", "def test_delete_acl(self):\n # Site ID 1 is owned by user 1 in the test data.\n # Check that user 2 can't delete it.\n self.set_user_token(2)\n res = self.__client.delete('/site/api/v1.0/site/1')\n self.assertEqual(res.status_code, 404)\n # Double check that user 1 _can_ delete it\n self.set_user_token(1)\n res = self.__client.delete('/site/api/v1.0/site/1')\n self.assertEqual(res.status_code, 200)", "def test_post_delete_account(self):\n c = Client()\n c.login(username='foo', password='bar')\n request = c.post('/GradMaze/accounts/delete/', follow=True)\n self.assertFalse(User.objects.filter(username='foo').exists())", "def test_terminal_v1_tasks_delete_0(self):\n pass", "def test_delete_checker_result(self):\n pass", "def test_user_delete_access_token(self):\n pass", "def test_delete(self):\n\n organizer = self.organizer_client\n\n # Set permissions\n self._set_permissions()\n assign_perm('activities.delete_activityphoto',\n user_or_group=self.organizer.user, obj=self.activity_photo)\n\n # Anonymous should return unauthorized\n response = self.client.post(self.delete_activity_photo_url)\n self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)\n self.assertEqual(ActivityPhoto.objects.count(),\n self.activity_photos_count)\n\n # Student should return forbidden\n response = self.student_client.post(self.delete_activity_photo_url)\n self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)\n self.assertEqual(ActivityPhoto.objects.count(),\n self.activity_photos_count)\n\n # Organizer should not delete a photo if he is not activity owner\n response = self.another_organizer_client.post(\n self.delete_activity_photo_url)\n self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)\n self.assertEqual(ActivityPhoto.objects.count(),\n self.activity_photos_count)\n\n # Organizer should delete a photo from his activity\n self.assertEqual(self.another_activity.score, 4.8)\n response = organizer.delete(self.delete_activity_photo_url)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(ActivityPhoto.objects.count(),\n self.activity_photos_count - 1)", "def test_delete_authentication_duo_verify(self):\n\n url = reverse('authentication_duo_verify')\n\n data = {}\n\n self.client.force_authenticate(user=self.test_user_obj)\n response = self.client.delete(url, data)\n\n self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Testing the heap after items are inserted
def test_insert(items, pqueue): bhm = BinaryHeapMax() for i in items: bhm.insert(i) assert str(bhm) == str(pqueue)
[ "def _check_heap(self):\n for i in self.heap.walk():\n parent = self.heap.get_parent(i)\n if self.heap.is_max():\n self.assertLessEqual(i.get_item(), parent.get_item())\n else:\n self.assertGreaterEqual(i.get_item(), parent.get_item())", "def test_pq_insert_one_item():\n pq = PriortyQ()\n pq.insert(\"item\", 1)\n assert (1, \"item\") in pq._queue._heap", "def insert(self, item):\n self.heapList.append(item)\n self.currentSize += 1 \n self.percUp(self.currentSize)", "def max_heap_insert(heap, item):\n heap.insert(0, item)\n max_heapify(heap, 0)\n #build_max_heap(heap)", "def test(self, *args):\n for x in args:\n if self.op(x, self.heap[0]):\n pos = 0\n while True:\n child = 2 * pos + 1\n if child >= self.length:\n break\n child += self.op(self.heap[child], self.heap[child + 1])\n if not self.op(x, self.heap[child]):\n break\n self.heap[pos] = self.heap[child]\n pos = child\n self.heap[pos] = x", "def add(self, item):\r\n \r\n self._size += 1\r\n self._heap.append(item)\r\n curPos = len(self._heap) - 1\r\n \r\n while curPos > 0:\r\n parent = (curPos - 1) // 2\r\n parentItem = self._heap[parent]\r\n if parentItem <= item:\r\n break\r\n \r\n else:\r\n self._heap[curPos] = self._heap[parent]\r\n self._heap[parent] = item\r\n curPos = parent", "def test_random_deletion_same_insatnce(self):\n random.seed(self._seed)\n for run in range(20):\n list_to_test = util.get_random_list()\n heap_instance = HeapQueue(list_to_test[:])\n util.check_heap(heap_instance, self)\n for deletion in range(random.randrange(10, 90)):\n index_to_delete = random.randrange(0, len(list_to_test))\n deleted_element = list_to_test.pop(index_to_delete)\n heap_instance.remove(deleted_element[1])\n util.check_heap(heap_instance, self)\n with self.subTest(msg=\"Loop: \" + str(run)):\n self.assertEqual(heap_instance.peek(), min(list_to_test))\n retrieved_list = util.retrieve(heap_instance)\n with self.subTest(msg=\"Loop: \" + str(run)):\n self.assertEqual(sorted(list_to_test), retrieved_list, \"Random seed: ({})\".format(str(self._seed)))", "def add(self, item): \n self.heap.append(item)\n i = len(self.heap) - 1\n while i:\n leftChildParent = math.floor((i-1)/2)\n rightChildParent = math.floor((i-2)/2)\n if leftChildParent == rightChildParent:\n if self.heap[i] < self.heap[rightChildParent]:\n temp = self.heap[i]\n self.heap[i] = self.heap[rightChildParent]\n self.heap[rightChildParent] = temp\n i = rightChildParent\n else:\n if self.heap[i] < self.heap[leftChildParent]:\n temp = self.heap[i]\n self.heap[i] = self.heap[leftChildParent]\n self.heap[leftChildParent] = temp\n i = leftChildParent", "def test_insert3_pop_returns_correct_value():\n pq = PriortyQ()\n pq.insert('item', 1)\n pq.insert('item3', 3)\n pq.insert('item2', 2)\n assert pq.pop() == 'item3'", "def heapify(self, arg_items):\n # cleaning the present PQ\n self._array.clear()\n \n #fill the array\n for it in arg_items:\n self._array.append(it)\n \n #heapifying the unsorted input\n n = len(self._array)\n \n idx = n-1\n parent_idx = self._parent(idx)\n while ( parent_idx >= 0 ):\n self._sift_down(parent_idx)\n parent_idx -= 1\n \n return", "def heapify(self):\n n = len(self.storage)\n # Transform bottom-up. The largest idx there's any point to looking at is\n # the largest with a child idx in-range, so must have 2*idx + 1 < n,\n # or idx\n for i in reversed(range(n // 2)):\n self._sift_up(i)", "def heapRandomTest(size, min_heap):\n heap = Heap(min_heap)\n ar = []\n\n # insertions\n for i in range(size):\n k = random.randint(-9999,9999)\n heap.insert(k)\n ar.append(k) \n\n if not heapCompare(heap, ar):\n print \"Error after insertions: heap =\",heap,\" ar=\",ar\n return False\n \n # deletions\n for i in range(size//4):\n index = random.randint(0,len(ar)-1)\n k = ar[index]\n heap.delete(k)\n ar.remove(k)\n\n if not heapCompare(heap, ar):\n print \"Error after deletions: heap =\",heap,\" ar=\",ar\n return False\n \n # pops\n ar.sort()\n if heap.isMinHeap():\n ar = ar[::-1]\n for i in range(size//4):\n heap.extract()\n ar.pop()\n\n if not heapCompare(heap, ar):\n print \"Error after pop/extract: heap =\",heap,\" ar=\",ar\n return False\n \n # random deletions\n for i in range(size//4):\n k = random.randint(-9999,9999)\n if k in ar:\n ar.remove(k)\n heap.delete(k)\n \n if not heapCompare(heap, ar):\n print \"Error after random deletions: heap =\",heap,\" ar=\",ar\n return False\n \n # further insertions\n for i in range(size//4):\n k = random.randint(-9999,9999)\n heap.insert(k)\n ar.append(k)\n \n if not heapCompare(heap, ar):\n print \"Error after further insertions: heap =\",heap,\" ar=\",ar\n return False\n \n return True", "def test_insert_increases_size(tree):\n tree.insert('hello')\n tree.insert('hi')\n assert tree.size() == 2", "def heappush(heap, item):\r\n heap.append(item)\r\n _siftdown(heap, 0, len(heap)-1)", "def automaticTest(sample_size):\n import random\n random_numbers = random.sample(range(100), sample_size)\n min_heap = MinHeap()\n max_heap = MaxHeap()\n for i in random_numbers:\n min_heap.push(i)\n max_heap.push(i)\n random_numbers.sort()\n for i in random_numbers:\n assert(min_heap.pop() == i)\n random_numbers.sort(reverse=True)\n for i in random_numbers:\n assert(max_heap.pop() == i)", "def _heappush_upto(heap, amount, item):\n if len(heap) >= amount:\n heappushpop(heap, item)\n else:\n heappush(heap, item)", "def test_remove(items, pqueue):\n bhm = BinaryHeapMax()\n bhm.heapify(items)\n bhm.remove()\n assert str(bhm) == str(pqueue)", "def insert(self, value):\n self.heap_list.append(value)\n self.current_size += 1\n self.perc_up(self.current_size)", "def djikstra_heap(s=0):" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Testing the heap after items are removed
def test_remove(items, pqueue): bhm = BinaryHeapMax() bhm.heapify(items) bhm.remove() assert str(bhm) == str(pqueue)
[ "def test_random_deletion_same_insatnce(self):\n random.seed(self._seed)\n for run in range(20):\n list_to_test = util.get_random_list()\n heap_instance = HeapQueue(list_to_test[:])\n util.check_heap(heap_instance, self)\n for deletion in range(random.randrange(10, 90)):\n index_to_delete = random.randrange(0, len(list_to_test))\n deleted_element = list_to_test.pop(index_to_delete)\n heap_instance.remove(deleted_element[1])\n util.check_heap(heap_instance, self)\n with self.subTest(msg=\"Loop: \" + str(run)):\n self.assertEqual(heap_instance.peek(), min(list_to_test))\n retrieved_list = util.retrieve(heap_instance)\n with self.subTest(msg=\"Loop: \" + str(run)):\n self.assertEqual(sorted(list_to_test), retrieved_list, \"Random seed: ({})\".format(str(self._seed)))", "def _check_heap(self):\n for i in self.heap.walk():\n parent = self.heap.get_parent(i)\n if self.heap.is_max():\n self.assertLessEqual(i.get_item(), parent.get_item())\n else:\n self.assertGreaterEqual(i.get_item(), parent.get_item())", "def test_remove_job_no(self):\r\n # todo add larger sample and more removes\r\n remove_job_no(2)\r\n self.assertEqual(self.h_1.heap[1], self.j_1_1)\r\n remove_job_no(1)\r\n self.assertEqual(self.h_1.heap[0], self.j_1_1)", "def delMin(self):\n self.heapList[1] = self.heapList[self.currentSize]\n self.heapList.pop()\n self.currentSize -= 1\n self.percDown(1)", "def heapRandomTest(size, min_heap):\n heap = Heap(min_heap)\n ar = []\n\n # insertions\n for i in range(size):\n k = random.randint(-9999,9999)\n heap.insert(k)\n ar.append(k) \n\n if not heapCompare(heap, ar):\n print \"Error after insertions: heap =\",heap,\" ar=\",ar\n return False\n \n # deletions\n for i in range(size//4):\n index = random.randint(0,len(ar)-1)\n k = ar[index]\n heap.delete(k)\n ar.remove(k)\n\n if not heapCompare(heap, ar):\n print \"Error after deletions: heap =\",heap,\" ar=\",ar\n return False\n \n # pops\n ar.sort()\n if heap.isMinHeap():\n ar = ar[::-1]\n for i in range(size//4):\n heap.extract()\n ar.pop()\n\n if not heapCompare(heap, ar):\n print \"Error after pop/extract: heap =\",heap,\" ar=\",ar\n return False\n \n # random deletions\n for i in range(size//4):\n k = random.randint(-9999,9999)\n if k in ar:\n ar.remove(k)\n heap.delete(k)\n \n if not heapCompare(heap, ar):\n print \"Error after random deletions: heap =\",heap,\" ar=\",ar\n return False\n \n # further insertions\n for i in range(size//4):\n k = random.randint(-9999,9999)\n heap.insert(k)\n ar.append(k)\n \n if not heapCompare(heap, ar):\n print \"Error after further insertions: heap =\",heap,\" ar=\",ar\n return False\n \n return True", "def test_remove_decreases_size(tree):\n tree.insert('hello')\n tree.insert('hi')\n tree.insert('help')\n tree.remove('help')\n tree.remove('hi')\n assert tree.size() == 1", "def test(self, *args):\n for x in args:\n if self.op(x, self.heap[0]):\n pos = 0\n while True:\n child = 2 * pos + 1\n if child >= self.length:\n break\n child += self.op(self.heap[child], self.heap[child + 1])\n if not self.op(x, self.heap[child]):\n break\n self.heap[pos] = self.heap[child]\n pos = child\n self.heap[pos] = x", "def delete(self, i):\n\t\tif i == len(self.heap.items) - 1:\n\t\t\treturn self.heap.items.pop()\n\t\tdeleted = self.heap.items[i]\n\t\tself.heap.items[i] = self.heap.items.pop()\n\t\tkey = self.heap.eval\n\t\tif i == 1:\n\t\t\tself.heap.heapify_down(i)\n\t\telif key(self.heap.items[i]) < key(self.heap.items[i/2]):\n\t\t\tself.heap.heapify_up(i)\n\t\telse:\n\t\t\tself.heap.heapify_down(i)\n\t\treturn deleted", "def delete(self, value):\r\n delete_complete = False\r\n\r\n # find the index of value and delete it from the heap\r\n for i in range(len(self.heap)):\r\n if value == self.heap[i]:\r\n self.__swap(i, -1)\r\n self.heap.pop()\r\n delete_complete = True\r\n\r\n # if the value is the last value of the heap, no need for heapify or bubble down\r\n if i == len(self.heap):\r\n break\r\n\r\n # if the swapped value breaks the balance, heapify again\r\n if self.heap[(i + 1) // 2 - 1] > self.heap[i]:\r\n self.heapify()\r\n else:\r\n self.__bubble_down(i)\r\n break\r\n\r\n if not delete_complete:\r\n print(\"No such value in the heap!\")", "def remove(self, item):\n if self.has_item(item):\n del self.set[item]\n self.heap = self.set.keys()\n heapq.heapify(self.heap)\n #self.heap = list(set(self.set.keys()) - set(item))\n #heapq.heapify(self.heap)", "def heap_unlock() -> None:", "def heapify(self, arg_items):\n # cleaning the present PQ\n self._array.clear()\n \n #fill the array\n for it in arg_items:\n self._array.append(it)\n \n #heapifying the unsorted input\n n = len(self._array)\n \n idx = n-1\n parent_idx = self._parent(idx)\n while ( parent_idx >= 0 ):\n self._sift_down(parent_idx)\n parent_idx -= 1\n \n return", "def pop(self):\n if len(self._items) == 0:\n raise LookupError('pop from empty heap')\n # else:\n # swap top item with the last item of self._items, and remove it\n _swap(self._items, 0, -1)\n min_item = self._items.pop()\n # now repair the heap property\n _shift_down(self._items, 0, self._less)\n # return\n return min_item", "def del_max(self):\n extracted_max = self.heaplist[0]\n self.heaplist[0] = self.heaplist[-1]\n self.heaplist.pop()\n i = 0\n length = len(self.heaplist)\n while i < length//2:\n l_idx = 2*i + 1\n r_idx = 2*i + 2\n if r_idx > length-1:\n if self.heaplist[i] < self.heaplist[l_idx]:\n temp = self.heaplist[l_idx]\n self.heaplist[l_idx] = self.heaplist[i]\n self.heaplist[i] = temp\n i = l_idx\n else:\n break\n else:\n if (self.heaplist[i] >= self.heaplist[l_idx]) and (self.heaplist[i]>= self.heaplist[r_idx]):\n break\n \n else:\n if self.heaplist[l_idx] == self.heaplist[r_idx]:\n max_idx = r_idx\n val = self.heaplist[r_idx]\n else: \n to_swap = {l_idx: self.heaplist[l_idx], r_idx:self.heaplist[r_idx]} \n max_idx, val = max(to_swap.items(), key = lambda x:x[1])\n self.heaplist[max_idx] = self.heaplist[i]\n self.heaplist[i] = val\n i = max_idx\n \n return extracted_max", "def heapRemoveSmallest(self,heap,vertices):\r\n vertices[heap[0][0]]=-1\r\n if len(heap)==1:\r\n heap.pop()\r\n return\r\n vertices[heap[len(heap)-1][0]] =0\r\n heap[0]=heap[len(heap)-1]\r\n heap.pop()\r\n if len(heap)>0:\r\n self.down(heap,0,vertices)", "def clean(self) -> None:\n self.heap = [t for t in self.heap if t is t.actor.sched_ticket]\n heapq.heapify(self.heap)", "def heapify(self):\n n = len(self.storage)\n # Transform bottom-up. The largest idx there's any point to looking at is\n # the largest with a child idx in-range, so must have 2*idx + 1 < n,\n # or idx\n for i in reversed(range(n // 2)):\n self._sift_up(i)", "def automaticTest(sample_size):\n import random\n random_numbers = random.sample(range(100), sample_size)\n min_heap = MinHeap()\n max_heap = MaxHeap()\n for i in random_numbers:\n min_heap.push(i)\n max_heap.push(i)\n random_numbers.sort()\n for i in random_numbers:\n assert(min_heap.pop() == i)\n random_numbers.sort(reverse=True)\n for i in random_numbers:\n assert(max_heap.pop() == i)", "def test_minheap_is_heap_not(self):\n heap = min_heap.MinHeap()\n heap.array = [100, 36, 25, 19, 17, 7, 3, 2, 1]\n self.assertFalse(heap.is_min_heap())" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extrae los operandos y operadores y quita los parentesis
def test_extraer_operandos_y_operadores_en_expr_sin_ptsis(self): self.assertEqual({'Operandos': [5, 4, 2, 2], 'Operadores': ['+', '*', '/']}, self.expresion.parse("5 + 4 * 2 / 2"))
[ "def __calculate_operators__(self):\n self.operator_str = \"\"\n for lit in self.p_seq_lits:\n ops = lit.get_operators()\n self.operator_str += ''.join(x for x in ops)", "def operacao(*args):\r\n if '+' in args:\r\n return num[0] + num[1]\r\n elif '-' in args:\r\n return num[0] - num[1]\r\n elif '*' in args:\r\n return num[0]*num[1]\r\n return num[0]/num[1]", "def transform_binary_operator(self, node):\n # get all the tokens of assignment\n # and store it in the tokens list\n tokens = list(node.get_tokens())\n\n # supported operators list\n operators_list = ['+', '-', '*', '/', '%','=',\n '>', '>=', '<', '<=', '==', '!=', '&&', '||', '+=', '-=',\n '*=', '/=', '%=']\n\n # this stack will contain variable content\n # and type of variable in the rhs\n combined_variables_stack = []\n\n # this stack will contain operators\n # to be processed in the rhs\n operators_stack = []\n\n # iterate through every token\n for token in tokens:\n # token is either '(', ')' or\n # any of the supported operators from the operator list\n if token.kind == cin.TokenKind.PUNCTUATION:\n\n # push '(' to the operators stack\n if token.spelling == '(':\n operators_stack.append('(')\n\n elif token.spelling == ')':\n # keep adding the expression to the\n # combined variables stack unless\n # '(' is found\n while (operators_stack\n and operators_stack[-1] != '('):\n if len(combined_variables_stack) < 2:\n raise NotImplementedError(\n \"Unary operators as a part of \"\n \"binary operators is not \"\n \"supported yet!\")\n rhs = combined_variables_stack.pop()\n lhs = combined_variables_stack.pop()\n operator = operators_stack.pop()\n combined_variables_stack.append(\n self.perform_operation(\n lhs, rhs, operator))\n\n # pop '('\n operators_stack.pop()\n\n # token is an operator (supported)\n elif token.spelling in operators_list:\n while (operators_stack\n and self.priority_of(token.spelling)\n <= self.priority_of(\n operators_stack[-1])):\n if len(combined_variables_stack) < 2:\n raise NotImplementedError(\n \"Unary operators as a part of \"\n \"binary operators is not \"\n \"supported yet!\")\n rhs = combined_variables_stack.pop()\n lhs = combined_variables_stack.pop()\n operator = operators_stack.pop()\n combined_variables_stack.append(\n self.perform_operation(\n lhs, rhs, operator))\n\n # push current operator\n operators_stack.append(token.spelling)\n\n # token is a bitwise operator\n elif token.spelling in ['&', '|', '^', '<<', '>>']:\n raise NotImplementedError(\n \"Bitwise operator has not been \"\n \"implemented yet!\")\n\n # token is a shorthand bitwise operator\n elif token.spelling in ['&=', '|=', '^=', '<<=',\n '>>=']:\n raise NotImplementedError(\n \"Shorthand bitwise operator has not been \"\n \"implemented yet!\")\n else:\n raise NotImplementedError(\n \"Given token {} is not implemented yet!\"\n .format(token.spelling))\n\n # token is an identifier(variable)\n elif token.kind == cin.TokenKind.IDENTIFIER:\n combined_variables_stack.append(\n [token.spelling, 'identifier'])\n\n # token is a literal\n elif token.kind == cin.TokenKind.LITERAL:\n combined_variables_stack.append(\n [token.spelling, 'literal'])\n\n # token is a keyword, either true or false\n elif (token.kind == cin.TokenKind.KEYWORD\n and token.spelling in ['true', 'false']):\n combined_variables_stack.append(\n [token.spelling, 'boolean'])\n else:\n raise NotImplementedError(\n \"Given token {} is not implemented yet!\"\n .format(token.spelling))\n\n # process remaining operators\n while operators_stack:\n if len(combined_variables_stack) < 2:\n raise NotImplementedError(\n \"Unary operators as a part of \"\n \"binary operators is not \"\n \"supported yet!\")\n rhs = combined_variables_stack.pop()\n lhs = combined_variables_stack.pop()\n operator = operators_stack.pop()\n combined_variables_stack.append(\n self.perform_operation(lhs, rhs, operator))\n\n return combined_variables_stack[-1][0]", "def calc(self, n1, op, n2):\n if op == \"*\":\n return n1 * n2\n if op == \"/\":\n return n1 // n2\n if op == \"+\":\n return n1 + n2\n if op == \"-\":\n return n1 - n2", "def calculate(self, op, a, b):\n if op == \"+\":\n return a + b\n elif op == \"-\":\n return a - b\n elif op == \"*\":\n return a * b\n elif op == \"/\":\n return a / b", "def calculator(nums, operators):\n result = nums[0]\n nums.pop(0)\n for i in range(len(operators)):\n if operators[i] == '+':\n result = nums[i] + result\n elif operators[i] == '-':\n result = nums[i] - result\n elif operators[i] == '*':\n result = nums[i] * result\n elif operators[i] == '/':\n result = nums[i] / result\n elif operators[i] == '**':\n result = nums[i] ** result\n elif operators[i] == '//':\n result = nums[i] // result\n elif operators[i] == '%':\n result = nums[i] % result\n return result", "def operands(self):\n return [self._get_operand(i) for i in range(self.operand_count)]", "def operate(term1: int, term2: int, op: str) -> int:\n if op == '+':\n return term1 + term2\n elif op == '*':\n return term1 * term2\n else:\n raise ValueError", "def apply_operators(e):\n e = e.expand()\n muls = e.atoms(Mul)\n subs_list = [(m, _apply_Mul(m)) for m in iter(muls)]\n return e.subs(subs_list)", "def test_operator_get_all_operators(self):\n pass", "def quad_add_oper(self, oper):\n\n if IdleCompiler.__should_gen_quads:\n IdleCompiler.__interp.add_operator(oper)", "def test_chained_unary_operators_ending_in_operand(self):\n t = ExpressionTreeNode.build_tree(['A', '~'])\n self.assertTrue(t.is_really_unary)\n\n t = ExpressionTreeNode.build_tree(['A', '~', '~'])\n self.assertTrue(t.is_really_unary)\n\n t = ExpressionTreeNode.build_tree(['A', '~', '~', '~'])\n self.assertTrue(t.is_really_unary)", "def math_operation_no_precedence(expression: str) -> str:\n elements = expression.split()\n final = 0\n for index, value in enumerate(elements):\n if index == 0:\n final = int(value)\n elif index % 2 == 0:\n if elements[index - 1] == \"+\":\n final += int(value)\n elif elements[index - 1] == \"*\":\n final *= int(value)\n return str(final)", "def print_ops():\n print(\"The operators are as follows (in order of precedence):\")\n for i in sorted(Operators, reverse=True):\n print(i.symbol,\":\",repr(i))\n print(\"where 'left' and 'right' stand for any expressions.\")\n print(\"'(' and ')' can be used to change the precedence, giving the expression contained the highest precedence.\")\n print(\"Note that all spaces are ignored entirely, so 'a b' would be treated as 'ab'.\")\n print(\"Besides this, expressions are evaluated from the right to the left, meaning that a&b&c is treated as a&(b&c).\")", "def test_mix_of_primitive_operators(self):\n self.assert_to_cnf_transformation(\n 'A and (B or C and D) and not (C or not D and not E)',\n 'A and (B or C) and (B or D) and not C and (D or E)')\n self.assert_to_cnf_transformation(\n '(A and B and C) or not (A and D) or (A and (B or C) or '\n '(D and (E or F)))',\n '(C or not A or not D or B or E or F) and '\n '(B or not A or not D or C or E or F)')", "def precedence(op: str, part=1) -> int:\n if op == '+':\n return 1 if part == 1 else 2\n elif op == '*':\n return 1\n return 0", "def math_operation_reverse_precedence(expression: str) -> str:\n elements = expression.split()\n addition_evaluated = []\n final = 1\n for index, value in enumerate(elements):\n if value == \"*\":\n addition_evaluated.append(value)\n elif index == 0:\n addition_evaluated.append(int(value))\n elif index % 2 == 0 and index >= 2 and elements[index - 1] == \"+\":\n if addition_evaluated[-1] in [\"+\", \"*\"]:\n addition_evaluated.append(int(value))\n else:\n addition_evaluated[-1] += int(value)\n elif addition_evaluated[-1] == \"*\":\n addition_evaluated.append(int(value))\n for index, value in enumerate(addition_evaluated):\n if index == 0:\n final *= int(value)\n if index % 2 == 0 and index >= 2 and addition_evaluated[index - 1] == \"*\":\n final *= int(value)\n return str(final)", "def apply_operators(operators, expression):\n\n i = 1\n while i < len(expression) - 1:\n\n if expression[i] in operators:\n operator = expression[i]\n op1 = expression[i - 1]\n op2 = expression[i + 1]\n\n # Apply the operation between the previous and following values\n if operator == '+':\n res = op1 + op2\n elif operator == '-':\n res = op1 - op2\n elif operator == '*':\n res = op1 * op2\n elif operator == '/':\n res = op1 / op2\n else:\n raise Exception(\"apply_operator() should only be called with valid operators!\")\n\n # Replace the 3 items (op1, operator, op2) with the operation result\n expression[i-1] = res\n del expression[i+1]\n del expression[i]\n\n else:\n i += 1 # Increment index", "def test_single_operand(self):\n for token in ('0', '1', 'token'):\n t = ExpressionTreeNode.build_tree([token])\n self.assertTrue(t.is_really_unary)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prompt the user to get their lottery numbers
def get_numbers(): number_of_lotto_numbers = 3 user_lotto_numbers = [] for i in range(number_of_lotto_numbers): is_powerball = False if i == number_of_lotto_numbers - 1: is_powerball = True number = int(input(f"Select a powerball number: ")) else: number = int(input(f"Select a number: ")) while not number_is_valid(number, is_powerball): if is_powerball: number = int(input(f"Your Powerball input '{number}' is not valid. Please select a number 1-26 ")) else: number = int(input(f"Your input '{number}' is not valid. Please select a number 1-70")) user_lotto_numbers.append(number) return user_lotto_numbers
[ "def ask_numbers():", "def lottery_game():\n user_numbers = get_numbers()\n number_of_drawings = 0\n while user_numbers != get_lotto_numbers():\n number_of_drawings += 1\n years = round(((number_of_drawings / 2) / 52), 2)\n print(f\"Full match took {years} years\")", "def user_nums():\n \n print \"-----------------------------------------\"\n print \"Numbers are your friend!!! \"\n print \"Time to pick 4 of them, any numbers will do, but they can't be the same.\"\n print \"-----------------------------------------\"\n \n duplicate_alpha(num_1, 1)\n duplicate_alpha(num_2, 2)\n duplicate_alpha(num_3, 3)\n duplicate_alpha(num_4, 4)\n\n results_list.append(num_list)\n return num_list", "def get_lottery(lottery_nums):\n my_logger.info('Requests for %s loterries' % lottery_nums)\n try:\n random_shuangses = random_shuangse(lottery_nums)\n except Exception as e:\n my_logger.error(e)\n return jsonify({'status': 'failed', 'lotteries': [], 'msg': '接口返回错误 %s' % e})\n else:\n my_logger.info('Lotteries returned: %s' % random_shuangses)\n return jsonify({'status': 'success', 'lotteries': random_shuangses, 'msg': ''})", "def user_numbers():\n numbers = []\n tries = 0\n while tries != 6:\n try:\n number = int(input('Give your number: '))\n if number in range(1, 50):\n if number not in numbers:\n numbers.append(number)\n tries += 1\n else:\n print(f'You picked {number} before. Choose another one!')\n else:\n print(\"You can choose only between 1-49.\")\n except ValueError:\n print(\"Only numbers!\")\n numbers.sort()\n\n return numbers", "def main():\n count = 1\n while count <= 10:\n comp_num = get_random_number()\n user_num = int(input(\"\\nGuess the number (1-10): \"))\n count = compare_numbers(comp_num, user_num, count)", "def numberGuessing():\n\twhile True:", "def sure_lottery():\n return [0, 1, 0]", "def prompt_alg():\n algorithms = {0: 'random', 1: 'greedy', 2: 'greedy2', 3: 'hillclimber', 4: 'simulated_annealing'}\n print(\"What algorithm should be used (type INFO to get description of algorithms)\")\n print(''.join(['{0}{1}'.format(str(key) + ': ', value + ' ') for key, value in algorithms.items()]), end=' ')\n user_in = input('\\n> ')\n command(user_in)\n try:\n user_in = int(user_in)\n except ValueError:\n print('Invalid number, choose one from list below')\n return prompt_alg()\n if user_in not in algorithms:\n print('Invalid algorithm, choose one from list below')\n return prompt_alg()\n else:\n return algorithms[user_in]", "def prompt_for_digits():\n card_num_str = input('Enter a credit card number: ').replace(' ', '')\n return convert_digit_str_to_list(card_num_str)", "def ask_for_balls():\r\n balls = 0\r\n\r\n while balls < 15:\r\n balls = int(input(\"How many balls do you want to use to play this game of Nim?\"))\r\n if balls < 15:\r\n print(\"Please enter a number that is equal to or higher than 15.\\n \")\r\n return balls", "def promptNum(message):\n choice = 0\n while not choice:\n choice = input(message+\" [number] \")\n try:\n int(choice)\n except:\n print(\"ERROR: Input not recognized. Choose a number\\n\")\n choice = 0\n return choice", "def get_custom_guesses_from_user():\n\n user_input = raw_input(\"How many guesses do you want? \")\n\n if not user_input.isdigit():\n print \"Please enter a number representing your number of guesses!\"\n return get_custom_guesses_from_user()\n\n lowes_valid_guesses_number = 1\n\n if int(user_input) < lowes_valid_guesses_number:\n print \"Please enter a number from 1 and upwords!\"\n return get_custom_guesses_from_user()\n\n return int(user_input)", "def bonus_balls():\n while True:\n try:\n b_balls = int(input('Enter the number of available bonus balls: '))\n break\n except:\n print('invalid input')\n\n while True:\n try:\n b_choices = int(input('Enter the amount of bonus balls to select: '))\n break\n except:\n print('invalid input')\n\n return b_balls, b_choices", "def balls():\n while True:\n try:\n balls = int(input('Enter the number of available balls: '))\n break\n except:\n print('invalid input')\n\n while True:\n try:\n choices = int(input('Enter the amount of balls to select: '))\n break\n except:\n print('invalid input')\n while True:\n try:\n cost = float(input('Enter the cost of one ticket: '))\n break\n except:\n print('invalid input')\n return balls, choices, cost", "def get_lotto_numbers(limit=99):\n count = 1\n nums = []\n while count < 6:\n rand = random.randrange(1, limit)\n if rand not in nums:\n nums.append(rand)\n count += 1\n\n return str(nums[0]) + \" \" + str(nums[1]) + \" \" + str(nums[2]) + \" \" +\\\n str(nums[3]) + \" \" + str(nums[4])", "def askForNumberOfGames():\n answer = None\n while answer == None:\n try:\n answer = int(\n input('How many number of games would you like to play? '))\n except ValueError:\n print('Not a valid number. Try again.')\n\n return answer", "def adivina_numero(): \n import random # para importar el modulo randon\n numero_aleatorio = random.randint(1, 100) #funcion randint (rand int) del modulo random\n numero_elegido = int(input('Elige un numero del 1 al 100: '))\n i=1\n while numero_elegido != numero_aleatorio:\n if numero_elegido < numero_aleatorio:\n numero_elegido= int(input('Busca un numero mas grande: '))\n else:\n numero_elegido= int(input('Busca un numero mas pequeño: '))\n i+=1\n print('¡GANASTE!')\n print('En ' +str(i) +' intentos')", "def thinker():\n while 1:\n # 3 numbers between [2..9]\n lis = sorted(sample(range(2, 10), 3))\n\n # number such that any triplet `range(10, n) % lis` is unique\n n = min(lcm(*lis) + 10, 100)\n\n giveup = randrange(10, n)\n mds = [giveup % i for i in lis]\n\n assert len({tuple(i % k for k in lis) for i in range(10, n)}) == len(range(10, n))\n\n print(\"A number between 9 and {} divided by {} {} and {} gives remainders {} {} and {}\".format(n, *lis, *mds))\n\n n = 0\n while n != giveup:\n try:\n n = eval(Input(\"What is the number? \"))\n except KeyboardInterrupt:\n return\n if n == giveup:\n print(n, \"is Correct\")\n else:\n print(n, \"is Wrong\")" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate list of random lottery numbers
def get_lotto_numbers(): number_of_lotto_numbers = 3 lotto_numbers = [] for i in range(number_of_lotto_numbers): while True: if i == number_of_lotto_numbers - 1: lotto_numbers.append(randrange(1, 26)) break else: new_number = randrange(1, 70) if new_number not in lotto_numbers: lotto_numbers.append(new_number) break return lotto_numbers
[ "def sure_lottery():\n return [0, 1, 0]", "def lottery():\n drawing_list = []\n i = 0\n while i < 6:\n pick = randint(1, 50)\n if pick not in drawing_list:\n drawing_list.append(pick)\n i += 1\n drawing_list.sort()\n return drawing_list", "def get_lotto_numbers(limit=99):\n count = 1\n nums = []\n while count < 6:\n rand = random.randrange(1, limit)\n if rand not in nums:\n nums.append(rand)\n count += 1\n\n return str(nums[0]) + \" \" + str(nums[1]) + \" \" + str(nums[2]) + \" \" +\\\n str(nums[3]) + \" \" + str(nums[4])", "def gen_rand_list(x: int, n: int) -> list:\n return [gen_rand_int(x) for _ in range(n)]", "def generate_cipher():\n # remove the pass statement and put your code here\n num_list =[]\n for i in range(4):\n \tran_num = random.randint(0, 9)\n \twhile ran_num in num_list:\n\t\tran_num = random.randint(0, 9)\t\n \tnum_list.append(ran_num)\n return num_list", "def get_lottery(lottery_nums):\n my_logger.info('Requests for %s loterries' % lottery_nums)\n try:\n random_shuangses = random_shuangse(lottery_nums)\n except Exception as e:\n my_logger.error(e)\n return jsonify({'status': 'failed', 'lotteries': [], 'msg': '接口返回错误 %s' % e})\n else:\n my_logger.info('Lotteries returned: %s' % random_shuangses)\n return jsonify({'status': 'success', 'lotteries': random_shuangses, 'msg': ''})", "def gen_rand_23():\n a = []\n for i in range(23):\n a.append(randint(1, 365))\n return a", "def clearly_random(how_many = 3):\r\n\r\n numbers = []\r\n\r\n i = 0\r\n while i < how_many:\r\n numbers.append(uniform(0,10)) \r\n i += 1\r\n\r\n print(numbers)", "def list_generator(rows: int):\n for row in range(rows):\n numbers = []\n for number in range(NUMBERS_PER_LINES):\n quick_pick = random.randint(MINIMUM, MAXIMUM)\n while quick_pick in numbers:\n quick_pick = random.randint(MINIMUM, MAXIMUM)\n numbers.append(quick_pick)\n numbers.sort()\n print(numbers)", "def list_ten_values_random_order():\n return [54, 26, 93, 17, 77, 31, 44, 55, 20, 3]", "def generate_code():\n digits = list(range(10))\n random.shuffle(digits[:3])\n print(digits[:3])\n \n return digits", "def random_list(i):\n import random\n num_list = sorted(random.sample(range(0, 100), i))\n return num_list", "def make_unqique_sorted_random_numbers(n):\n lower_bound = 0\n upper_bound = n * 10\n\n already_used_numers = set()\n\n accumulator = []\n\n while len(accumulator) < n:\n random_number = random.randint(lower_bound, upper_bound)\n if random_number not in already_used_numers:\n accumulator.append(random_number)\n already_used_numers.add(random_number)\n\n return list(sorted(accumulator))", "def get_random_values():\n digits = list(range(10))\n random.shuffle(digits)\n digits = [str(digit) for digit in digits[:3]]\n return \"\".join(digits)", "def draw_winning_ticket(self):\r\n number_taken = []\r\n ticket = []\r\n n_number = 0\r\n while len(ticket)<6:\r\n number = random.randint(1, 45)\r\n if number not in ticket:\r\n ticket.append(number)\r\n number_taken.append(number)\r\n ticket.sort()\r\n return ticket", "def select_ten():\n random_10 = set([])\n while len(random_10) < 10:\n num = randint(0,20)\n random_10.add(num)\n \n return random_10", "def getran(num, rang):\n a = []\n i = 0\n while i < num:\n a.append(random.randint(0, rang))\n i += 1\n return a", "def gen_randoms(start, stop, numEach):\n theLists = []\n for i in range(start, stop+1):\n theLists.append([])\n for j in range(numEach):\n nums = gen_random_numbers(i, 0, len(all_codes) - 1)\n codes = [all_codes[x] for x in nums]\n theLists[-1].append(codes)\n return theLists", "def genPWlist():\n pwList = []\n j = 1\n while j <= 10:\n nextPW = [genPW()]\n pwList = pwList + nextPW\n j += 1\n return pwList" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Starts the lottery game Prints amount of years it took to complete
def lottery_game(): user_numbers = get_numbers() number_of_drawings = 0 while user_numbers != get_lotto_numbers(): number_of_drawings += 1 years = round(((number_of_drawings / 2) / 52), 2) print(f"Full match took {years} years")
[ "def execute(self):\n self.yearlyStepsPerTile = self.model.sim(self.pedsPerHourOn, self.pedsPerHourOff)", "def main():\n\t\n\t# start running trials\n\t# save outcomes of trials\n\t\n\tsuccesses = 0\n\t\n\tfor trial in range(1000):\n\t\tavailable_seats = list(range(0, 100))\n\t\tsuccesses += simulate(available_seats)\n\t\n\tprint(successes/(1000))", "def main():\n\tplayer1 = Player()\n\tplayer2 = Player()\n\tplayer3 = Player()\n\tplayer1.qlagent()\n\tplayer2.human()\n\tplayer1 = player1.kind\n\tplayer2 = player2.kind\n\tpickle_in = open(\"Qlearn_new.pickle\",\"rb\")\n\tqtable = pickle.load(pickle_in)\n\n\n\tgame = tictactoe_game(player1,player2,qtable)\n\tgame.play_game()\n\n\tprint (player1 + ' as X wins:' + str(game.xwin_count))\n\tprint (player2 + ' as O wins:' + str(game.ywin_count))\n\tprint ('Draws:' + str(game.draw_count))", "def new_game(new_interval):\n\n global secret_number, num_guesses\n secret_number = random.randint(1, new_interval)\n num_guesses = int(math.log(new_interval, 2)) + 1\n\n print\n print '=============================================='\n print\n print 'New game begins! Choose a number between 1 and', new_interval\n print 'You have', num_guesses, 'guesses'\n print", "def main():\r\n # Greeting to the user\r\n print(\"Welcome to the Study Timer!\\n\")\r\n # Get the amount on time the person wants to study for\r\n study_length = study_session_length()\r\n # Ask how often they want to break\r\n break_interval = break_interval_time()\r\n # Ask the user what activities they would like to do during break\r\n shuffled_list_of_activities = activities()\r\n # Determine number of breaks\r\n number_of_breaks = number_breaks(study_length, break_interval)\r\n # Start timer\r\n interval_timer(break_interval, number_of_breaks,\r\n shuffled_list_of_activities)\r\n # Ask user to start over\r\n run_timer_again()", "def main():\n run_game(even)", "def runBingoGame(numPlayers,gameNumber):\n\tallPlayers = []\n\tfor playerNum in range(numPlayers):\n\t\tnewPlayer = bingoCard(playerNum)\n\t\tallPlayers.append(newPlayer)\n\t\tnewPlayer.seeCard()\n\t\n\tcallList = numCalls()\n\tprint 'call order: ' + str(callList) + '\\n'\n\n\t# turn = 1\n\t# winCallHistory = []\n\t# for number in callList:\n\t# \tfor player in allPlayers:\n\t# \t\tif player.stopPlaying():\n\t# \t\t\tif player.hasNumber(number):\n\t# \t\t\t\tplayer.markNumber(number)\n\t\t\t\t\n\t# \t\t\tif number not in winCallHistory:\n\t# \t\t\t\twinCallHistory.append(number)\n\t# \t\t\t# turn += 1\n\t# \t\telse:\n\t# \t\t\twinner = player\n\t# \t\t\tbreak\n\n\t\t\t# turn += 1\n\t\t\t# callHistory.append(number)\n\n\twinCallHistory = []\n\twinner = allPlayers[0]\n\tfor number in callList:\n\t\tif winner.stopPlaying():\n\t\t\tbreak\n\n\t\tfor player in allPlayers:\n\t\t\tif player.stopPlaying():\n\t\t\t\twinner = player\n\t\t\t\tbreak\n\n\t\t\telse:\n\t\t\t\tif player.hasNumber(number):\n\t\t\t\t\tplayer.markNumber(number)\n\t\t\t\t\t\n\t\tif number not in winCallHistory:\n\t\t\t\twinCallHistory.append(number)\n\n\tif winner == allPlayers[0]:\n\t\tnumTurnsToWin = len(winCallHistory)\n\telse:\n\t\tnumTurnsToWin = len(winCallHistory)-1\n\n\tif gameNumber/50 == 0:\n\t\tprint 'game number: ' + str(gameNumber) + '/1000\\n'\n\t\tprint 'turn completed: ' + str(numTurnsToWin)\n\t\tprint 'calls until win: ' + str(winCallHistory) + '\\n'\n\t\tprint 'player ' + str(winner.getCardName()) + ' won with ' + str(winner.wonWithCondition()) + '\\n'\n\t\t# print 'bingo! \\n'\n\t\tprint 'bingo! \\ncard has marked numbers: ' + str(winner.getAllMarkedNums())\n\t\tprint 'card has marked positions: ' + str(winner.getAllMarkedPos()) + '\\n'\n\n\treturn numTurnsToWin", "def test_computer_loop(self):\n\n s = 0\n for i in range(100):\n game = mastermind.ComputerPlayer()\n self.assertEqual(game.play_mastermind(), True)\n s += game.get_count_guesses()\n print(\"Średnia ilość strzałów potrzebnych od odgadnięcia kodu\\n Sprawność: \", s/100)", "def main_game_func():\n\n initialize()\n number_to_guess = generate_number_to_be_guessed()\n notify_on_code_generation()\n attempts_counter = process_input_loop(number_to_guess)\n # In case of giving up attempts_counter is set to zero. No congratulations for leavers.\n if attempts_counter > 0:\n congratulate_winner(attempts_counter)", "def tutorial():\n\tprint \"King's Decision puts you in the position of a king forced to make quick choices.\"\n\tprint \"You will be presented with a number of random situations and given a number of \"\n\tprint \"choices to choose from. You will have 15 seconds to make a snap decision; if you \"\n\tprint \"fail to come to a decision, you will automatically choose to behead the person presenting \"\n\tprint \"the case, much to the chagrin of your court and subjects. If you do this twice, the people \"\n\tprint \"will revolt and kill you.\"\n\tprint \"\\n\"\n\tprint \"The goal is to come to prudent, informed, and honorable decisions. Bad decisions will\"\n\tprint \"bring consequences, such as growing unrest among the people. If you are able to make\"\n\tprint \"good decisions five times in a row, you will win the title of 'the Great', and win the game.\"\n\tprint \"Best of luck to you, the king!\"\n\ttime.sleep(5)\n\traw_input(\"Press any key to begin the game.\")\n\tgame_start()", "def new_game():\n\n global secret_number, guesses_number\n\n if num_range == 100:\n guesses_number = 7\n elif num_range == 1000:\n guesses_number = 10\n\n secret_number = random.randrange(0, num_range)\n\n print \"New game. Range is [0,\" + str(num_range) + \")\"\n print \"Number of remaining guesses is \" + str(guesses_number)\n print", "def albums_age():\n os.system('clear')\n current_year = datetime.now().year\n music_list = music()\n print(\"The age of albums:\")\n for item in music_list:\n album_age = current_year - item[1][0]\n print(\"%s: %s - %d years old\" % (item[0][0], item[0][1], album_age))\n print(\"\\nPress enter to continue\")\n input()\n os.system('clear')", "def main():\n year = input(\"Enter a year: \")\n yearc = str(year + ':')\n wordsByYearList = printedWords(readWordFile(input('Enter the name of a file: ')))\n print(\"The amount of words printed in\", yearc, wordsForYear(int(year), wordsByYearList))\n labels = 'Year', 'Total Words'\n plot = s.plot2D('Number of Printed Words over Time', labels)\n for yc in wordsByYearList:\n point = yc.year, yc.count\n plot.addPoint(point)\n plot.display()", "def when_to_run_func(): \n global run\n run += 1\n if run == 1:\n clean_players()\n exp_players()\n team_sel()", "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 run(start_year=None, years_ago=1):\n if start_year == None:\n now = datetime.datetime.now()\n start_year = now.year\n\n assert isinstance(start_year, int)\n assert isinstance(years_ago, int)\n assert len(f\"{start_year}\") == 4\n\n for i in range(0, years_ago + 1):\n url = f\"https://www.boxofficemojo.com/year/world/{start_year}/\"\n finished = parse_and_extract(url, name=start_year)\n if finished:\n print(f\"finished {start_year}\")\n else:\n print(f\"{start_year} does data not exist\")\n start_year -= 1", "def main():\n count = 1\n while count <= 10:\n comp_num = get_random_number()\n user_num = int(input(\"\\nGuess the number (1-10): \"))\n count = compare_numbers(comp_num, user_num, count)", "def you_won():\n print(\"\\nThis is it!\")\n end = Decimal(time.time() - start)\n end = str(round(end, 1))\n global lettercount\n print(\"\\nSaving \" + capital + \" took thou \" + str(end) + \" seconds and \" + repr(lettercount) + \" letters.\")\n replay = input('Enter any number if you want to save another city, if not enter anything YOU COWARD!')\n if replay.isnumeric():\n main()\n else:\n print(\"Shame. I shall just destroy whole Europe at once. HA HA HA\")\n sys.exit()", "def do_countdown(self):\r\n if self.pilot.get() != '' and self.passord_input.get() != '':\r\n if self.launch_count >= 1:\r\n self.launch_button.config(text=self.launch_count)\r\n self.launch_count -= 1\r\n else:\r\n self.launch_button.config(text='LIFTOFF!!')\r\n\r\n # raise NotImplementedError\r" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Recon enumeration should always produce valid recons
def test_enum_recon(self): expected_recons = [ {'a': 'a', 1: 1, 'c': 'c', 3: 3, 'd': 'd', 2: 2, 'b': 'b'}, {'a': 'a', 1: 1, 'c': 'c', 3: 3, 'd': 'd', 2: 2, 'b': 'b'}, {'a': 'a', 1: 1, 'c': 'c', 3: 3, 'd': 'd', 2: 2, 'b': 'b'}, {'a': 'a', 1: 1, 'c': 'c', 3: 3, 'd': 'd', 2: 1, 'b': 'b'}, {'a': 'a', 1: 1, 'c': 'c', 3: 3, 'd': 'd', 2: 1, 'b': 'b'}, {'a': 'a', 1: 1, 'c': 'c', 3: 1, 'd': 'd', 2: 1, 'b': 'b'}, {'a': 'a', 1: 1, 'c': 'c', 3: 3, 'd': 'd', 2: 2, 'b': 'b'}, {'a': 'a', 1: 1, 'c': 'c', 3: 1, 'd': 'd', 2: 2, 'b': 'b'}, {'a': 'a', 1: 1, 'c': 'c', 3: 3, 'd': 'd', 2: 2, 'b': 'b'}, {'a': 'a', 1: 1, 'c': 'c', 3: 1, 'd': 'd', 2: 2, 'b': 'b'}, {'a': 'a', 1: 1, 'c': 'c', 3: 3, 'd': 'd', 2: 2, 'b': 'b'}, {'a': 'a', 1: 1, 'c': 'c', 3: 3, 'd': 'd', 2: 1, 'b': 'b'}, {'a': 'a', 1: 1, 'c': 'c', 3: 3, 'd': 'd', 2: 1, 'b': 'b'}, {'a': 'a', 1: 1, 'c': 'c', 3: 1, 'd': 'd', 2: 1, 'b': 'b'}, {'a': 'a', 1: 1, 'c': 'c', 3: 3, 'd': 'd', 2: 2, 'b': 'b'}, {'a': 'a', 1: 1, 'c': 'c', 3: 1, 'd': 'd', 2: 2, 'b': 'b'}, {'a': 'a', 1: 1, 'c': 'c', 3: 3, 'd': 'd', 2: 2, 'b': 'b'}, {'a': 'a', 1: 1, 'c': 'c', 3: 1, 'd': 'd', 2: 2, 'b': 'b'}, ] expected_events = [ {'a': 'gene', 1: 'spec', 'c': 'gene', 3: 'spec', 'd': 'gene', 2: 'spec', 'b': 'gene'}, {'a': 'gene', 1: 'dup', 'c': 'gene', 3: 'spec', 'd': 'gene', 2: 'spec', 'b': 'gene'}, {'a': 'gene', 1: 'dup', 'c': 'gene', 3: 'spec', 'd': 'gene', 2: 'dup', 'b': 'gene'}, {'a': 'gene', 1: 'dup', 'c': 'gene', 3: 'spec', 'd': 'gene', 2: 'dup', 'b': 'gene'}, {'a': 'gene', 1: 'dup', 'c': 'gene', 3: 'dup', 'd': 'gene', 2: 'dup', 'b': 'gene'}, {'a': 'gene', 1: 'dup', 'c': 'gene', 3: 'dup', 'd': 'gene', 2: 'dup', 'b': 'gene'}, {'a': 'gene', 1: 'dup', 'c': 'gene', 3: 'dup', 'd': 'gene', 2: 'dup', 'b': 'gene'}, {'a': 'gene', 1: 'dup', 'c': 'gene', 3: 'dup', 'd': 'gene', 2: 'dup', 'b': 'gene'}, {'a': 'gene', 1: 'dup', 'c': 'gene', 3: 'dup', 'd': 'gene', 2: 'spec', 'b': 'gene'}, {'a': 'gene', 1: 'dup', 'c': 'gene', 3: 'dup', 'd': 'gene', 2: 'spec', 'b': 'gene'}, {'a': 'gene', 1: 'spec', 'c': 'gene', 3: 'spec', 'd': 'gene', 2: 'dup', 'b': 'gene'}, {'a': 'gene', 1: 'spec', 'c': 'gene', 3: 'spec', 'd': 'gene', 2: 'dup', 'b': 'gene'}, {'a': 'gene', 1: 'spec', 'c': 'gene', 3: 'dup', 'd': 'gene', 2: 'dup', 'b': 'gene'}, {'a': 'gene', 1: 'spec', 'c': 'gene', 3: 'dup', 'd': 'gene', 2: 'dup', 'b': 'gene'}, {'a': 'gene', 1: 'spec', 'c': 'gene', 3: 'dup', 'd': 'gene', 2: 'dup', 'b': 'gene'}, {'a': 'gene', 1: 'spec', 'c': 'gene', 3: 'dup', 'd': 'gene', 2: 'dup', 'b': 'gene'}, {'a': 'gene', 1: 'spec', 'c': 'gene', 3: 'dup', 'd': 'gene', 2: 'spec', 'b': 'gene'}, {'a': 'gene', 1: 'spec', 'c': 'gene', 3: 'dup', 'd': 'gene', 2: 'spec', 'b': 'gene'}, ] tree = parse_newick("((a,b),(c,d))") stree = parse_newick("((a,b),(c,d))") gene2species = lambda x: x for i, (recon, events) in enumerate(phylo.enum_recon( tree, stree, depth=None, gene2species=gene2species)): phylo.assert_recon(tree, stree, recon) recon_names = dict((node.name, snode.name) for node, snode in recon.items()) event_names = dict((node.name, event) for node, event in events.items()) self.assertEqual(recon_names, expected_recons[i]) self.assertEqual(event_names, expected_events[i])
[ "def re_to_nfa(self, re):\n\t alphabet = CHARSET + \"\";\n\t if re.is_simple_type():\n\t if re.type == SYMBOL_RE:\n\t # pt un sg. simbol\n\t return NFA(alphabet, {0, 1}, 0, {1}, {(0, re.symbol) : frozenset({1})});\n\t elif re.type == EMPTY_STRING_RE:\n\t # pt. epsilon\n\t return NFA(alphabet, {0, 1}, 0, {1}, {(0, \"\") : frozenset({1})});\n\t else:\n\t # pt. multimea vida\n \treturn NFA(alphabet, {0}, 0, set(), {});\n\t else:\n\t if re.type == CONCATENATION_RE:\n\t nfa_left = self.re_to_nfa(re.lhs);\n\t nfa_right = self.re_to_nfa(re.rhs);\n\t self.rename_states(nfa_right, nfa_left);\n\t # construiesc alfabetul\n\t # adaug toate starile in automatul final\n\t states = nfa_left.states.union(nfa_right.states);\n\n\t for key in nfa_left.delta: \n\t if key in nfa_right.delta: \n\t nfa_left.delta[key] = nfa_left.delta[key].union(nfa_right.delta[key]);\n\t nfa_left.delta.update(nfa_right.delta);\n\t \n\t # trebuie sa am tranzitie pe \"epsilon\" din fosta stare\n\t # finala in starea initiala a celui de-al doilea automat\n\t key = (nfa_left.final_states.pop(), \"\");\n\t value = set({nfa_right.start_state});\n\n\t if key in nfa_left.delta:\n\t nfa_left.delta[key] = nfa_left.delta[key].union(value);\n\t else:\n\t nfa_left.delta.update({key: value});\n\t # returnez noul automat\n\t return NFA(alphabet, states, nfa_left.start_state, nfa_right.final_states, nfa_left.delta);\n\t \n\t elif re.type == ALTERNATION_RE:\n\t # adaug o stare initiala si una finala\n\t # si tranzitii din starea initiala pe \"epsilon\" catre urm. stare\n\t # si din ultima stare pe \"epsilon\" catre starea finala adaugata\n\t nfa_left = self.re_to_nfa(re.lhs);\n\t nfa_right = self.re_to_nfa(re.rhs);\n\t self.rename_states(nfa_right, nfa_left);\n\t state_init, state_final = self.new_states(nfa_left, nfa_right);\n\t states = nfa_left.states.union(nfa_right.states).union({state_init, state_final});\n\t \n\t for key in nfa_left.delta: \n\t if key in nfa_right.delta: \n\t nfa_left.delta[key] = nfa_left.delta[key].union(nfa_right.delta[key]); \n\t nfa_left.delta.update(nfa_right.delta);\n\t \n\t key = (nfa_left.final_states.pop(), \"\");\n\t value = frozenset({state_final});\n\t if key in nfa_left.delta:\n\t nfa_left.delta[key] = nfa_left.delta[key].union(value);\n\t else:\n\t nfa_left.delta.update({key: value});\n\n\t key = (nfa_right.final_states.pop(), \"\");\n\t value = frozenset({state_final});\n\t if key in nfa_left.delta:\n\t nfa_left.delta[key] = nfa_left.delta[key].union(value);\n\t else:\n\t nfa_left.delta.update({key: value});\n\t \n\t nfa_left.delta.update({(state_init, \"\"): frozenset({nfa_left.start_state}).union( \n\t frozenset({nfa_right.start_state}))});\n\t # returnez noul automat format prin \"reuniune\"\n\t return NFA(alphabet, states, state_init, {state_final}, nfa_left.delta);\n\n\t else:\n\t # inseamna ca am e*\n\t # trebuie sa adaug doua tranzitii pe \"epsilon\":\n\t # de la starea initiala la starea finala\n\t # de la starea finala la starea initiala\n\t nfa_left = self.re_to_nfa(re.lhs);\n\t key = (next(iter(nfa_left.final_states)), \"\");\n\t value = frozenset({nfa_left.start_state});\n\t if key in nfa_left.delta:\n\t nfa_left.delta[key] = nfa_left.delta[key].union(value);\n\t else:\n\t nfa_left.delta.update({key: value});\n\n\t key = (nfa_left.start_state, \"\");\n\t value = frozenset(nfa_left.final_states);\n\t if key in nfa_left.delta:\n\t nfa_left.delta[key] = nfa_left.delta[key].union(value);\n\t else:\n\t nfa_left.delta.update({key: value});\n\n\t return nfa_left", "def test_irreversible_reaction(self):\n\n reactant = [Molecule(smiles='O=O')]\n reaction_list = self.database.kinetics.families['Singlet_Val6_to_triplet'].generate_reactions(reactant)\n self.assertFalse(reaction_list[0].reversible)", "def testEnumValueRemoval(self):\n self.assertNotBackwardCompatible('enum E { kFoo, kBar };',\n 'enum E { kFoo };')\n self.assertNotBackwardCompatible(\n '[Extensible] enum E { [Default] kFoo, kBar };',\n '[Extensible] enum E { [Default] kFoo };')\n self.assertNotBackwardCompatible(\n '[Extensible] enum E { [Default] kA, [MinVersion=1] kB };',\n '[Extensible] enum E { [Default] kA, };')\n self.assertNotBackwardCompatible(\n \"\"\"[Extensible] enum E {\n [Default] kA,\n [MinVersion=1] kB,\n [MinVersion=1] kZ };\"\"\",\n '[Extensible] enum E { [Default] kA, [MinVersion=1] kB };')", "def testNewNonExtensibleEnumValue(self):\n self.assertNotBackwardCompatible('enum E { kFoo, kBar };',\n 'enum E { kFoo, kBar, kBaz };')", "def test_iterconstantsIdentity(self):\n constants = list(self.STATUS.iterconstants())\n again = list(self.STATUS.iterconstants())\n self.assertIs(again[0], constants[0])\n self.assertIs(again[1], constants[1])", "def test_iter(self):\n\n enum = self.test_construct()\n\n _struct = {\n 'BLUE': 0x0,\n 'RED': 0x1,\n 'GREEN': 0x2}\n\n for key, value in enum:\n assert key in _struct\n assert _struct[key] is value\n _struct[key] = True\n\n assert all(_struct.itervalues()) # make sure all values touched", "def test_parse_works(): # noqa: PLR0915\n scheme = rx.parse_reactions(\"A -> B // a direct reaction\")\n assert scheme[0] == (\"A\", \"B\")\n assert scheme[1] == (\"A -> B\",)\n assert scheme[2] == (False,)\n assert np.all(scheme[3] == scheme[4])\n assert np.all(np.array([[-1], [1]]) == scheme[3])\n\n scheme = rx.parse_reactions(\"B <- A // reverse reaction of the above\")\n assert scheme[0] == (\"A\", \"B\")\n assert scheme[1] == (\"A -> B\",)\n assert scheme[2] == (False,)\n assert np.all(scheme[3] == scheme[4])\n assert np.all(np.array([[-1], [1]]) == scheme[3])\n\n scheme = rx.parse_reactions(\"A <=> B // an equilibrium\")\n assert scheme[0] == (\"A\", \"B\")\n assert scheme[1] == (\"A -> B\", \"B -> A\")\n assert np.all(np.array([True, True]) == scheme[2])\n assert np.all(np.array([[-1.0, 1.0], [1.0, -1.0]]) == scheme[3])\n assert np.all(np.array([[-1.0, 0.0], [1.0, 0.0]]) == scheme[4])\n\n scheme = rx.parse_reactions(\n \"\"\"A <=> B -> A // a lot of\n A -> B <=> A // repeated\n A -> B <- A // reactions\n B <- A -> B\"\"\",\n )\n assert scheme[0] == (\"A\", \"B\")\n assert scheme[1] == (\"A -> B\", \"B -> A\")\n assert np.all(np.array([True, True]) == scheme[2])\n assert np.all(np.array([[-1.0, 1.0], [1.0, -1.0]]) == scheme[3])\n assert np.all(np.array([[-1.0, 0.0], [1.0, 0.0]]) == scheme[4])\n\n scheme = rx.parse_reactions(\"A -> A‡ -> B // a transition state\")\n assert scheme[0] == (\"A\", \"A‡\", \"B\")\n assert scheme[1] == (\"A -> B\",)\n assert scheme[2] == (False,)\n assert np.all(np.array([[-1.0], [0.0], [1.0]]) == scheme[3])\n assert np.all(np.array([[-1.0], [1.0], [0.0]]) == scheme[4])\n\n scheme = rx.parse_reactions(\"A -> A‡ -> B <- A‡ <- A // (should be) same as above\")\n assert scheme[0] == (\"A\", \"A‡\", \"B\")\n assert scheme[1] == (\"A -> B\",)\n assert scheme[2] == (False,)\n assert np.all(np.array([[-1.0], [0.0], [1.0]]) == scheme[3])\n assert np.all(np.array([[-1.0], [1.0], [0.0]]) == scheme[4])\n\n scheme = rx.parse_reactions(\n \"\"\"\n B -> B‡ -> C // chained reactions and transition states\n B‡ -> D // this is a bifurcation\n B -> B'‡ -> E // this is a classical competitive reaction\n A -> B‡\n \"\"\",\n )\n assert scheme[0] == (\"B\", \"B‡\", \"C\", \"D\", \"B'‡\", \"E\", \"A\")\n assert scheme[1] == (\"B -> C\", \"B -> D\", \"B -> E\", \"A -> C\", \"A -> D\")\n assert np.all(np.array([False, False, False, False, False]) == scheme[2])\n assert np.all(\n np.array(\n [\n [-1.0, -1.0, -1.0, 0.0, 0.0],\n [0.0, 0.0, 0.0, 0.0, 0.0],\n [1.0, 0.0, 0.0, 1.0, 0.0],\n [0.0, 1.0, 0.0, 0.0, 1.0],\n [0.0, 0.0, 0.0, 0.0, 0.0],\n [0.0, 0.0, 1.0, 0.0, 0.0],\n [0.0, 0.0, 0.0, -1.0, -1.0],\n ],\n )\n == scheme[3],\n )\n assert np.all(\n np.array(\n [\n [-1.0, -1.0, -1.0, 0.0, 0.0],\n [1.0, 1.0, 0.0, 1.0, 1.0],\n [0.0, 0.0, 0.0, 0.0, 0.0],\n [0.0, 0.0, 0.0, 0.0, 0.0],\n [0.0, 0.0, 1.0, 0.0, 0.0],\n [0.0, 0.0, 0.0, 0.0, 0.0],\n [0.0, 0.0, 0.0, -1.0, -1.0],\n ],\n )\n == scheme[4],\n )\n\n scheme = rx.parse_reactions(\n \"\"\"// when in doubt, reactions should be considered distinct\n A -> A‡ -> B // this is a tricky example\n A -> B // but it's better to be explicit\"\"\",\n )\n assert scheme[0] == (\"A\", \"A‡\", \"B\")\n assert scheme[1] == (\"A -> B\", \"A -> B\")\n assert np.all(np.array([False, False]) == scheme[2])\n assert np.all(np.array([[-1.0, -1.0], [0.0, 0.0], [1.0, 1.0]]) == scheme[3])\n assert np.all(np.array([[-1.0, -1.0], [1.0, 0.0], [0.0, 1.0]]) == scheme[4])\n\n scheme = rx.parse_reactions(\n \"\"\"\n // the policy is to not chain transition states\n A -> A‡ -> A'‡ -> B // this is weird\"\"\",\n )\n assert scheme[0] == (\"A\", \"A‡\", \"A'‡\", \"B\")\n assert scheme[1] == (\"A -> A'‡\",)\n assert scheme[2] == (False,)\n assert np.all(np.array([[-1.0], [0.0], [1.0], [0.0]]) == scheme[3])\n assert np.all(np.array([[-1.0], [1.0], [0.0], [0.0]]) == scheme[4])", "def testNewValueInExistingVersion(self):\n self.assertNotBackwardCompatible(\n '[Extensible] enum E { [Default] kFoo, kBar };',\n 'enum E { kFoo, kBar, kBaz };')\n self.assertNotBackwardCompatible(\n '[Extensible] enum E { [Default] kFoo, kBar };',\n '[Extensible] enum E { [Default] kFoo, kBar, kBaz };')\n self.assertNotBackwardCompatible(\n '[Extensible] enum E { [Default] kFoo, [MinVersion=1] kBar };',\n 'enum E { kFoo, [MinVersion=1] kBar, [MinVersion=1] kBaz };')", "def gen_reactions(self):\n model = self.model\n cell = self.knowledge_base.cell\n nucleus = model.compartments.get_one(id='n')\n mitochondrion = model.compartments.get_one(id='m')\n cytoplasm = model.compartments.get_one(id='c')\n\n rna_input_seq = self.options['rna_input_seq']\n \n # Get species involved in reaction\n metabolic_participants = ['amp', 'cmp', 'gmp', 'ump', 'h2o', 'h']\n metabolites = {}\n for met in metabolic_participants:\n met_species_type = model.species_types.get_one(id=met)\n metabolites[met] = {\n 'c': met_species_type.species.get_or_create(compartment=cytoplasm, model=model),\n 'm': met_species_type.species.get_or_create(compartment=mitochondrion, model=model)\n }\n\n self.submodel.framework = wc_ontology['WC:next_reaction_method'] \n\n print('Start generating RNA degradation submodel...')\n # Create reaction for each RNA and get exosome\n rna_exo_pair = self.options.get('rna_exo_pair')\n ribosome_occupancy_width = self.options['ribosome_occupancy_width']\n rna_kbs = cell.species_types.get(__type=wc_kb.eukaryote.TranscriptSpeciesType)\n self._degradation_modifier = {}\n deg_rxn_no = 0\n for rna_kb in rna_kbs: \n\n rna_kb_compartment_id = rna_kb.species[0].compartment.id\n if rna_kb_compartment_id == 'c':\n rna_compartment = cytoplasm\n degradation_compartment = cytoplasm\n else:\n rna_compartment = mitochondrion\n degradation_compartment = mitochondrion \n \n rna_model = model.species_types.get_one(id=rna_kb.id).species.get_one(compartment=rna_compartment)\n reaction = model.reactions.get_or_create(submodel=self.submodel, id='degradation_' + rna_kb.id)\n reaction.name = 'degradation of ' + rna_kb.name\n \n if rna_kb.id in gvar.transcript_ntp_usage:\n ntp_count = gvar.transcript_ntp_usage[rna_kb.id]\n else:\n if rna_kb.id in rna_input_seq:\n seq = rna_input_seq[rna_kb.id]\n else: \n seq = rna_kb.get_seq()\n ntp_count = gvar.transcript_ntp_usage[rna_kb.id] = {\n 'A': seq.upper().count('A'),\n 'C': seq.upper().count('C'),\n 'G': seq.upper().count('G'),\n 'U': seq.upper().count('U'),\n 'len': len(seq)\n }\n \n # Adding participants to LHS\n reaction.participants.append(rna_model.species_coefficients.get_or_create(coefficient=-1))\n reaction.participants.append(metabolites['h2o'][\n degradation_compartment.id].species_coefficients.get_or_create(coefficient=-(ntp_count['len']-1)))\n\n ribo_binding_site_st = model.species_types.get_one(id='{}_ribosome_binding_site'.format(rna_kb.id))\n if ribo_binding_site_st:\n ribo_binding_site_species = ribo_binding_site_st.species[0]\n site_per_rna = math.floor(ntp_count['len']/ribosome_occupancy_width) + 1\n reaction.participants.append(ribo_binding_site_species.species_coefficients.get_or_create(\n coefficient=-site_per_rna))\n\n # Adding participants to RHS\n reaction.participants.append(metabolites['amp'][\n degradation_compartment.id].species_coefficients.get_or_create(coefficient=ntp_count['A']))\n reaction.participants.append(metabolites['cmp'][\n degradation_compartment.id].species_coefficients.get_or_create(coefficient=ntp_count['C']))\n reaction.participants.append(metabolites['gmp'][\n degradation_compartment.id].species_coefficients.get_or_create(coefficient=ntp_count['G']))\n reaction.participants.append(metabolites['ump'][\n degradation_compartment.id].species_coefficients.get_or_create(coefficient=ntp_count['U']))\n reaction.participants.append(metabolites['h'][\n degradation_compartment.id].species_coefficients.get_or_create(coefficient=ntp_count['len']-1))\n \n # Assign modifier\n self._degradation_modifier[reaction.name] = model.species_types.get_one(\n name=rna_exo_pair[rna_kb.id]).species.get_one(compartment=degradation_compartment)\n\n deg_rxn_no += 1\n print('{} RNA degradation reactions have been generated'.format(deg_rxn_no))", "def reprEnum(e, typ):\n e = int(e)\n n = typ[\"node\"]\n flags = int(typ[\"flags\"])\n # 1 << 2 is {ntfEnumHole}\n if ((1 << 2) & flags) == 0:\n o = e - int(n[\"sons\"][0][\"offset\"])\n if o >= 0 and 0 < int(n[\"len\"]):\n return n[\"sons\"][o][\"name\"].string(\"utf-8\", \"ignore\")\n else:\n # ugh we need a slow linear search:\n s = n[\"sons\"]\n for i in range(0, int(n[\"len\"])):\n if int(s[i][\"offset\"]) == e:\n return s[i][\"name\"].string(\"utf-8\", \"ignore\")\n\n return str(e) + \" (invalid data!)\"", "def test_immutable(self):\n\n enum = self.test_construct()\n\n # disallow new properties\n with self.assertRaises(NotImplementedError):\n enum['BLACK'] = 0x5\n\n with self.assertRaises(NotImplementedError):\n enum.BLACK = 0x5\n\n # disallow overwrites too\n with self.assertRaises(NotImplementedError):\n enum['GREEN'] = 0x5\n\n with self.assertRaises(NotImplementedError):\n enum.GREEN = 0x5\n\n # make sure nothing changed\n assert enum['GREEN'] is enum.GREEN is 0x2", "def test_from_rmg_reaction(self):\n rmg_rxn_1 = Reaction(reactants=[Species(label='nC3H7', smiles='[CH2]CC')],\n products=[Species(label='iC3H7', smiles='C[CH]C')])\n rxn_1 = ARCReaction(rmg_reaction=rmg_rxn_1)\n self.assertEqual(rxn_1.label, 'nC3H7 <=> iC3H7')\n\n rmg_rxn_2 = Reaction(reactants=[Species(label='OH', smiles='[OH]'), Species(label='OH', smiles='[OH]')],\n products=[Species(label='O', smiles='[O]'), Species(label='H2O', smiles='O')])\n rxn_2 = ARCReaction(rmg_reaction=rmg_rxn_2)\n self.assertEqual(rxn_2.label, 'OH + OH <=> O + H2O')", "def testScalar_Enum(self):\n self.scalarGetAndCheck(\"snimpyEnum\", \"down\")", "def test07_unnamed_enum(self):\n\n import cppyy\n\n assert cppyy.gbl.fragile is cppyy.gbl.fragile\n fragile = cppyy.gbl.fragile\n assert cppyy.gbl.fragile is fragile\n\n g = fragile.G()", "def check_enum(self):\n # Check names duplicates\n names = [e.name for e in self.entries]\n if len(names) != len(set(names)):\n dups = set([n for n in names if names.count(n) > 1])\n raise ValueError(\"found %s duplicated in %s\"\n % (''.join(dups), self.name))\n # Check values duplicates\n vals = [e.value for e in self.entries]\n if len(vals) != len(set(vals)):\n dups = set([str(n) for n in vals if vals.count(n) > 1])\n raise ValueError(\"found value %s used for more than one name in %s\"\n % (' '.join(dups), self.name))", "def _set_irreps(self):\n # the totally symmetric irrep must always be the first element of elements\n if self.pg == 'cn':\n if self.n == 1:\n # C1\n a = IrreducibleRepresentation(self, (1,))\n self.elements = FrozenOrderedBidict({ 'a': a })\n # besser: dimensions?\n self.symop_multiplicity = (1,)\n self.order = 1\n\n if self.pg == 'cnv':\n if self.n == 2:\n # C2v\n a1 = IrreducibleRepresentation(self, (1, 1, 1, 1))\n a2 = IrreducibleRepresentation(self, (1, 1,-1,-1))\n b1 = IrreducibleRepresentation(self, (1,-1, 1,-1))\n b2 = IrreducibleRepresentation(self, (1,-1,-1, 1))\n self.elements = FrozenOrderedBidict({ 'a1': a1, 'a2': a2, 'b1': b1, 'b2': b2 })\n self.symop_multiplicity = (1, 1, 1, 1)\n self.order = 4\n\n if self.pg == 'dn':\n if self.n == 3:\n # D3\n a1 = IrreducibleRepresentation(self, (1, 1, 1))\n a2 = IrreducibleRepresentation(self, (1, 1,-1))\n e = IrreducibleRepresentation(self, (2,-1, 0), degenerate=True)\n self.elements = FrozenOrderedBidict({ 'a1': a1, 'a2': a2, 'e': e })\n self.symop_multiplicity = (1, 2, 3)\n self.order = 6\n\n if self.pg == 'dnh':\n if self.n == 2:\n # D2h\n ag = IrreducibleRepresentation(self, (1, 1, 1, 1, 1, 1, 1, 1))\n b1g = IrreducibleRepresentation(self, (1, 1,-1,-1, 1, 1,-1,-1))\n b2g = IrreducibleRepresentation(self, (1,-1,-1, 1, 1,-1, 1,-1))\n b3g = IrreducibleRepresentation(self, (1,-1, 1,-1, 1,-1,-1, 1))\n au = IrreducibleRepresentation(self, (1, 1, 1, 1,-1,-1,-1,-1))\n b1u = IrreducibleRepresentation(self, (1, 1,-1,-1,-1,-1, 1, 1))\n b2u = IrreducibleRepresentation(self, (1,-1,-1, 1,-1, 1,-1, 1))\n b3u = IrreducibleRepresentation(self, (1,-1, 1,-1,-1, 1, 1,-1))\n self.elements = FrozenOrderedBidict({ 'ag': ag, 'b1g': b1g, 'b2g': b2g, 'b3g': b3g,\n 'au': au, 'b1u': b1u, 'b2u': b2u, 'b3u': b3u })\n self.symop_multiplicity = (1, 1, 1, 1, 1, 1, 1, 1)\n self.order = 8\n\n if self.n == 6:\n # D6h\n a1g = IrreducibleRepresentation(self, (1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1))\n a2g = IrreducibleRepresentation(self, (1, 1, 1, 1,-1,-1, 1, 1, 1, 1,-1,-1))\n b1g = IrreducibleRepresentation(self, (1,-1, 1,-1, 1,-1, 1, 1,-1,-1,-1, 1))\n b2g = IrreducibleRepresentation(self, (1,-1, 1,-1,-1, 1, 1, 1,-1,-1, 1,-1))\n e1g = IrreducibleRepresentation(self, (2, 1,-1,-2, 0, 0, 2,-1, 1,-2, 0, 0), degenerate=True)\n e2g = IrreducibleRepresentation(self, (2,-1,-1, 2, 0, 0, 2,-1,-1, 2, 0, 0), degenerate=True)\n a1u = IrreducibleRepresentation(self, (1, 1, 1, 1, 1, 1,-1,-1,-1,-1,-1,-1))\n a2u = IrreducibleRepresentation(self, (1, 1, 1, 1,-1,-1,-1,-1,-1,-1, 1, 1))\n b1u = IrreducibleRepresentation(self, (1,-1, 1,-1, 1,-1,-1,-1, 1, 1, 1,-1))\n b2u = IrreducibleRepresentation(self, (1,-1, 1,-1,-1, 1,-1,-1, 1, 1,-1, 1))\n e1u = IrreducibleRepresentation(self, (2, 1,-1,-2, 0, 0,-2, 1,-1, 2, 0, 0), degenerate=True)\n e2u = IrreducibleRepresentation(self, (2,-1,-1, 2, 0, 0,-2, 1, 1,-2, 0, 0), degenerate=True)\n self.elements = FrozenOrderedBidict({ 'a1g': a1g, 'a2g': a2g, 'b1g': b1g, 'b2g': b2g, 'e1g': e1g, 'e2g': e2g,\n 'a1u': a1u, 'a2u': a2u, 'b1u': b1u, 'b2u': b2u, 'e1u': e1u, 'e2u': e2u })\n self.symop_multiplicity = (1, 2, 2, 1, 3, 3, 1, 2, 2, 1, 3, 3)\n self.order = 24", "def testRenameEnumValue(self):\n self.assertBackwardCompatible('enum E { kA, kB };', 'enum E { kX, kY };')", "def test_abstract(self):\n\n with self.assertRaises(TypeError):\n struct.BidirectionalEnum()", "def RefractionIndexBlue(self):\n pass" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a design matrix with features given by radial basis functions. `n_centers` Gaussian kernels are placed along data dimension, equidistant between the minimum and the maximum along that dimension. The result then contains one column for each of the Kernels.
def rbf(X, n_centers): mn = X.min(axis=0) mx = X.max(axis=0) pivots = [] for i, j in itertools.izip(mn, mx): _tmp = np.linspace(i, j, n_centers + 2) pivots.append(_tmp[1:-1]) Y = [] for row in X: _row = [] for r, cs in itertools.izip(row, pivots): width = cs[1] - cs[0] for c in cs: e = np.exp(-0.5 * ((r - c) / width)**2) _row.append(e) Y.append(_row) return np.asarray(Y)
[ "def get_indices_clusters(self, centers):\n\n assert self.get_size() > 0, \"set is empty\"\n centers_size = centers.get_size()\n assert centers_size > 0, \"no centers given\"\n\n self_size = self.get_size()\n dim = self.dim\n self_displacements = self.displacements\n self_spans = self.spans\n self_weights = self.weights\n centers_points = centers.points\n centers_weights = centers.weights\n\n centers_points_repeat_each_row = np.repeat(centers_points, self_size, axis=0).reshape(-1,\n dim) # this is a size*k-simensional vector, where the i-th element is center[j], where j=i/k\n a = np.where(np.isnan(centers_points))\n b = np.where(np.isnan(centers_points_repeat_each_row))\n a_flag = b_flag = False\n if np.sum(a) > 0:\n a_flag = True\n if np.sum(b) > 0:\n b_flag = True\n displacements_repeat_all = np.repeat(self_displacements.reshape(1, -1), centers_size, axis=0).reshape(-1,\n dim) # repeating the displacement for the sum of squared distances calculation from each center for all the lines\n spans_repeat_all = np.repeat(self_spans.reshape(1, -1), centers_size, axis=0).reshape(-1,\n dim) # repeating the displacement for the sum of squared distances calculation from each center for all the lines\n centers_minus_displacements = centers_points_repeat_each_row - displacements_repeat_all\n centers_minus_displacements_squared_norms = np.sum(\n np.multiply(centers_minus_displacements, centers_minus_displacements), axis=1)\n centers_minus_displacements_dot_spans = np.multiply(centers_minus_displacements, spans_repeat_all)\n centers_minus_displacements_dot_spans_squared_norms = np.sum(\n np.multiply(centers_minus_displacements_dot_spans, centers_minus_displacements_dot_spans), axis=1)\n a = np.where(np.isnan(centers_minus_displacements_squared_norms))\n b = np.where(np.isnan(centers_minus_displacements_dot_spans_squared_norms))\n a_flag = b_flag = False\n if np.sum(a) > 0:\n a_flag = True\n if np.sum(b) > 0:\n b_flag = True\n all_unwighted_distances = centers_minus_displacements_squared_norms - centers_minus_displacements_dot_spans_squared_norms\n self_weights_repeat_all = np.repeat(self_weights.reshape(-1, 1), centers_size, axis=0).reshape(-1, 1)\n centers_weights_repeat_each_row = np.repeat(centers_weights, self_size, axis=0).reshape(-1, 1)\n total_weights = np.multiply(self_weights_repeat_all, centers_weights_repeat_each_row)\n all_weighted_distances = np.multiply(all_unwighted_distances.reshape(-1, 1), total_weights.reshape(-1, 1))\n all_distances = (all_weighted_distances).reshape(-1, self_size)\n\n # sum_of_squared_distances_reshaped = sum_of_squared_distances.reshape(-1,size)\n # sum_of_squared_distances_reshaped_mins = np.min(all_distances, axis=0) #this is a size-dimensional vector, where the i-th element contains the smallest distance from the i-th line to the given set of centers\n cluster_indices = np.argmin(all_distances.T,\n axis=1) # the i-th element in this array contains the index of the cluster the i-th line was clusterd into.\n if np.min(all_distances) < 0:\n x = 2\n return cluster_indices", "def synthetic_image_maker(x_centroids, y_centroids, fwhm=2.5):\n # Construct synthetic images from centroid/flux data.\n synthetic_image = np.zeros((1024, 1024))\n sigma = fwhm/2.355\n for i in range(len(x_centroids)):\n # Cut out little boxes around each source and add in Gaussian representations. This saves time.\n int_centroid_x = int(np.round(x_centroids[i]))\n int_centroid_y = int(np.round(y_centroids[i]))\n y_cut, x_cut = np.mgrid[int_centroid_y-10:int_centroid_y +\n 10, int_centroid_x-10:int_centroid_x+10]\n dist = np.sqrt((x_cut-x_centroids[i])**2+(y_cut-y_centroids[i])**2)\n synthetic_image[y_cut,\n x_cut] += np.exp(-((dist)**2/(2*sigma**2)+((dist)**2/(2*sigma**2))))\n return(synthetic_image)", "def createVectors(start, centers):\n\tout = []\n\ti = 0\n\twhile(i < len(centers)):\n\t\tout.append(getNormalisedVector(getVector(start, centers[i])))\n\t\ti += 1\n\treturn out", "def _generate_mask(sigma, kernel_size):\n center = floor(kernel_size/2)\n gf = np.empty((kernel_size, kernel_size), dtype=float)\n for i in range(0, kernel_size):\n for j in range(0, kernel_size):\n x = fabs(center - i)\n y = fabs(center - j)\n gf[i][j] = (1/(2*PI*sigma*sigma))*pow(EULER, -((x*x + y*y) / (2*sigma)))\n # normalization\n sum_of_all_values = sum(sum(gf))\n for i in range(len(gf)):\n for j in range(len(gf[i])):\n gf[i][j] = gf[i][j]/sum_of_all_values\n return gf", "def density_cluster(Data,iradius, Clusters): #This function classifies data points into clusters and noise points", "def make_gaussian_prf(size):\n fwhm_num = 10\n fwhms = np.arange(1, fwhm_num+1)\n prfs = np.zeros((size, size, size*size*fwhm_num))\n\n for k in range(fwhm_num):\n for i in range(size):\n for j in range(size):\n idx = k*size*size + i*size + j\n prfs[:, :, idx] = make_2d_gaussian(size, fwhm=fwhms[k],\n center=(j, i))\n return prfs", "def createGaborKernels (inclinations=[0,30,60,90,120,150],kernel_size=9,pos_var=16,pos_w=10, pos_psi=90):\n\n\tif kernel_size%2==0:\n\t\tkernel_size+=1\n\n\tresultKernels = []\n\n\tfor pos_phase in inclinations:\n\t\tvar = pos_var/10.0\n\t\tw = pos_w/10.0\n\t\tphase = pos_phase*CV_PI/180.0\n\t\tpsi = CV_PI*pos_psi/180.0\n \n\t\tkernel = cvCreateMat(kernel_size,kernel_size,CV_32FC1)\n\t\tcvZero(kernel)\n\n\t\tfor x in range(-kernel_size/2+1,kernel_size/2+1):\n \t\tfor y in range(-kernel_size/2+1,kernel_size/2+1):\n\t\t\t\tkernel_val = exp( -((x*x)+(y*y))/(2*var))*cos( w*x*cos(phase)+w*y*sin(phase)+psi)\n\t\t\t\tcvSet2D(kernel,y+kernel_size/2,x+kernel_size/2,cvScalar(kernel_val))\n\n\t\tresultKernels.append(kernel)\n\n\treturn resultKernels", "def get_gaussians_2d(k=8, n=128, std=0.05):\r\n\r\n angles = np.linspace(start=0, stop=2 * np.pi, num=k, endpoint=False)\r\n centers = np.stack([np.cos(angles), np.sin(angles)], axis=1)\r\n\r\n # Create an empty array that will contain the generated points.\r\n points = np.empty(shape=(k * n, 2), dtype=np.float64)\r\n\r\n # For each one of the k centers, generate the points by sampling from a normal distribution in each axis.\r\n for i in range(k):\r\n points[i * n: i * n + n, 0] = np.random.normal(loc=centers[i, 0], scale=std, size=n)\r\n points[i * n: i * n + n, 1] = np.random.normal(loc=centers[i, 1], scale=std, size=n)\r\n\r\n plt.figure()\r\n plt.scatter(points[:, 0], points[:, 1], s=5)\r\n plt.show()\r\n\r\n return points", "def get_patches(self, centers, verbose=False):\n\n if not np.iterable(centers): # if centers is a number\n self.ncen = centers\n nsample = self.pos.shape[0] // 2\n self.km = krd.kmeans_sample(self.pos, ncen=self.ncen,\n nsample=nsample, verbose=verbose)\n if not self.km.converged:\n self.km.run(self.pos, maxiter=100)\n self.centers = self.km.centers\n else: # if centers is an array of RA, DEC pairs\n assert len(centers.shape) == 2 # shape should be (:, 2)\n self.km = krd.KMeans(centers)\n self.centers = centers\n self.ncen = len(centers)\n\n self.labels = self.km.find_nearest(self.pos).astype(int)\n self.sub_labels = np.unique(self.labels)\n\n # indexes of clusters for subsample i\n self.indexes = [np.where(self.labels != ind)[0]\n for ind in self.sub_labels]\n\n # indexes of clusters not in subsample i\n self.non_indexes = [np.where(self.labels == ind)[0]\n for ind in self.sub_labels]\n\n self.dsx_sub = np.zeros(shape=(self.nbin, self.ncen))\n self.dst_sub = np.zeros(shape=(self.nbin, self.ncen))", "def render_gaussian_hmap(centers, shape, sigma=None):\n if sigma is None:\n sigma = shape[0] / 40\n x = [i for i in range(shape[1])]\n y = [i for i in range(shape[0])]\n xx, yy = np.meshgrid(x, y)\n xx = np.reshape(xx.astype(np.float32), [shape[0], shape[1], 1])\n yy = np.reshape(yy.astype(np.float32), [shape[0], shape[1], 1])\n x = np.reshape(centers[:,1], [1, 1, -1])\n y = np.reshape(centers[:,0], [1, 1, -1])\n distance = np.square(xx - x) + np.square(yy - y)\n hmap = np.exp(-distance / (2 * sigma**2 )) / np.sqrt(2 * np.pi * sigma**2)\n hmap /= (\n np.max(hmap, axis=(0, 1), keepdims=True) + np.finfo(np.float32).eps\n )\n return hmap", "def radial_distribution_function(nbins=50):\n\n # Array of distances\n dist = rdf_distances(system.pos/force.sigma, system.L/force.sigma, np.zeros(system.N*(system.N-1)))\n\n max_dist = 0.5*system.L[0]/force.sigma\n bins = np.linspace(0., max_dist, nbins)\n rdf = nrdf(bins, np.zeros(len(bins)-1, dtype = np.float), dist, system.N, system.rho*force.sigma**3)\n\n\n # Coordination Number\n #n_c = 4*np.pi*system.rho * np.cumsum(rdf*bins[1]*bins[1:]**2)\n\n # Isothermal Compressibility\n #kt = 4*np.pi*np.cumsum((rdf-1) * bins[1]*force.sigma * (bins[1:]*force.sigma)**2)/system.T/const.KB + 1/(const.KB * system.T * system.rho)\n #tot_area = 4*np.pi*np.sum(rdf*bins[1]*force.sigma)*system.L[0]**2\n #kt = (1/const.KB*system.T)*(1/system.rho + tot_area - 4/3*np.pi*system.L[0]**3)\n integral = isothermal_integral(rdf, bins[1:]*force.sigma)\n kt = 1/const.KB/system.T/system.rho + 4*np.pi*integral/const.KB/system.T\n return rdf, bins[1:], kt", "def generate_heatmaps(norm_marks, map_size=(64, 64), sigma=3):\n maps = []\n width, height = map_size\n for norm_mark in norm_marks:\n x = width * norm_mark[0]\n y = height * norm_mark[1]\n heatmap = generate_heatmap(map_size, (x, y), sigma)\n maps.append(heatmap)\n maps = np.array(maps,dtype=np.float32)\n return np.einsum(\"kij->ijk\",maps)", "def create_kernel(n=5, geom=\"square\", kernel=None):\n if kernel is None:\n if geom == \"square\":\n k = np.ones((n,n))\n elif geom == \"round\":\n xind, yind = np.indices((n, n))\n c = n // 2\n center = (c, c)\n radius = c / 2\n\n circle = (xind - center[0])**2 + (yind - center[1])**2 < radius**2\n k = circle.astype(np.int)\n else:\n k = kernel\n \n return k", "def init_centers(X, k):\n samples = np.random.choice(len(X), size=k, replace=False)\n return X[samples, :]", "def __compute_cluster_centers(self):\n center = dict()\n for index,class_key in enumerate(self.classes):\n membership_list = np.array([mb[index] for mb in self.df.membership])\n membership_list = membership_list**self.m\n num = np.dot(membership_list, self.X)\n den = np.sum(membership_list)\n center[class_key] = num/den\n return center", "def get_nm_interp(magnitude, centers, n_m_dist):\n \n return np.interp(magnitude, centers, n_m_dist)", "def normal2d_density_array(nrows, ncols, sigma_x=1, sigma_y=1, rho=0, mu_x=None, mu_y=None, normalized=True):\n x = np.arange(0, nrows)\n y = np.reshape(np.arange(0, ncols), (ncols, 1))\n # y = x[:, np.newaxis]\n\n if mu_x is None:\n mu_x = nrows // 2\n if mu_y is None:\n mu_y = ncols // 2\n\n density = normal2d_density(\n x, y, mu_x, mu_y, sigma_x, sigma_y, rho, normalized)\n\n return density", "def _new_centers(self, X, closest, K):\n mus = np.zeros((K, X.shape[1]))\n closest = np.array(closest)\n global_mean = None\n for i in range(K):\n idx = closest == i\n X_ = X[idx, :]\n if X_.shape[0] == 0: # No point was closest to this centre!\n if global_mean is None:\n global_mean = np.mean(X, axis=0)\n mu = global_mean # TODO: Correct solution?\n else:\n mu = np.mean(X_, axis=0)\n mus[i, :] = mu\n\n return mus", "def scan_cluster_locations(self, centers, radius, resolution, error=0.125):\n all_points = [] # all points in all grids\n\n # create grids centered at cluster center\n for center in centers:\n c_x = center[0]\n c_y = center[1]\n dim = radius+error\n mini_grid = np.linspace(-dim,dim, 20)\n\n # create final list, offset by cluster center coordinates\n scan_points = [(x+c_x, y+c_y) for x in mini_grid for y in mini_grid]\n\n for point in scan_points:\n all_points.append(point)\n\n return all_points" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate label based on length
def gen_label(self, length): characters = string.ascii_lowercase + string.digits selected_charalist = random.choices(characters, k=length) return "".join(selected_charalist)
[ "def label_generator(self) -> str:\n label = LABEL + str(self.label_counter)\n self.label_counter += 1\n return label", "def augment_label(label, n):\n return [label]*n", "def ln(label, char='-', width=70):\r\n label_len = len(label) + 2\r\n chunk = (width - label_len) // 2\r\n out = '%s %s %s' % (char * chunk, label, char * chunk)\r\n pad = width - len(out)\r\n if pad > 0:\r\n out = out + (char * pad)\r\n return out", "def _createRightLabel(self):\n self.label_R = Label(self.frame_in_text_R, text=self.current_seq_len, bg=\"#f5feff\")\n self.label_R.pack(padx=60, side=RIGHT)\n return self.label_R", "def set_array_length_label(self, array_length):\n self.array_length_label.setText(\"Array Length: {}\".format(array_length))", "def generate_labels(self, max_label_size=50, min_label_size=10, tightness=200):\n self.labels = []\n placed = []\n padding = 5\n while tightness > 0:\n w = randrange(max_label_size - min_label_size) + min_label_size\n h = randrange(max_label_size - min_label_size) + min_label_size\n ul = Point(padding + randrange(self.canvas.width() - w),\n padding + randrange(self.canvas.height() - h))\n rect = Rectangle(ul, ul + Point(w, h))\n\n overlap = False\n for placed_rect in placed:\n if rect.overlaps(placed_rect):\n overlap = True\n tightness -= 1\n break\n\n if overlap:\n continue\n placed.append(rect)\n\n offsets = []\n k1 = randrange(4) * randrange(2) + 1\n k2 = randrange(4) * randrange(2) + 1\n for j in range(k1 + 1):\n for i in range(k2 + 1):\n if (i / k2 * w).is_integer() and (j / k1 * h).is_integer():\n offsets.append(Point(int(i / k2 * w), int(j / k1 * h)))\n\n point = ul + offsets[randrange(len(offsets))]\n\n offsets = [f\"{p}\" for p in offsets]\n line = f\"{point}\\t{w},{h}\\t{' '.join(offsets)}\"\n self.labels.append(Label(line))", "def trunc_label(label, num_opts=None, max_lines=None, max_length=25):\n \"\"\"If the label space is too small, only some lines will be append and the rest will be represented with ...\"\"\"\n if max_lines is None:\n if num_opts <= 4:\n max_lines = 4\n elif num_opts <= 6:\n max_lines = 3\n elif num_opts <= 8:\n max_lines = 2\n else:\n max_lines = 1\n\n res = wrap(label, max_length)\n res_full_length = len(res)\n res = res[:min(res_full_length, max_lines)]\n\n return \"\\n\".join(res) + (\"...\" if res_full_length > max_lines else \"\")", "def label_gen(index):\n # print(index)\n #print(type(index))\n #assert isinstance(index, (float, int))\n\n # generates unique parameter strings based on index of peak\n pref = str(int(index))\n comb = 'a' + pref + '_'\n\n cent = 'center'\n sig = 'sigma'\n amp = 'amplitude'\n fract = 'fraction'\n\n # creates final objects for use in model generation\n center = comb + cent\n sigma = comb + sig\n amplitude = comb + amp\n fraction = comb + fract\n \n #assert isinstance((center, sigma, amplitude, fraction, comb), str)\n\n return center, sigma, amplitude, fraction, comb", "def FormCATSLabel(PathLength=10):\r\n AtomPair = ['DD', 'DA', 'DP', 'DN', 'DL', 'AA', 'AP', 'AN', 'AL',\r\n 'PP', 'PN', 'PL', 'NN', 'NL', 'LL']\r\n CATSLabel = []\r\n for i in AtomPair:\r\n for k in range(PathLength):\r\n CATSLabel.append(\"CATS_\" + i + str(k))\r\n return CATSLabel", "def generate_label() -> str:\n global _return_label_counter\n _return_label_counter += 1\n return f\"__RETURN{_return_label_counter}__\"", "def pn(self, num, label):\n f = \"*{:,}* {}\".format(num, label)\n if num > 1:\n f += \"s\"\n return f", "def generate_dummy_label(flavor):\n if flavor == 0:\n dummy = np.empty((32,32,8))\n dummy[:16,:16,:] = 0\n dummy[:16,16:,:] = 1\n dummy[16:,:16,:] = 2\n dummy[16:,16:,:] = 3\n return dummy\n if flavor == 1:\n dummy = np.empty((32,32,8))\n dummy[:8,:16,:] = 0\n dummy[8:16,:16,:] = 1\n dummy[:16,16:,:] = 2\n dummy[16:,:16,:] = 3\n dummy[16:,16:,:] = 4\n return dummy\n if flavor == 3:\n dummy = np.zeros((32,32,32))\n dummy[1:12,1:12,1:12] = ball(5)*1\n dummy[14:31,14:31,14:31] = ball(8)*2\n return dummy", "def label(self):\n if self.tex is None:\n name_tex = r'{\\rm %s}' % text2tex(self.name)\n else:\n name_tex = self.tex\n\n if self.units == ureg.dimensionless:\n units_tex = ''\n else:\n units_tex = r' \\; \\left( {:~L} \\right)'.format(self.units)\n\n return name_tex + units_tex", "def _create_label(self, kg: KG, vertex: Vertex, n: int) -> str:\n if len(self._label_map) == 0:\n self._weisfeiler_lehman(kg)\n\n suffix = \"-\".join(\n sorted(\n set(\n [\n self._label_map[neighbor][n - 1]\n for neighbor in kg.get_neighbors(\n vertex, is_reverse=True\n )\n ]\n )\n )\n )\n return f\"{self._label_map[vertex][n - 1]}-{suffix}\"", "def translate_label(label_number: int) -> str:\n\tif label_number == 0:\n\t\treturn \"\"\n\t# get a letter A-E based on the modulo being 0-5 respectively\n\tletter = chr((label_number - 1) % 5 + ord(\"A\"))\n\t# get the index number of the label\n\tnumber = (label_number - 1) // 5 + 1\n\t# return label name\n\treturn letter + str(number)", "def num_labels(self): # -> int:\n ...", "def label():\n return _make_type(_core.LLVMLabelType(), TYPE_LABEL)", "def gen_name(length):\n seed()\n return ''.join(choice(ascii_lowercase) for _ in xrange(length))", "def build_train_labels_lin(self):\r\n\r\n self.train_labels = np.zeros([self.num_trials_train*5,5]) # 5 == Number of states\r\n self.train_labels[:self.num_trials_train,0] = 0.9\r\n self.train_labels[self.num_trials_train:self.num_trials_train*2,1] = 0.9\r\n self.train_labels[self.num_trials_train*2:self.num_trials_train*3,2] = 0.9\r\n self.train_labels[self.num_trials_train*3:self.num_trials_train*4,3] = 0.9\r\n self.train_labels[self.num_trials_train*4:,4] = 0.9" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get always the same 0...1 random number based on an arbitrary string
def get_random_by_string(s): sum = reduce(lambda x, y: x+(y*37), [ord(c) for c in s]) return float(sum % 360) / 360 # Initialize random gen by server name hash #random.seed(s) #return random.random()
[ "def get_random_sensor_id():\n return \"\".join(random.choice(\"0123456789abcdef\") for i in range(12))", "def get_random_number():\n\n return random.randint(0, 100000)", "def generate_number_to_be_guessed():\n\n digits = [str(digit) for digit in range(10)]\n random.shuffle(digits)\n\n return ''.join(digits[:3])", "def get_random_sting():\n return \"random string\"", "def random_number():\n return random.getrandbits(32)", "def randstring():\n return binascii.b2a_hex(os.urandom(15)).upper()", "def generateNumSyndicate():\n if randint(0, 3):\n return str(randint(1, numSyndicates))\n return 'null'", "def php_mt_rand(s1):\n s1 ^= (s1 >> 11)\n s1 ^= (s1 << 7) & 0x9d2c5680\n s1 ^= (s1 << 15) & 0xefc60000\n s1 ^= (s1 >> 18)\n return s1", "def _generate_random() -> int:\n import pyotp # pylint: disable=import-outside-toplevel\n\n return int(pyotp.random_base32(length=32, chars=list(\"1234567890\")))", "def nextPsuedoRandNum(num, length):\n return ((num * 113) + 137) % length", "def randId(n):\n return str(n) +\"-\" + str(+random.randint(1,10000))", "def rand_symbol():\n return random.randint(0, 3)", "def generate_randid():\n\n chars = string.digits + string.ascii_uppercase\n chars = chars.replace('I', '')\n chars = chars.replace('O', '')\n\n return ''.join(random.choice(chars) for i in range(8))", "def rnd_string(n_bytes):\n return ''.join(\n random.choice(string.ascii_letters + string.digits)\n for _ in range(n_bytes))", "def get_number(a=1, b=100):\n return random.randint(a, b)", "def generate_id():\n length = 6\n return ''.join(random.choices(string.ascii_lowercase + string.digits, k=length))", "def random_string():\n rs = (''.join(random.choice(string.ascii_uppercase)\n for i in range(16)))\n\n return rs", "def rand():\r\n global rand_seed\r\n rand_seed = (MULTIPLIER * rand_seed + INCREMENT)\r\n return (rand_seed >> 16) & 0x7FFF", "def get_random_values():\n digits = list(range(10))\n random.shuffle(digits)\n digits = [str(digit) for digit in digits[:3]]\n return \"\".join(digits)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set terminal tab / decoration color. Please note that iTerm 2 / Konsole have different control codes over this. Note sure what other terminals support this behavior.
def decorate_terminal(color): if color is None: # Reset tab color sys.stdout.write("\033]6;1;bg;*;default\a") sys.stdout.flush() else: r, g, b = color # iTerm 2 # http://www.iterm2.com/#/section/documentation/escape_codes" sys.stdout.write("\033]6;1;bg;red;brightness;%d\a" % int(r * 255)) sys.stdout.write("\033]6;1;bg;green;brightness;%d\a" % int(g * 255)) sys.stdout.write("\033]6;1;bg;blue;brightness;%d\a" % int(b * 255)) sys.stdout.flush() # Konsole # TODO # http://meta.ath0.com/2006/05/24/unix-shell-games-with-kde/
[ "def set_iterm_tab_color(color):\n return \"\"\"\n \\033]6;1;bg;red;brightness;%s\\a\n \\033]6;1;bg;green;brightness;%s\\a\n \\033]6;1;bg;blue;brightness;%s\\a\n \"\"\" % (*util.hex_to_rgb(color),)", "def DefaultColorCoding():\n print((\"\\033[49m \\033[39m \"), end=' ') #set to default color coding, suppress newline", "def init_theme(self):\n term = getsession().terminal\n if term.number_of_colors != 0:\n self.colors['border'] = term.cyan\n self.colors['highlight'] = term.cyan + term.reverse\n self.colors['lowlight'] = term.normal\n self.colors['normal'] = term.normal\n if getsession().env.get('TERM') == 'unknown':\n self.glyphs = GLYPHSETS['unknown']\n else:\n self.glyphs = GLYPHSETS['thin']", "def setConsoleColor(hex_color=\"\",counter=0):\r\n if len(hex_color) != 7:\r\n hex_color = MpGlobal.Window.style_dict[\"theme_very_dark\"].name()\r\n \r\n MpGlobal.Window.txt_main.setStyleSheet(\"background: \"+hex_color+\";\")\r\n\r\n if counter > 0:\r\n MpGlobal.Console_State_Counter = counter;", "def set_text_attr(color):\n\t SetConsoleTextAttribute(stdout_handle, color)", "def __init__(self):\n if sys.stdout.isatty():\n self.HEADER = '\\033[95m'\n self.OKBLUE = '\\033[94m'\n self.OKGREEN = '\\033[92m'\n self.WARNING = '\\033[93m'\n self.FAIL = '\\033[91m'\n self.ENDC = '\\033[0m'\n self.BOLD = '\\033[1m'\n self.UNDERLINE = '\\033[4m'", "def set_highlight(self):\r\n vim.command(\"highlight DbgCurrent term=reverse ctermfg=White ctermbg=Red gui=reverse\")\r\n vim.command(\"highlight DbgBreakPt term=reverse ctermfg=White ctermbg=Green gui=reverse\")", "def red(t):\n return \"\\033[1;7;31m {} \\033[0m\".format(t) if tty() else t", "def change_colorscheme(self,new_colorscheme):\n #TODO minimum number of colors\n self.colorscheme = new_colorscheme\n print self.colorscheme, new_colorscheme", "def setColors(self, fg=None, bg=None):\n if self.console._lockColors is self:\n self.console._lockColors = None\n if fg is not None:\n self._fgcolor = _formatColor(fg)\n if bg is not None:\n self._bgcolor = _formatColor(bg)", "def init_colors(self):\n\t\tcurses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)\n\t\tcurses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK)\n\t\tcurses.init_pair(3, curses.COLOR_BLUE, curses.COLOR_BLACK)\n\t\tcurses.init_pair(4, curses.COLOR_YELLOW, curses.COLOR_BLACK)\n\t\tcurses.init_pair(5, curses.COLOR_CYAN, curses.COLOR_BLACK)", "def set_color(self, color):\n self._text.color = color", "def switch_color(self):\n pass", "def _apply_configuration(self, terminal):\n terminal.set_colors(self._fg_color, self._bg_color, self._palette)\n terminal.set_font_scale(self._font_scale)\n if self._font_family:\n font = terminal.get_font()\n font.set_family(self._font_family)\n terminal.set_font(font)", "def init_colors():\n curses.initscr()\n curses.start_color()\n curses.use_default_colors()\n # default 8 colors of terminal\n curses.init_pair(1, curses.COLOR_WHITE, -1)\n curses.init_pair(2, curses.COLOR_BLUE, -1)\n curses.init_pair(3, curses.COLOR_CYAN, -1)\n curses.init_pair(4, curses.COLOR_GREEN, -1)\n curses.init_pair(5, curses.COLOR_MAGENTA, -1)\n curses.init_pair(6, curses.COLOR_RED, -1)\n curses.init_pair(7, curses.COLOR_YELLOW, -1)\n global_vars.colors = {\n 'white': curses.color_pair(1),\n 'blue': curses.color_pair(2),\n 'cyan': curses.color_pair(3),\n 'green': curses.color_pair(4),\n 'magenta': curses.color_pair(5),\n 'red': curses.color_pair(6),\n 'yellow': curses.color_pair(7),\n }\n global_vars.color_names = list(global_vars.colors.keys())", "def set_color(self, red, green, blue):\n self.appt_color = color_rgb(red, green, blue)", "def outline_color(self, new_outline_color):\n self._palette[0] = new_outline_color", "def set_text_color(self, foreground_color, background_color):\n\n raise NotImplementedError()", "def setAtomColor(self, atom, color):\n self.setAtomsColor({atom: color})", "def set_color(self):\n nodes = cmds.ls(sl=True) or []\n if nodes:\n color = cmds.getAttr('{0}.overrideColorRGB'.format(nodes[0]))[0]\n color = QtGui.QColor(color[0]*255, color[1]*255, color[2]*255)\n color = QtWidgets.QColorDialog.getColor(color, self, 'Set Curve Color')\n if color.isValid():\n color = [color.redF(), color.greenF(), color.blueF()]\n for node in nodes:\n cmds.setAttr('{0}.overrideEnabled'.format(node), True)\n cmds.setAttr('{0}.overrideRGBColors'.format(node), True)\n cmds.setAttr('{0}.overrideColorRGB'.format(node), *color)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Train MLP model, using random search to choose hyperparameters. The general structure is to first do the random search and get the best performing hyperparameters on the validation set, then retrain the best model on the train/valid split to generate a learning curve. sklearn RandomizedSearch doesn't provide a way to save epochlevel results for each search model, which is why retraining at the end is necessary. search_hparams should be a dict with lists of hyperparameter options to randomly search over; the options/defaults are specified below.
def train_mlp(X_train, X_test, y_train, y_test, seed, search_hparams={}, batch_size=50, n_folds=3, max_iter=100, search_n_iter=20): import torch.optim from skorch import NeuralNetClassifier from skorch.callbacks import Callback, EpochScoring from skorch.dataset import ValidSplit from pancancer_evaluation.prediction.nn_models import ThreeLayerNet # first set up the random search # default hyperparameter search options # will be overridden by any existing entries in search_hparams default_hparams = { 'learning_rate': [0.1, 0.01, 0.001, 5e-4, 1e-4], 'h1_size': [100, 200, 300, 500, 1000], 'dropout': [0.1, 0.5, 0.75], 'weight_decay': [0, 0.1, 1, 10, 100] } for k, v in default_hparams.items(): search_hparams.setdefault(k, v) model = ThreeLayerNet(input_size=X_train.shape[1]) clf_parameters = { 'lr': search_hparams['learning_rate'], 'module__input_size': [X_train.shape[1]], 'module__h1_size': search_hparams['h1_size'], 'module__dropout': search_hparams['dropout'], 'optimizer__weight_decay': search_hparams['weight_decay'], } net = NeuralNetClassifier( model, max_epochs=max_iter, batch_size=batch_size, optimizer=torch.optim.Adam, iterator_train__shuffle=True, verbose=0, # by default this prints loss for each epoch train_split=False, device='cuda' ) if n_folds == -1: # for this option we just want to do a grid search for a single # train/test split, this is much more computationally efficient # but could have higher variance from sklearn.model_selection import train_test_split subtrain_ixs, valid_ixs = train_test_split( np.arange(X_train.shape[0]), test_size=0.2, random_state=seed, shuffle=True ) cv_pipeline = RandomizedSearchCV( estimator=net, param_distributions=clf_parameters, n_iter=search_n_iter, cv=((subtrain_ixs, valid_ixs),), scoring='average_precision', verbose=2, random_state=seed ) else: cv_pipeline = RandomizedSearchCV( estimator=net, param_distributions=clf_parameters, n_iter=search_n_iter, cv=n_folds, scoring='average_precision', verbose=2, random_state=seed ) cv_pipeline.fit(X=X_train.values.astype(np.float32), y=y_train.status.values.astype(np.int)) print(cv_pipeline.best_params_) print('Training final model...') # then retrain the model and get epoch-level performance info # define callback for scoring test set, to run each epoch class ScoreData(Callback): def __init__(self, X, y): self.X = X self.y = y def on_epoch_end(self, net, **kwargs): y_pred = net.predict_proba(self.X)[:, 1] net.history.record( 'test_aupr', average_precision_score(self.y, y_pred) ) net = NeuralNetClassifier( model, max_epochs=max_iter, batch_size=batch_size, optimizer=torch.optim.Adam, iterator_train__shuffle=True, verbose=0, train_split=ValidSplit(cv=((subtrain_ixs, valid_ixs),)), callbacks=[ ScoreData( X=X_test.values.astype(np.float32), y=y_test.status.values.astype(np.int) ), EpochScoring(scoring='average_precision', name='valid_aupr', lower_is_better=False), EpochScoring(scoring='average_precision', on_train=True, name='train_aupr', lower_is_better=False) ], device='cuda', **cv_pipeline.best_params_ ) net.fit(X_train.values.astype(np.float32), y_train.status.values.astype(np.int)) X_subtrain, X_valid = X_train.iloc[subtrain_ixs, :], X_train.iloc[valid_ixs, :] y_subtrain, y_valid = y_train.iloc[subtrain_ixs, :], y_train.iloc[valid_ixs, :] # Get all performance results y_predict_train = net.predict_proba( X_subtrain.values.astype(np.float32) )[:, 1] y_predict_valid = net.predict_proba( X_valid.values.astype(np.float32) )[:, 1] y_predict_test = net.predict_proba( X_test.values.astype(np.float32) )[:, 1] return (net, cv_pipeline, (y_subtrain, y_valid), (y_predict_train, y_predict_valid, y_predict_test))
[ "def random_search(learner, params = {}, rnn_type=\"\", seed=0, attempts_per_param=2):\n print(\"RNN type:\", rnn_type)\n print(\"===\")\n print(\"full parameter range:\")\n print(params)\n print(\"===\")\n\n shuffle_seed=0\n random.seed(shuffle_seed)\n params_subrange = {}\n\n best_accuracy = 0.0\n best_config = {}\n tried_configs = set()\n\n params_copy = params.copy()\n num_epochs = params_copy[\"num_epochs\"]\n del params_copy[\"num_epochs\"]\n\n # Two samples for each parameter to optimize (only those that have a choice)\n attempts_per_round = max(1, attempts_per_param * sum([1 for l in params_copy.values() if len(l) > 1]))\n\n while extend_subrange(params_subrange, params_copy, best_config):\n print(\"params_subrange:\")\n print(params_subrange)\n print(\"===\")\n\n for setting_nr in range(attempts_per_round):\n start = time.time()\n\n config = {}\n for param, settings in params_subrange.items():\n selection = random.choice(settings)\n config[param] = selection\n\n if frozenset(config.items()) not in tried_configs:\n print(\"\\n === Running config: ===\")\n print(config)\n tried_configs.add(frozenset(config.items()))\n epochs_to_model_costs = learner.learn(rnn_type=rnn_type, config=config, num_epochs=num_epochs, seed=seed) \n shuffle_seed+=1\n random.seed(shuffle_seed)\n for num_epochs_selected, model_costs in epochs_to_model_costs.items():\n model, val_loss, val_acc = model_costs\n config[\"num_epochs\"] = num_epochs_selected\n print(config)\n print(\"Val_acc: %f\" % (val_acc))\n if val_acc > best_accuracy:\n best_config = copy.deepcopy(config)\n best_accuracy = val_acc\n best_model = model\n time_elapsed = time.time() - start\n print(\"time (s):\" + str(time_elapsed))\n print(\"Best config and validation accuracy so far:\")\n print(best_config)\n print(best_accuracy)\n print(\"===\\n\")\n else:\n print(\" === already tried: ===\")\n print(config)\n print(\"===\")\n print(\"Best config, validation accuracy:\")\n print(best_config)\n print(best_accuracy)\n print(\"===\")\n \n return best_model, best_config", "def random_search(train_loader, val_loader,\n random_search_spaces={\n \"learning_rate\": ([0.0001, 0.1], 'log'),\n \"hidden_size\": ([100, 400], \"int\"),\n \"activation\": ([Sigmoid(), Relu()], \"item\"),\n },\n model_class=ClassificationNet, num_search=20, epochs=20,\n patience=5):\n configs = []\n for _ in range(num_search):\n configs.append(random_search_spaces_to_config(random_search_spaces))\n\n return findBestConfig(train_loader, val_loader, configs, epochs, patience,\n model_class)", "def select_best_model_ranking(model_class, X_train, X_valid, X_test, param_grid, max_combinations=None,\n param_grid_random_seed=0, use_filter=True, early_stopping=False,\n early_stopping_params=None, use_test_for_selection=False, entities_subset=None,\n corrupt_side='s,o', use_default_protocol=False, retrain_best_model=False, verbose=False):\n logger.debug('Starting gridsearch over hyperparameters. {}'.format(param_grid))\n if use_default_protocol:\n logger.warning('DeprecationWarning: use_default_protocol will be removed in future. \\\n Please use corrupt_side argument instead.')\n corrupt_side = 's,o'\n\n if early_stopping_params is None:\n early_stopping_params = {}\n\n # Verify missing parameters for the model class (default values will be used)\n undeclared_args = set(model_class.__init__.__code__.co_varnames[1:]) - set(param_grid.keys())\n if len(undeclared_args) != 0:\n logger.debug(\"The following arguments were not defined in the parameter grid\"\n \" and thus the default values will be used: {}\".format(', '.join(undeclared_args)))\n\n param_grid[\"model_name\"] = model_class.name\n _scalars_into_lists(param_grid)\n\n if max_combinations is not None:\n np.random.seed(param_grid_random_seed)\n model_params_combinations = islice(_next_hyperparam_random(param_grid), max_combinations)\n else:\n model_params_combinations = _next_hyperparam(param_grid)\n\n best_mrr_train = 0\n best_model = None\n best_params = None\n\n if early_stopping:\n try:\n early_stopping_params['x_valid']\n except KeyError:\n logger.debug('Early stopping enable but no x_valid parameter set. Setting x_valid to {}'.format(X_valid))\n early_stopping_params['x_valid'] = X_valid\n\n if use_filter:\n X_filter = np.concatenate((X_train, X_valid, X_test))\n else:\n X_filter = None\n\n if use_test_for_selection:\n selection_dataset = X_test\n else:\n selection_dataset = X_valid\n\n experimental_history = []\n\n def evaluation(ranks):\n mrr = mrr_score(ranks)\n mr = mr_score(ranks)\n hits_1 = hits_at_n_score(ranks, n=1)\n hits_3 = hits_at_n_score(ranks, n=3)\n hits_10 = hits_at_n_score(ranks, n=10)\n return mrr, mr, hits_1, hits_3, hits_10\n\n for model_params in tqdm(model_params_combinations, total=max_combinations, disable=(not verbose)):\n current_result = {\n \"model_name\": model_params[\"model_name\"],\n \"model_params\": model_params\n }\n del model_params[\"model_name\"]\n try:\n model = model_class(**model_params)\n model.fit(X_train, early_stopping, early_stopping_params)\n ranks = evaluate_performance(selection_dataset, model=model,\n filter_triples=X_filter, verbose=verbose,\n entities_subset=entities_subset,\n use_default_protocol=use_default_protocol,\n corrupt_side=corrupt_side)\n\n curr_mrr, mr, hits_1, hits_3, hits_10 = evaluation(ranks)\n\n current_result[\"results\"] = {\n \"mrr\": curr_mrr,\n \"mr\": mr,\n \"hits_1\": hits_1,\n \"hits_3\": hits_3,\n \"hits_10\": hits_10\n }\n\n info = 'mr: {} mrr: {} hits 1: {} hits 3: {} hits 10: {}, model: {}, params: {}'.format(\n mr, curr_mrr, hits_1, hits_3, hits_10, type(model).__name__, model_params\n )\n\n logger.debug(info)\n if verbose:\n logger.info(info)\n\n if curr_mrr > best_mrr_train:\n best_mrr_train = curr_mrr\n best_model = model\n best_params = model_params\n except Exception as e:\n current_result[\"results\"] = {\n \"exception\": str(e)\n }\n\n if verbose:\n logger.error('Exception occurred for parameters:{}'.format(model_params))\n logger.error(str(e))\n else:\n pass\n experimental_history.append(current_result)\n\n if best_model is not None:\n if retrain_best_model:\n best_model.fit(np.concatenate((X_train, X_valid)), early_stopping, early_stopping_params)\n\n ranks_test = evaluate_performance(X_test, model=best_model,\n filter_triples=X_filter, verbose=verbose,\n entities_subset=entities_subset,\n use_default_protocol=use_default_protocol,\n corrupt_side=corrupt_side)\n\n test_mrr, test_mr, test_hits_1, test_hits_3, test_hits_10 = evaluation(ranks_test)\n\n info = \\\n 'Best model test results: mr: {} mrr: {} hits 1: {} hits 3: {} hits 10: {}, model: {}, params: {}'.format(\n test_mrr, test_mr, test_hits_1, test_hits_3, test_hits_10, type(best_model).__name__, best_params\n )\n\n logger.debug(info)\n if verbose:\n logger.info(info)\n\n test_evaluation = {\n \"mrr\": test_mrr,\n \"mr\": test_mr,\n \"hits_1\": test_hits_1,\n \"hits_3\": test_hits_3,\n \"hits_10\": test_hits_10\n }\n else:\n ranks_test = []\n\n test_evaluation = {\n \"mrr\": np.nan,\n \"mr\": np.nan,\n \"hits_1\": np.nan,\n \"hits_3\": np.nan,\n \"hits_10\": np.nan\n }\n\n return best_model, best_params, best_mrr_train, ranks_test, test_evaluation, experimental_history", "def mlp(train, test, model_path):\n if not model_path.exists():\n clf = MLPClassifier(early_stopping=True)\n params = {'hidden_layer_sizes': list(itertools.product([3, 4], [20, 50, 100])),\n 'learning_rate': ['adaptive']}\n gs = GridSearchCV(clf, params, cv=5, n_jobs=2, scoring='f1_macro')\n gs.fit(train[0], train[1])\n joblib.dump(gs, model_path)\n else:\n gs = joblib.load(model_path)\n y_pred = gs.predict(test[0])\n print('Best params: ', gs.best_params_)\n evaluate(test[1], y_pred)", "def randomize_hyperparamters():\n\tglobal h\n\t# Note: N evenly spaced random points in interval [a,b) is given by:\n\t# a + (b - a) * randint(N)/N\n\th.update({'l1_parameter' : 0.02 * randint(10) / 10,\n\t\t\t 'l2_parameter' : 0.02 * randint(10) / 10,\n\t\t\t 'num_residual_blocks' : np.random.choice([2,3,4,5]),\n\t\t\t 'num_conv_blocks' : np.random.choice([2,3,4]),\n\t\t\t 'num_final_conv_blocks' : np.random.choice([2,3,4]),\n\t\t\t 'num_filters' : np.random.choice([16,32,64,128]),\n\t\t\t 'learning_rate' : 0.00005 + (0.001 - 0.00005) * randint(20) / 20\n\t\t})\n\th.update({\"optimizer\" : keras.optimizers.Adam(lr=learning_rate, beta_1=beta_1, beta_2=beta_2, amsgrad=False),\n\t\t\t 'regularizer' : l1_l2(l1=h['l1_parameter'], l2=h['l2_parameter'])})", "def grid_search():\n pipeline1 = Pipeline([\n (\"scaler\", StandardScaler()),\n (\"nnet\", MLPClassifier(\n random_state=42,\n max_iter=300))\n ])\n\n pipeline2 = Pipeline([\n (\"scaler\", StandardScaler()),\n (\"nn\", KNeighborsClassifier(\n n_jobs=-1))\n\n ])\n\n pipeline3 = Pipeline([\n (\"scaler\", StandardScaler()),\n (\"svm\", SVC(\n probability=True,\n random_state=42)),\n ])\n\n pipeline4 = Pipeline([\n (\"scaler\", StandardScaler()),\n (\"rf\", RandomForestClassifier(\n random_state=42,\n n_jobs=-1))\n ])\n\n # 144\n param1 = {\n 'nnet__hidden_layer_sizes': [(100,), (50, 50), (100, 50), (50,)],\n 'nnet__activation': ['identity', 'logistic', 'tanh', 'relu'],\n 'nnet__solver': ['lbfgs', 'sgd', 'adam'],\n 'nnet__alpha': [0.001, 0.0001, 0.00001]\n }\n # 64 combinations\n param2 = {\n 'nn__n_neighbors': [3, 5, 9, 13],\n 'nn__weights': ['uniform', 'distance'],\n 'nn__algorithm': ['auto', 'ball_tree', 'kd_tree', 'brute'],\n 'nn__metric': ['euclidean', 'manhattan'],\n }\n\n # 64 combinations\n param3 = {\n 'svm__C': [0.01, 0.1, 1.0, 10.0],\n 'svm__kernel': ['linear', 'rbf', 'poly', 'sigmoid'],\n 'svm__gamma': ['scale', 'auto'],\n 'svm__class_weight': ['balanced', None],\n }\n\n # 144 combinations\n param4 = {\n 'rf__n_estimators': [50, 100, 200],\n 'rf__criterion': ['gini', 'entropy'],\n 'rf__max_depth': [10, 50, 100, None],\n 'rf__min_samples_split': [2, 5, 10],\n 'rf__class_weight': ['balanced', None]\n }\n\n pipelines = [pipeline1, pipeline2, pipeline3, pipeline4]\n params = [param1, param2, param3, param4]\n\n sd = StressDetector(wav_path, abs_cont)\n sd.get_features('./data/complete_features.tsv')\n feat_set1_params = sd.grid_search(pipelines, params)\n\n sd2 = StressDetector(wav_path, abs_norm_cont)\n sd2.get_features('./data/complete_features.tsv')\n feat_set2_params = sd2.grid_search(pipelines, params)\n\n print(\n f'Feature Set 1: absolute + context-aware features \\n {feat_set1_params}')\n print(\n f'Feature Set 2: absolute + normalized + context-aware features \\n {feat_set2_params}')", "def fine_tune_model(model, param_grid, x_train, y_train, cv=5, verbose=0, randomized=False):\n from time import perf_counter\n\n start_time = perf_counter()\n\n grid_search = None\n if randomized:\n print(f\"Performing Randomized search for {type(model).__name__}...\")\n grid_search = model_selection.RandomizedSearchCV(model, param_grid, cv=cv, verbose=verbose, n_jobs=-1)\n else:\n print(f\"Performing Grid search for {type(model).__name__}...\")\n grid_search = model_selection.GridSearchCV(model, param_grid, cv=cv, verbose=verbose, n_jobs=-1)\n\n # Start fine tuning of the model\n grid_search.fit(x_train, y_train)\n time_taken = round(perf_counter() - start_time, 2)\n print(f\"Time elapsed : {get_display_time(time_taken)} | score : {grid_search.best_score_:.2}\")\n print(f\"Best parameters : {grid_search.best_params_} \")\n return grid_search.best_estimator_", "def add_grid_search(self):\n # Here to apply ramdom search to pipeline, need to follow naming \"rgs__paramname\"\n params = {\"rgs__\" + k: v for k, v in self.model_params.items()}\n self.pipeline = RandomizedSearchCV(estimator=self.pipeline, param_distributions=params,\n n_iter=100, cv=3, verbose=2,\n random_state=42, n_jobs=-1)", "def tune_hyperparam(y, x, k_fold, seed, hprange, method, args, compute_loss):\n\tk_indices = build_k_indices(y, k_fold, seed)\n\n\t# define lists to store the loss of training data and test data\n\tloss_tr = []\n\tloss_te = []\n\n\t# cross validation\n\tfor hp in hprange:\n\t\t# compute the cv_losses\n\t\tcv_tr, cv_te = cv_loss(y, x, k_indices, method, args + [hp], compute_loss)\n\n\t\tloss_tr.append(cv_tr)\n\t\tloss_te.append(cv_te)\n\n\t# keep the hyperparam giving best loss on the test set\n\tind_hp_opt = np.argmin(loss_te)\n\tbest_hp = hprange[ind_hp_opt]\n\n\treturn best_hp, loss_tr, loss_te", "def tune_model(self, n_tries, hyperparameters_dict, preprocessing_pipeline, model_class, X_train, y_train, X_test, y_test):\n \n # Preprocess the data\n X_train = preprocessing_pipeline.fit_transform(X_train, y_train)\n X_test = preprocessing_pipeline.transform(X_test)\n\n # Generate hyperparameters sets\n #self.hyperparameters_sets_lst = self._generate_random_hyperparameters_sets(hyperparameters_dict)\n\n # Actually do the tuning\n best, trials = self._tune_model_helper(n_tries, model_class, hyperparameters_dict, X_train, y_train, X_test, y_test)\n \n # Generate a DataFrame with results\n results_df = pd.DataFrame({\"model\": [\"MLP\"] * len(trials.tids), \"iteration\": trials.tids, \"QWK\": [-x[\"loss\"] for x in trials.results]})\n results_df = pd.concat([results_df, pd.DataFrame(trials.vals, index = results_df.index)], axis = 1) # For LightGBM\n\n \"\"\"\n results_df[\"activation\"] = [\"relu\" if a == 0 else \"tanh\" for a in trials.vals[\"activation\"]]\n results_df[\"dropout\"] = trials.vals[\"dropout\"]\n results_df[\"l2_regularization\"] = trials.vals[\"l2_regularization\"]\n results_df[\"learning_rate\"] = trials.vals[\"learning_rate\"]\n results_df[\"nb_layers\"] = [i + 3 for i in trials.vals[\"layers\"]]\n for i in range(1, 8):\n results_df[\"layer\" + str(i)] = np.nan\n\n results_df.loc[results_df[\"nb_layers\"] == 3, [\"layer1\", \"layer2\", \"layer3\", \"layer4\", \"layer5\", \"layer6\", \"layer7\"]] = pd.DataFrame({\"layer1\": trials.vals[\"n_units_layer_31\"], \"layer2\": trials.vals[\"n_units_layer_32\"], \"layer3\": trials.vals[\"n_units_layer_33\"], \"layer4\": np.nan, \"layer5\": np.nan, \"layer6\": np.nan, \"layer7\": np.nan}).values\n results_df.loc[results_df[\"nb_layers\"] == 4, [\"layer1\", \"layer2\", \"layer3\", \"layer4\", \"layer5\", \"layer6\", \"layer7\"]] = pd.DataFrame({\"layer1\": trials.vals[\"n_units_layer_41\"], \"layer2\": trials.vals[\"n_units_layer_42\"], \"layer3\": trials.vals[\"n_units_layer_43\"], \"layer4\": trials.vals[\"n_units_layer_44\"], \"layer5\": np.nan, \"layer6\": np.nan, \"layer7\": np.nan})\n results_df.loc[results_df[\"nb_layers\"] == 5, [\"layer1\", \"layer2\", \"layer3\", \"layer4\", \"layer5\", \"layer6\", \"layer7\"]] = pd.DataFrame({\"layer1\": trials.vals[\"n_units_layer_51\"], \"layer2\": trials.vals[\"n_units_layer_52\"], \"layer3\": trials.vals[\"n_units_layer_53\"], \"layer4\": trials.vals[\"n_units_layer_54\"], \"layer5\": trials.vals[\"n_units_layer_55\"], \"layer6\": np.nan, \"layer7\": np.nan})\n results_df.loc[results_df[\"nb_layers\"] == 6, [\"layer1\", \"layer2\", \"layer3\", \"layer4\", \"layer5\", \"layer6\", \"layer7\"]] = pd.DataFrame({\"layer1\": trials.vals[\"n_units_layer_61\"], \"layer2\": trials.vals[\"n_units_layer_62\"], \"layer3\": trials.vals[\"n_units_layer_63\"], \"layer4\": trials.vals[\"n_units_layer_64\"], \"layer5\": trials.vals[\"n_units_layer_65\"], \"layer6\": trials.vals[\"n_units_layer_66\"], \"layer7\": np.nan})\n results_df.loc[results_df[\"nb_layers\"] == 7, [\"layer1\", \"layer2\", \"layer3\", \"layer4\", \"layer5\", \"layer6\", \"layer7\"]] = pd.DataFrame({\"layer1\": trials.vals[\"n_units_layer_71\"], \"layer2\": trials.vals[\"n_units_layer_72\"], \"layer3\": trials.vals[\"n_units_layer_73\"], \"layer4\": trials.vals[\"n_units_layer_74\"], \"layer5\": trials.vals[\"n_units_layer_75\"], \"layer6\": trials.vals[\"n_units_layer_76\"], \"layer7\": trials.vals[\"n_units_layer_77\"]}).values\n \"\"\"\n \n results_df.sort_values(\"QWK\", ascending = False, inplace = True)\n \n return results_df", "def Hyper_Parameter_Tuning(DataFrame, labels, weights=None, \n param_dict_list = None,\n cv_folds=5, early_stopping_rounds=1000,\n search_method : ['grid','random','evolution'] = 'random',\n objective='binary:logistic', scoring='roc_auc',\n tree_method='auto'):\n extra_params = {'scoring' : scoring,\n 'n_jobs' : cpu_n_jobs,\n 'iid' : False,\n 'cv' : cv_folds,\n 'verbose' : verbose_level}\n \n XGBoost_default_params['tree_method'] = tree_method\n XGBoost_default_params['objective'] = objective\n \n # Define classifier model\n Model = xgb.XGBClassifier(**XGBoost_default_params)\n \n # List of search result dicts to return to user\n result_list = []\n \n if param_dict_list is not None:\n for i,item in enumerate(param_dict_list):\n if isinstance(item, str) and item.find(\"set_\") == 0:\n # If item is to be used for setting parameter.\n # Split the string at the \"=\" sign, and extract \n # param name and value\n s = item[len(\"set_\"):].split(\"=\")\n param = s[0]\n value = float(s[-1])\n # Set param to value\n Model.set_params(**{param : value})\n \n elif isinstance(item, str) and item == 'tune_trees':\n # item is used to trigger tuning of number of trees (estimators)\n # Find optimal number of estimators to use.\n Model, cv_early_stopping_obj = find_estimators(\n Model, DataFrame, labels, weights, \n cv_folds, early_stopping_rounds)\n \n elif isinstance(item, dict):\n # item is a dict of param dists, which are tuned together.\n item_copy = item.copy()\n \n if search_method == 'grid':\n print(f\"GridSearch for parameters : {list(item_copy.keys())} ...\\n\")\n search_result = GridSearchCV(\n estimator=Model, param_grid=item_copy, **extra_params)\n \n elif search_method == 'random':\n assert('n_iter' in item_copy)\n n_iter = item_copy.pop('n_iter')\n print(f\"RandomSearch for parameters : {list(item_copy.keys())} ...\\n\")\n search_result = RandomizedSearchCV(\n estimator=Model, param_distributions=item_copy,\n n_iter=n_iter, **extra_params)\n \n elif search_method == 'evolution':\n evo_params = EvoSearch_default_params.copy()\n for param in EvoSearch_default_params:\n if param in item_copy:\n evo_params[param] = item_copy.pop(param)\n print(f\"EvolutionarySearch for parameters : {list(item_copy.keys())} ...\\n\")\n search_result = EvolutionaryAlgorithmSearchCV(\n estimator=Model, params=item_copy, **evo_params,\n **extra_params)\n \n # Perform search\n search_result.fit(DataFrame, labels, sample_weight=weights)\n result_list.append(search_result.cv_results_)\n \n # Set Model parameters to new best\n for param in item_copy:\n Model.set_params(**{param : search_result.best_params_[param]})\n print(f\"Tuning for parameters : {list(item_copy.keys())} is done.\\n\")\n\n \n# # Plot Grid Search result\n## plot_grid_search(gsearch3.cv_results_, subsample, colsample_bytree, 'Subsample', 'Colsample by tree')\n## plt.show(0)\n## plt.savefig(\"/groups/hep/stefan/work/HP_plots/Subsample_Colsample_by_tree.png\")\n## plt.close('all')\n \n \n # Model.set_params(n_jobs=cpu_n_jobs)\n \n return Model, result_list, cv_early_stopping_obj", "def grid_search(model, tuned_params_dict, print_results=True, results_to_csv=False):\n global X, y\n\n # Use Grid Search\n tuned_parameters = [tuned_params_dict]\n clf = GridSearchCV(model, tuned_parameters, cv=5, scoring='neg_mean_absolute_error', n_jobs=4)\n clf.fit(X, y)\n\n # Assign results\n means = clf.cv_results_['mean_test_score']\n stds = clf.cv_results_['std_test_score']\n parameters = clf.cv_results_['params']\n\n # Print results if needed\n if print_results:\n print(\"Best parameters set found on development set:\")\n print()\n print(clf.best_params_)\n print()\n print(\"Grid scores on development set:\")\n print()\n for mean, std, params in zip(means, stds, clf.cv_results_['params']):\n print(\"%0.3f (+/-%0.03f) for %r\" % (mean, std * 2, params))\n\n # Save into csv if needed\n if results_to_csv:\n model_csv = pd.DataFrame(data=parameters)\n model_csv.insert(loc=0, column='STD', value=stds)\n model_csv.insert(loc=0, column='MAE', value=means)\n model_csv.to_csv(r'../data/model_analysis.csv')", "def new_random_search(self, params, num_runs, **kwargs):\n hyper = self.client.api.hyper_random_search(\n params, num_runs, get_run_request(self.client, kwargs)\n )\n return HyperSearch(self.client.api, hyper)", "def build_model():\n\n pipeline = Pipeline([\n ('vect', CountVectorizer(tokenizer=tokenize)),\n ('tfidf', TfidfTransformer()),\n ('clf', MultiOutputClassifier(RandomForestClassifier())),\n ])\n\n # randomized search parameters\n parameters_dist = {\n 'clf__estimator__n_estimators': [50, 75, 100],\n #'clf__estimator__learning_rate': [0.5, 1.0, 1.5],\n }\n\n cv = RandomizedSearchCV(pipeline, param_distributions=parameters_dist, n_iter=20, verbose=10)\n\n return cv", "def random_search(self, desired_outputs, query, num_search, model, log_prior, mdp, true_reward_matrix):\n best_objective_disc = float(\"inf\")\n for _ in range(num_search):\n num_fixed = self.args.feature_dim - len(query)\n\n # Sample weights\n other_weights = self.sample_weights('search', num_fixed)\n\n # Calculate objective\n objective_disc, optimal_weights_disc, feature_exps_disc = model.compute(\n desired_outputs, self.sess, mdp, query, log_prior,\n other_weights, true_reward_matrix=true_reward_matrix)\n\n # Update best variables\n if objective_disc <= best_objective_disc:\n best_objective_disc = objective_disc\n best_optimal_weights_disc = optimal_weights_disc\n best_feature_exps_disc = feature_exps_disc\n\n return best_objective_disc, best_optimal_weights_disc, best_feature_exps_disc", "def ClaimClassifierHyperParameterSearch():\n\n # Initialise dataset\n data = np.genfromtxt('car_insurance_training_data.csv', delimiter=\",\", skip_header=1)\n\n # Balance and Preprocess Dataset\n balanced_dataset = _balance_dataset_public(data)\n processed_dataset = _preprocessor_public(balanced_dataset)\n\n # Segment Training and validation Component of Dataset in ratio of 0.7:0.3\n train, test = np.split(processed_dataset, [int(0.7 * len(processed_dataset))])\n train_x = train[:,:-2]\n train_y = train[:,-1:]\n val_x = test[:,:-2]\n val_y = test[:,-1:]\n\n # Initialise Hyperparameter array\n best_hp = {'Epoch': None, 'BatchSize': None, 'LearningRate': None, 'ActFunc': None, 'Layers': None, 'Neurons': None}\n\n\n # OPTIMISATION: EPOCH\n best_accuracy = 0\n\n for epoch in [1,5,10,20,40,100,200,400,600]:\n\n classifier = ClaimClassifier(epoch=epoch)\n\n # Training of Classifier\n classifier.fit(train_x, train_y)\n accuracy = classifier.evaluate_architecture(val_x, val_y)\n print(\"Epoch\", epoch, \" -- Accuracy: \", accuracy)\n\n # Update Hyperparameter value, if accuracy > current best accuracy\n if (accuracy > best_accuracy):\n best_hp['Epoch'] = epoch\n\n # OPTIMISATION: BATCH SIZE\n best_accuracy = 0\n\n for batchsize in [2,4,8,16,32,64,128,256]:\n\n classifier = ClaimClassifier(epoch=best_hp['Epoch'], batchsize=batchsize)\n\n # Training of Classifier\n classifier.fit(train_x, train_y)\n accuracy = classifier.evaluate_architecture(val_x, val_y)\n print(\"BatchSize\", batchsize, \" -- Accuracy: \", accuracy)\n\n # Update Hyperparameter value, if accuracy > current best accuracy\n if (accuracy > best_accuracy):\n best_hp['BatchSize'] = batchsize\n\n # OPTIMISATION: LEARNING RATE\n best_accuracy = 0\n\n for learningrate in [0.000001, 0.00001, 0.00003, 0.00006, 0.0001, 0.001, 0.01, 0.05, 0.1, 0.5]:\n\n classifier = ClaimClassifier(epoch=best_hp['Epoch'], batchsize=best_hp['BatchSize'], learnrate=learningrate)\n\n # Training of Classifier\n classifier.fit(train_x, train_y)\n accuracy = classifier.evaluate_architecture(val_x, val_y)\n print(\"LearningRate\", learningrate, \" -- Accuracy: \", accuracy)\n\n # Update Hyperparameter value, if accuracy > current best accuracy\n if (accuracy > best_accuracy):\n best_hp['LearningRate'] = learningrate\n\n # OPTIMISATION: NUMBER OF NEURONS\n best_accuracy = 0\n\n for neurons in [512, 256, 128, 64, 32, 18, 16, 12, 9, 8, 4]:\n\n classifier = ClaimClassifier(epoch=best_hp['Epoch'], batchsize=best_hp['BatchSize'], learnrate=best_hp['LearningRate'], neurons=neurons)\n\n # Training of Classifier\n classifier.fit(train_x, train_y)\n accuracy = classifier.evaluate_architecture(val_x, val_y)\n print(\"Neurons\", neurons, \" -- Accuracy: \", accuracy)\n\n # Update Hyperparameter value, if accuracy > current best accuracy\n if (accuracy > best_accuracy):\n best_hp['Neurons'] = neurons\n\n # RETURN OPTIMAL HYPERPARAMTERS\n return best_hp", "def run_grid_search(model: object, params: dict, data: tuple, metrics: list, refit: str):\n\n X, y = data\n grid_model = GridSearchCV(model, params, scoring=metrics, refit=refit, n_jobs=-1, verbose=1)\n grid_model.fit(X, y)\n\n return grid_model", "def nested_cv_param_search( # pylint:disable=invalid-name # pylint:disable=too-many-branches\n X: np.ndarray, # pylint:disable=invalid-name # noqa: N803\n y: np.ndarray,\n param_dict: Dict[str, Any],\n pipeline: Pipeline,\n outer_cv: BaseCrossValidator,\n inner_cv: BaseCrossValidator,\n groups: Optional[np.ndarray] = None,\n hyper_search_params: Optional[Dict[str, Any]] = None,\n **kwargs,\n):\n if hyper_search_params is None:\n hyper_search_params = {\"search_method\": \"grid\"}\n\n scoring = kwargs.pop(\"scoring\", None)\n kwargs, scoring_dict = _setup_scoring_dict(scoring, **kwargs)\n\n cols = [\n \"param_search\",\n \"cv_results\",\n \"best_estimator\",\n \"conf_matrix\",\n \"predicted_labels\",\n \"true_labels\",\n \"train_indices\",\n \"test_indices\",\n ]\n for scorer in scoring_dict:\n cols.append(f\"test_{scorer}\")\n results_dict = {key: [] for key in cols}\n\n # fix random states of cv objects for reproducibility\n if hasattr(outer_cv, \"random_state\"):\n outer_cv.random_state = kwargs.get(\"random_state\", None)\n if hasattr(inner_cv, \"random_state\"):\n inner_cv.random_state = kwargs.get(\"random_state\", None)\n\n for train, test in tqdm(list(outer_cv.split(X, y, groups)), desc=\"Outer CV\"):\n cv_obj = _get_param_search_cv_object(\n pipeline, param_dict, inner_cv, scoring_dict, hyper_search_params, **kwargs\n )\n\n if groups is None:\n x_train, x_test, y_train, y_test = split_train_test(X, y, train, test)\n groups_train = None\n else:\n ( # pylint:disable=unbalanced-tuple-unpacking\n x_train,\n x_test,\n y_train,\n y_test,\n groups_train,\n _,\n ) = split_train_test(X, y, train, test, groups)\n\n cv_obj = _fit_cv_obj_one_fold(cv_obj, x_train, y_train, groups_train)\n\n results_dict[\"param_search\"].append(cv_obj)\n for scorer in scoring_dict:\n results_dict[f\"test_{scorer}\"].append(get_scorer(scorer)._score_func(y_test, cv_obj.predict(x_test)))\n results_dict[\"train_indices\"].append(train)\n results_dict[\"test_indices\"].append(test)\n results_dict[\"predicted_labels\"].append(cv_obj.predict(x_test))\n results_dict[\"true_labels\"].append(y_test)\n results_dict[\"cv_results\"].append(cv_obj.cv_results_)\n results_dict[\"best_estimator\"].append(cv_obj.best_estimator_)\n try:\n results_dict[\"conf_matrix\"].append(confusion_matrix(y_test, cv_obj.predict(x_test), normalize=None))\n except ValueError as e:\n if \"Classification metrics can't handle a mix of multiclass and continuous targets\" in e.args[0]:\n warnings.warn(\"Cannot compute confusion matrix for regression tasks.\")\n\n return results_dict", "def search(self):\n overall_start_time = time.time()\n # Get all possible parameter combinations as list\n parameter_combinations = list(dict(zip(self.parameter_grid, x))\n for x in itertools.product(*self.parameter_grid.values()))\n # Current grid search root path:\n gridsearch_root_path = os.path.join(self.dataset_custodian.prepared_data_dir_path, \"GridSearch\")\n if create_dir_if_necessary(gridsearch_root_path):\n # Write gridsearch parameters to file:\n write_file_content(os.path.join(gridsearch_root_path, \"gridsearch_\" + get_timestamp() + \".json\"),\n to_json({\"train_parameter_values\": self.parameter_grid,\n \"param_combinations\": parameter_combinations}))\n # Overall best file path:\n overall_best_score_file_path = os.path.join(gridsearch_root_path, OVERALL_BEST_SCORE_JSON_NAME)\n overall_best_score_data = ScoreData()\n if os.path.exists(overall_best_score_file_path):\n # Overall best score may be non-None from previous run!\n overall_best_score_data = ScoreData.from_json(read_file_content(overall_best_score_file_path))\n print(\"Searching best of\", len(parameter_combinations), \"parameter combinations ...\")\n\n param_comb_count = 0\n # For pretty printing:\n param_combs_digits = int(math.log10(len(parameter_combinations))) + 1\n # Outer grid search loop over each parameter combination:\n for param_combination in parameter_combinations:\n param_comb_count += 1\n param_comb_start_time = time.time()\n param_comb_count_str = (\"{:0\" + str(param_combs_digits) + \"d}/{}\").format(param_comb_count,\n len(parameter_combinations))\n if self.verbosity >= 1:\n print(\"\\nParameter combination\", param_comb_count_str + \":\", param_combination)\n\n # Create model directory name from hash because string representation of params is too long (>255 chars)\n # for file name\n curr_params_as_string = str(param_combination)\n # Directory name: MD5 plus start of all-parameter-string:\n param_comb_dir_name = as_safe_filename(get_md5_string(curr_params_as_string) + \"_\"\n + \",\".join((str(value) for value in param_combination.values())))\n param_comb_dir_name = param_comb_dir_name[0:255]\n param_comb_dir_path = os.path.join(gridsearch_root_path, param_comb_dir_name)\n # Create directory path if necessary:\n if create_dir_if_necessary(param_comb_dir_path, self.verbosity >= 2):\n # Write complete parameters as json:\n write_file_content(os.path.join(param_comb_dir_path, \"params.json\"), to_json(param_combination))\n\n # Create TensorBoard directory path if necessary:\n tensorboard_dir_root_path = os.path.join(param_comb_dir_path, \"tensorboard\")\n create_dir_if_necessary(tensorboard_dir_root_path, self.verbosity >= 2)\n\n param_comb_best_score_file_path = os.path.join(param_comb_dir_path, PARAM_COMB_BEST_SCORE_JSON_NAME)\n param_comb_best_score_data = ScoreData()\n if os.path.exists(param_comb_best_score_file_path):\n # Best score may be there from previous run!\n param_comb_best_score_data = ScoreData.from_json(read_file_content(param_comb_best_score_file_path))\n\n # Copy params dict because it is modified below\n param_combination_model_params = dict(param_combination)\n # Extract and remove non-model params:\n epochs = param_combination_model_params.pop(\"epochs\")\n repetitions = param_combination_model_params.pop(\"repetitions\")\n early_stopping = param_combination_model_params.pop(\"early_stopping\")\n batch_size = param_combination_model_params.pop(\"batch_size\")\n threshold_mode = param_combination_model_params.pop(\"threshold_mode\")\n # Create the generator which yields the training sequences\n data_generator_sequence = DatasetCustodianSequence(self.dataset_custodian, \"train\", batch_size,\n shuffle_on_end=True)\n\n reps_best_scores_data: List[ScoreData] = []\n rep_digits = int(math.log10(repetitions)) + 1\n # Multiple repetitions to average out variance\n for repetition in range(repetitions):\n # Initialize scores datas with \"none\" scores:\n reps_best_scores_data.append(ScoreData())\n early_stopping_best_main_scores_data = ScoreData()\n early_stopping_best_scores_data = ScoreData()\n # Create Tensorboard directory:\n tensorboard_dir_path = os.path.join(tensorboard_dir_root_path, str(repetition).zfill(rep_digits))\n create_dir_if_necessary(tensorboard_dir_path)\n\n # Create model:\n model = EagerModel.create(dataset_custodian=self.dataset_custodian,\n # input_shape=self.dataset_custodian.get_sample_shape(),\n output_neuron_count=len(self.dataset_custodian.get_labels()),\n **param_combination_model_params)\n if self.verbosity >= 2:\n if model.built:\n model.summary()\n else:\n print(\"Can not print model summary since model has not been built yet.\")\n\n if tensorflow.executing_eagerly():\n assert model.model_graph is not None\n\n # Create Tensorboard callback with model graph:\n tensorboard_callback = CustomTensorBoard(model_graph=model.model_graph, log_dir=tensorboard_dir_path,\n write_graph=True)\n\n train_losses = []\n epochs_digits = int(math.log10(epochs)) + 1\n # Perform the training for given epochs\n for epoch in range(epochs):\n epoch_start_time = time.time()\n if self.verbosity >= 2:\n # Print one line per epoch:\n print(\"P.C.\", param_comb_count_str + \", \", end=\"\")\n print((\"Rep. {:0\" + str(rep_digits) + \"d}/{}, \").format(repetition + 1, repetitions),\n end=\"\")\n print((\"Ep. {:0\" + str(epochs_digits) + \"d}/{}: \").format(epoch + 1, epochs), end=\"\")\n\n # Silently ignore FutureWarning inside the context manager:\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\", category=FutureWarning)\n # Generate a warning for NaN and/or (-)inf\n with errstate(inf_or_nan=ExecutionCallback.WARN):\n try:\n # Train the model for one epoch. We use our own epoch loop instead of fit_generator's\n # epochs > 1 to gain more control over pre- and post-epoch actions.\n train_hist_obj = model.fit_generator(\n data_generator_sequence,\n epochs=1,\n # Verbosity: 0 ^= no ouput, 1 ^= progress bar, 2 ^= one line per epoch:\n verbose=1 if self.verbosity >= 4 else 0,\n callbacks=[tensorboard_callback],\n shuffle=False, # Shuffling is done by DatasetCustodianSequence\n # Queue size: Number was heuristically chosen. Other numbers may work better in\n # other environments\n max_queue_size=10 * multiprocessing.cpu_count(),\n # Multiprocessing is deactivated since we rarely observed deadlocks\n use_multiprocessing=False,\n workers=multiprocessing.cpu_count())\n except InvalidArgumentError as ia_ex:\n # Error, which rarely occurs:\n # Input to reshape is a tensor with 65856 values, but the requested shape has 0\n # [[{{node training_52/Adam/gradients/value_repeated_52/Tile_grad/Reshape_1}}]]\n print(\"InvalidArgumentError during model.fit_generator:\", ia_ex)\n # Skip this epoch\n continue\n\n train_loss = train_hist_obj.history[\"loss\"][0] # [0] to select the only epoch\n\n # Display NaN gradients if any and if supported by optimizer (for now only own custom optimizer):\n model_optimizer = model.optimizer.optimizer\n if hasattr(model_optimizer, \"print_and_reset_nan_infos\"):\n model_optimizer.print_and_reset_nan_infos(suffix=\", \")\n\n # Terminate on NaN:\n if np.isnan(train_loss) or np.isinf(train_loss):\n if self.verbosity >= 2:\n print(\"Terminate On NaN: Invalid train loss\", train_loss)\n # Continue with next repetition:\n break\n\n # Employ the precision used for displaying the numbers\n train_losses.append(float(SCORE_FORMAT_STRING.format(train_loss)))\n\n # Determine train and validation (and test) scores:\n train_and_val_scores = {}\n\n # Whether softmax function should be applied to the models prediction before score calculation.\n # Since restructure for eager execution, models do not have a soft max layer. Instead, the loss\n # function contains the softmax function. Therefore, softmax should be applied to predictions\n # for score calculation too.\n # Models that were created before introduction of has_softmax_layer attribute, did not have a\n # softmax layer, i.e., the default value is False.\n apply_softmax = not getattr(model, \"has_softmax_layer\", False)\n\n # Dont show warnings arising from the model only predicting one class (such that the other class\n # has no support) like \"UndefinedMetricWarning: Precision and F-score are ill-defined and being set\n # to 0.0 in labels with no predicted samples.\"\n with expect_warnings([UndefinedMetricWarning, RuntimeWarning]):\n # Evaluate the model with training data\n train_score, train_score_name, train_all_scores, train_summary \\\n = get_scores(model, self.dataset_custodian,\n split_name_or_indices=\"train\",\n # Determine threshold depending on current parameter combination's value:\n threshold_to_use=threshold_mode,\n apply_softmax=apply_softmax,\n no_print=self.verbosity < 4)\n # Add train loss and other train scores to collection of all scores:\n train_all_scores[\"train_loss\"] = train_loss\n # Remember whether the threshold has been applied to softmax'ed outputs or to non-softmax'ed\n # outputs\n train_all_scores[\"softmax_has_been_applied\"] = apply_softmax\n # Store train scores and summary text:\n train_and_val_scores[\"train\"] = {\"scores\": train_all_scores, \"summary\": train_summary}\n if self.verbosity >= 2:\n # Continue epoch output line:\n print(\"Train loss\", SCORE_FORMAT_STRING.format(train_loss) + \",\",\n \"Train score\", train_score_name + \":\", SCORE_FORMAT_STRING.format(train_score) + \", \",\n end=\"\")\n\n # Add train scores to tensorboard:\n tensorboard_callback.add_scores(\n GridSearch.filter_and_prefix_scores(train_all_scores, \"train_\", \"float\"))\n\n if len(self.dataset_custodian.traintestval_split_indices[\"validation\"]) > 0:\n # Evaluate the model with validation data using the threshold determined using training data\n val_score, val_score_name, val_all_scores, val_summary \\\n = get_scores(model, self.dataset_custodian,\n split_name_or_indices=\"validation\",\n # Use the train threshold for validation\n threshold_to_use=train_all_scores[\"threshold\"],\n apply_softmax=apply_softmax,\n no_print=self.verbosity < 4)\n # Add val scores to collection of all scores:\n train_and_val_scores[\"validation\"] = {\"scores\": val_all_scores, \"summary\": val_summary}\n if self.verbosity >= 2:\n # Continue epoch output line:\n print(\"Validation score\", val_score_name + \":\", SCORE_FORMAT_STRING.format(val_score) +\n \", \" + \"\".join([sn + \": \" + SCORE_FORMAT_STRING.format(sv) + \", \"\n for sn, sv in val_all_scores.items()\n if type(sv).__name__.startswith(\"float\")]), end=\"\")\n # Print non-float (i.e. string) threshold:\n if isinstance(val_all_scores[\"threshold\"], str):\n print(\"threshold:\", val_all_scores[\"threshold\"] + \", \", end=\"\")\n # Print confusion matrix on small class count\n if len(self.dataset_custodian.get_label_ints()) < 5:\n print(\"conf_matrix:\", str(val_all_scores[\"conf_matrix\"].tolist()) + \", \", end=\"\")\n\n # Add scores to tensorboard:\n tensorboard_callback.add_scores(\n GridSearch.filter_and_prefix_scores(val_all_scores, \"val_\", \"float\"))\n else:\n if self.verbosity >= 2:\n print(\"No validation data (using train scores), \", end=\"\")\n val_score_name = train_score_name\n val_score = train_score\n\n # Manage best scores:\n model_file_name = SCORE_FORMAT_STRING.format(val_score) + \"_\" + val_score_name \\\n + \"_\" + SCORE_FORMAT_STRING.format(train_loss) + \"_train_loss\" \\\n + \"_\" + str(repetition) + \"_\" + str(epoch)\n\n current_score_data = ScoreData(model_file_name, param_combination, repetition, epoch,\n val_score_name, val_score, train_loss)\n\n # Early stopping:\n if early_stopping is not None:\n es_patience = early_stopping[\"patience\"]\n es_train_loss_reduction_percentage = early_stopping[\"train_loss_reduction_percentage\"]\n es_train_loss_stop_threshold_patience = early_stopping[\"train_loss_stop_threshold_patience\"]\n es_train_loss_stop_threshold = early_stopping[\"train_loss_stop_threshold\"]\n\n # Update early stopping score using es_train_loss_reduction_percentage:\n if current_score_data.greater_than(early_stopping_best_scores_data,\n es_train_loss_reduction_percentage):\n early_stopping_best_scores_data = current_score_data\n # Update separate early stopping main score which only tracks main score improvements:\n if current_score_data.main_score_greater_than(early_stopping_best_main_scores_data):\n early_stopping_best_main_scores_data = current_score_data\n\n # Check for main score progress during last es_train_loss_stop_threshold_patience epochs:\n if epoch - early_stopping_best_main_scores_data.epoch > es_train_loss_stop_threshold_patience:\n # No main score progress during last es_train_loss_stop_threshold_patience epochs.\n # Check train loss threshold:\n if current_score_data.train_loss < es_train_loss_stop_threshold:\n if self.verbosity >= 2:\n print(\"Early Stopping: Main score did not improve for\",\n es_train_loss_stop_threshold_patience,\n \"epochs and train loss\", current_score_data.train_loss,\n \"is less than threshold\", es_train_loss_stop_threshold)\n # Continue with next repetition:\n break\n # Check for overall score progress improvement (including train loss improvements):\n if epoch - early_stopping_best_scores_data.epoch > es_patience:\n if self.verbosity >= 2:\n print(\"Early Stopping: Score did not improve significantly for\", es_patience, \"epochs.\")\n # Continue with next repetition:\n break\n\n save_model = False\n # Repetition wise best score\n if current_score_data > reps_best_scores_data[repetition]:\n # Update best score\n reps_best_scores_data[repetition] = current_score_data\n # Save model:\n save_model = True\n\n # Param-comb wise best score:\n if current_score_data > param_comb_best_score_data:\n # Update best score\n param_comb_best_score_data = current_score_data\n # Write best param comb score to file:\n write_file_content(param_comb_best_score_file_path, param_comb_best_score_data.to_json())\n # Save model:\n save_model = True\n\n if save_model:\n # Save underlying model:\n save_model_to_path(model, param_comb_dir_path, model_file_name, add_timestamp=False,\n verbose=False)\n\n # Compute test scores if there is a test split:\n if len(self.dataset_custodian.traintestval_split_indices[\"test\"]) > 0:\n with expect_warnings([UndefinedMetricWarning, RuntimeWarning]):\n # Evaluate the model with test data using the best threshold determined using training\n # data\n test_score, test_score_name, test_all_scores, test_summary \\\n = get_scores(model, self.dataset_custodian,\n split_name_or_indices=\"test\",\n # Use the train threshold for test\n threshold_to_use=train_all_scores[\"threshold\"],\n apply_softmax=apply_softmax,\n no_print=self.verbosity < 4)\n # Add test scores to collection of all scores:\n train_and_val_scores[\"test\"] = {\"scores\": test_all_scores, \"summary\": test_summary}\n # Add test scores to tensorboard:\n tensorboard_callback.add_scores(\n GridSearch.filter_and_prefix_scores(test_all_scores, \"test_\", \"float\"))\n # Print basic test score info:\n if self.verbosity >= 2:\n print(\"Test score\", test_score_name + \":\",\n SCORE_FORMAT_STRING.format(test_score) + \", \",\n end=\"\")\n else:\n if self.verbosity >= 2:\n print(\"No test data, \", end=\"\")\n\n # Save scores:\n write_file_content(os.path.join(param_comb_dir_path, model_file_name) + \"_scores.json\",\n to_json(train_and_val_scores))\n\n print(\"Saved repetition-wise best model as\", model_file_name + \", \", end=\"\")\n else:\n if self.verbosity >= 2:\n print(\"Best validation score so far:\", param_comb_best_score_data.compact_repr() + \", \",\n end=\"\")\n\n # Overall best score:\n if current_score_data > overall_best_score_data:\n # Update overall best score:\n overall_best_score_data = current_score_data\n\n # ... and write it to file:\n write_file_content(overall_best_score_file_path, overall_best_score_data.to_json())\n\n # Epoch time:\n if self.verbosity >= 2:\n print(SCORE_FORMAT_STRING.format(time.time() - epoch_start_time), \"s\")\n # End of one repetition / one training. Tell CustomTensorBoard about this:\n tensorboard_callback.call_super_on_train_end()\n # Finished parameter combination: Print statistics and best model:\n if self.verbosity >= 1:\n print(\"Finished parameter combination in\", time.time() - param_comb_start_time, \"s with best score\",\n param_comb_best_score_data.compact_repr(),\n \"(parameter combination: \" + str(param_combination) + \")\")\n # Statistics for score over repetitions:\n repetition_best_main_scores = [rep_best_score.main_score for rep_best_score in reps_best_scores_data]\n repetition_score_summary = {\"best_scores_data\": reps_best_scores_data,\n \"best_main_scores\": repetition_best_main_scores,\n \"mean\": np.mean(repetition_best_main_scores),\n \"median\": np.median(repetition_best_main_scores),\n \"std\": np.std(repetition_best_main_scores),\n \"var\": np.var(repetition_best_main_scores)}\n print(\"Best validation scores by repetition:\", repetition_score_summary)\n write_file_content(os.path.join(param_comb_dir_path, REPETITIONS_SUMMARY_JSON_NAME),\n to_json(repetition_score_summary))\n # Elapsed time\n print(time.time() - overall_start_time, \"s elapsed so far.\")\n\n # Print current best score:\n if self.verbosity >= 1:\n self.print_overall_best_score_data(overall_best_score_data, \"Current \")\n\n # Finished all parameter combinations\n print(\"Completed grid search in\", int(time.time() - overall_start_time), \"s.\")\n self.print_overall_best_score_data(overall_best_score_data)\n self.generate_gridsearch_summary_csv(gridsearch_root_path, is_path=True)\n return overall_best_score_data" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Runs all filters on the word. If none of them return False, then returns true
def _run_filters(self, word): if len(self._filters) > 0: for f in self._filters: f.run(word) # print( 'running filter \n filtername: %s \n word: %s' % (f.__name__, word) ) # if f.run(word) is False: # print( 'filter %s failed: %s' % (f.__name__, word) ) # return False return True
[ "def __call__(self, buf):\n return all(filter_(buf) for filter_ in self.filters)", "def tweet_filter(self, tweet):\n for rule in self.tf:\n if not self.tf[rule](tweet):\n return False\n return True", "def match(self,filter):\n\n\n return filter in self.memo or filter in self.tags", "def test_filters(self):\r\n text = \"\"\"I contain WikiWords that ShouldBe skipped by the filters\"\"\"\r\n chkr = SpellChecker(\"en_US\",text=text,\r\n filters=[enchant.tokenize.WikiWordFilter])\r\n for err in chkr:\r\n # There are no errors once the WikiWords are skipped\r\n self.fail(\"Extraneous spelling errors were found\")\r\n self.assertEqual(chkr.get_text(),text)", "def process_word(self, word_arg: str) -> bool:\n print(\"WARNING: THIS FUNCTION HAS NOT BEEN EXTENSIVELY TESTED.\")\n if any(len(letter) != 1 for letter in self.alphabet):\n raise NotImplementedError(\n \"Can only process words if all strings have length 1.\"\n )\n word = list(word_arg)\n state = self.start\n for letter in word:\n if (state, letter) not in self.weighted_transitions:\n return False\n (state, _) = self.weighted_transitions[(state, letter)]\n return state in self.accepting", "async def execute_filters(self, event: BaseEvent) -> bool:\n result: bool = True\n for filter in self.filters:\n f_result = await filter.check(event)\n if not f_result:\n return False\n return result", "def filter(self, word):\n remove=False \n \n # Rule 0, word is not protein\n if word[\"type\"] == \"Protein\":\n remove = True\n \n # Rule 1, filter by pos tag\n # only pos tag with significant number of trigger occurrence are include\n # IN (preposition) is not used, need further study about this. for simplicity it's not included\n elif word[\"pos_tag\"] not in self.POS_TAG:\n remove = True\n \n # Rule 2, filter by word length\n # only words with length greater than 3 are included\n elif len(word[\"string\"]) < 4:\n remove = True \n \n # Rule 3, filter by score\n elif word['score'] < 0.02:\n remove = True\n \n # rule 4 filter by number of string occurance in dictionary\n elif self.wdict.count(word['string']) < 3:\n remove = True\n \n return remove", "def test_filter_keywords():\n assert KeywordsChief.filter_keyword(\"\") == (\"\", [], [])\n # check how the special chars are filtered/ignored by the filter_keywords() method\n assert KeywordsChief.filter_keyword(\"python\") == (\"python\", [], [])\n assert KeywordsChief.filter_keyword(\".python\") == (\"python\", [], [])\n assert KeywordsChief.filter_keyword(\"python.\") == (\"python\", [], [])\n assert KeywordsChief.filter_keyword(\".python.\") == (\"python\", [], [])\n assert KeywordsChief.filter_keyword(\"_python\") == (\"python\", [], [])\n assert KeywordsChief.filter_keyword(\"python_\") == (\"python\", [], [])\n assert KeywordsChief.filter_keyword(\"_python_\") == (\"python\", [], [])\n assert KeywordsChief.filter_keyword(\"___python___\") == (\"python\", [], [])\n assert KeywordsChief.filter_keyword(\"_._python_._\") == (\"python\", [], [])", "def any_text_contains(\n self, text: str, deep: bool = True, separator: str = \"\", strip: bool = False\n ) -> bool:\n ...", "def isFiltered():\n\treturn True", "def pos_filter(word, part_of_speech):\n return part_of_speech in word.get(\"tags\", {})", "def any_matches(self) -> bool:\n ...", "def BooleanSearch(text, all_words=None, any_words=None, none_words=None):\n if type(all_words) == str:\n all_words = [all_words]\n if type(any_words) == str:\n any_words = [any_words]\n if type(none_words) == str:\n none_words = [none_words]\n if all_words == None and any_words == None and none_words == None:\n print(\"Please specify at least one search option with all_words, any_words, or none_words.\")\n return\n\n ## Start with index of entire text list\n text_index = list(range(len(text)))\n\n ## Narrow list down to only indices where text contains all of the 'all_words'\n if all_words != None:\n all_words_list = text_index\n for w in all_words:\n if re.match('\\W', w[0]) == None:\n regex = re.compile(r'\\b' + w + r'\\b', flags=re.IGNORECASE)\n else:\n regex = re.compile(r'\\B' + w + r'\\b', flags=re.IGNORECASE)\n temp_list = [i for i in text_index if regex.search(text[i]) != None]\n all_words_list = sorted(list(set(all_words_list).intersection(set(temp_list))))\n text_index = all_words_list\n\n ## Narrow list down to only indices where text contains one or more of the 'any_words'\n if any_words != None:\n any_words_list = []\n for w in any_words:\n if re.match('\\W', w[0]) == None:\n regex = re.compile(r'\\b' + w + r'\\b', flags=re.IGNORECASE)\n else:\n regex = re.compile(r'\\B' + w + r'\\b', flags=re.IGNORECASE)\n temp_list = [i for i in text_index if regex.search(text[i]) != None]\n any_words_list = any_words_list + temp_list\n text_index = sorted(list(set(any_words_list)))\n\n ## Narrow list down to only indices where text does not contain any of the 'none_words'\n if none_words != None:\n none_words_list = text_index\n for w in none_words:\n if re.match('\\W', w[0]) == None:\n regex = re.compile(r'\\b' + w + r'\\b', flags=re.IGNORECASE)\n else:\n regex = re.compile(r'\\B' + w + r'\\b', flags=re.IGNORECASE)\n temp_list = [i for i in text_index if regex.search(text[i]) == None]\n none_words_list = sorted(list(set(none_words_list).intersection(set(temp_list))))\n text_index = none_words_list\n\n return text_index", "def filter_words(pred, filter_string=None, filename = \"words.txt\"):\n count = 0\n # Make a true predicate function, folding in the filter_string if there was one.\n # I want this so when I run through all lines in words.txt, I can just check\n # true_pred(word), without having to worry about whether I also need to pass\n # in the filter string.\n if filter_string==None:\n # No filter string, so our true_pred fuction will really just be a pass-through\n # for pred, which could be has_no_e or is_abecedarian\n def true_pred(word):\n return pred(word)\n else:\n # Else case. So there *is* a filter string. I want to be able to filter without\n # referring to the filter string, so true_pred is now a \"wrapper\" around\n # another fuction, with that extra argument already in there\n # pred here might be avoids, uses_only or uses_all\n def true_pred(word):\n return pred(word, filter_string)\n fin = open(filename)\n for line in fin:\n word = line.strip()\n if true_pred(word):\n print(word)\n count +=1\n print(\"Found\", count, \"words\")", "def test_phrase_punc_filt(self):\n test_search_phrase1 = \"this would be considered a search phrase. ;; yes. HELLO\"\n expected_phrase1 = ['yes', 'hello', 'search', 'phrase', 'considered', 'would']\n test_search_phrase2 = \"duplicate duplicate. duplicate. duplicate. duplicate DUPLICATE\"\n expected_phrase2 = ['duplicate']\n test_search_phrase3 = \" \"\n expected_phrase3 = []\n test_search_phrase4 = ''\n expected_phrase4 = []\n\n test_nonSearchPhrase1 = \"this would be an example of an. a HTML HTML HTML page phrase input\"\n expected_nsp1 = ['would', 'example', 'html', 'html', 'html', 'page', 'phrase', 'input']\n test_nonSearchPhrase2 = \" \"\n expected_nsp2 = []\n test_nonSearchPhrase3 = \" nuclear warhead\"\n expected_nsp3 = ['nuclear', 'warhead']\n test_nonSearchPhrase4 = \"these duplicate, should duplicate, keep, duplicate.\"\n expected_nsp4 = ['duplicate', 'duplicate', 'duplicate', 'keep']\n\n # Tests that each of the arrays returned contain the same words that the resulting array returned from function\n # No duplicates\n res1 = self.__class__.testCrawler.phrase_punc_filt(test_search_phrase1, user_input=True)\n res1ctd = all(e in res1 for e in expected_phrase1) and len(res1) == len(expected_phrase1)\n\n res2 = self.__class__.testCrawler.phrase_punc_filt(test_search_phrase2, user_input=True)\n res2ctd = all(e in res2 for e in expected_phrase2) and len(res2) == len(expected_phrase2)\n\n res3 = self.__class__.testCrawler.phrase_punc_filt(test_search_phrase3, user_input=True)\n res3ctd = all(e in res3 for e in expected_phrase3) and len(res3) == len(expected_phrase3)\n\n res4 = self.__class__.testCrawler.phrase_punc_filt(test_search_phrase4, user_input=True)\n res4ctd = all(e in res4 for e in expected_phrase4) and len(res4) == len(expected_phrase4)\n\n # W duplicates for web scraper\n nsp1 = self.__class__.testCrawler.phrase_punc_filt(test_nonSearchPhrase1)\n nsp1ctd = all(e in nsp1 for e in expected_nsp1) and len(nsp1) == len(expected_nsp1)\n\n nsp2 = self.__class__.testCrawler.phrase_punc_filt(test_nonSearchPhrase2)\n nsp2ctd = all(e in nsp2 for e in expected_nsp2) and len(nsp2) == len(expected_nsp2)\n\n nsp3 = self.__class__.testCrawler.phrase_punc_filt(test_nonSearchPhrase3)\n nsp3ctd = all(e in nsp3 for e in expected_nsp3) and len(nsp3) == len(expected_nsp3)\n\n nsp4 = self.__class__.testCrawler.phrase_punc_filt(test_nonSearchPhrase4)\n nsp4ctd = all(e in nsp4 for e in expected_nsp4) and len(nsp4) == len(expected_nsp4)\n\n self.assertTrue(res1ctd)\n self.assertTrue(res2ctd)\n self.assertTrue(res3ctd)\n self.assertTrue(res4ctd)\n\n self.assertTrue(nsp1ctd)\n self.assertTrue(nsp2ctd)\n self.assertTrue(nsp3ctd)\n self.assertTrue(nsp4ctd)", "def apply_filter(full_path, filter_rexs):\n for rex in filter_rexs:\n if rex.match(full_path):\n return True\n return False", "def combine_filters(*args):\n def func(rec):\n for filt in args:\n if not filt(rec):\n return False\n return True\n return func", "def allInText(self, words, text):\n index = 0\n for word in words:\n index = text[index:].find(word)\n if index == -1:\n return False\n return True", "def all_fluffy(s):\n \n for ch in s:\n if ch not in 'fluffy':\n return False\n return True" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
HTMLescape the text in `t`. We first hide real common entities to avoid double escaping
def escape(t): return (t .replace("&quot;", '@quot;') .replace("&amp;", "@amp;").replace("&lt;", "@lt;").replace("&gt;", "@gt;") .replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;") .replace("'", "&#39;").replace('"', "&quot;") .replace("\\", "&#92;") .replace("@quot;", '&quot;') .replace("@amp;", "&amp;").replace("@lt;", "&lt;").replace("@gt;", "&gt;") )
[ "def encode_html( self, text):\n\t\thtml_escape_table = {\n\t\t\t\"&\": \"&amp;\",\n\t\t\t'\"': \"&quot;\",\n\t\t\t\"'\": \"&apos;\",\n\t\t\t\">\": \"&gt;\",\n\t\t\t\"<\": \"&lt;\",\n\t\t\t}\n\t\t\n\t\tdef html_escape(text):\n\t\t\t\"\"\"Produce entities within text.\"\"\"\n\t\t\tL=[]\n\t\t\tfor c in text:\n\t\t\t\tL.append(html_escape_table.get(c,c))\n\t\t\treturn \"\".join(L)\n\n\t\treturn html_escape( text )", "def escape_html(html):\n #boileeeeeeerplate\n return unicode(html).replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace('\"', '&quot;').replace(\"'\", '&#39;')", "def escape_html(s):\n return cgi.escape(s, quote = True)", "def html_escape(s):\n if s is None:\n return ''\n if hasattr(s, '__html__'):\n return s.__html__()\n if not isinstance(s, basestring):\n if hasattr(s, '__unicode__'):\n s = unicode(s)\n else:\n s = str(s)\n s = cgi.escape(s, True)\n if isinstance(s, unicode):\n s = s.encode('ascii', 'xmlcharrefreplace')\n return s", "def convert_unicode_to_html(text):\n return html.escape(text).encode(\"ascii\", \"xmlcharrefreplace\").decode()", "def _escape(self, s):\r\n return s", "def escape(data, entities={}):\r\n data = data.replace(\"&\", \"&amp;\")\r\n data = data.replace(\"<\", \"&lt;\")\r\n data = data.replace(\">\", \"&gt;\")\r\n if entities:\r\n data = __dict_replace(data, entities)\r\n return data", "def escapeForContent(data):\n if isinstance(data, unicode):\n data = data.encode('utf-8')\n data = data.replace(b'&', b'&amp;'\n ).replace(b'<', b'&lt;'\n ).replace(b'>', b'&gt;')\n return data", "def templatize(self, text, context):\n return Template(\"{% autoescape off %}\" + text + \"{% endautoescape %}\").render(context)", "def html_encode_django_chars(txt):\n txt = txt.replace(\"{\", \"&#123;\")\n txt = txt.replace(\"}\", \"&#125;\")\n txt = txt.replace(\"%\", \"&#37;\")\n return txt", "def UndoSafeForHTML(escaped_string):\n raw_string = escaped_string.replace('&lt;', '<')\n raw_string = raw_string.replace('&gt;', '>')\n raw_string = raw_string.replace('&quot;', '\"')\n raw_string = raw_string.replace('&amp;', '&')\n return raw_string", "def escape(cls, text, quotes=True):\r\n if not text:\r\n return cls()\r\n if type(text) is cls:\r\n return text\r\n if hasattr(text, '__html__'):\r\n return cls(text.__html__())\r\n\r\n text = text.replace('&', '&amp;') \\\r\n .replace('<', '&lt;') \\\r\n .replace('>', '&gt;')\r\n if quotes:\r\n text = text.replace('\"', '&#34;')\r\n return cls(text)", "def _escape(message):\n translations = {\n '\"': '&quot;',\n \"'\": '&#39;',\n '`': '&lsquo;',\n '\\n': '<br>',\n }\n for k, v in translations.items():\n message = message.replace(k, v)\n\n return message", "def __html2unicode(self, s):\n # First the digits:\n ents = set(html_entity_digit_re.findall(s))\n if len(ents) > 0:\n for ent in ents:\n entnum = ent[2:-1]\n try:\n entnum = int(entnum)\n s = s.replace(ent, unichr(entnum))\n except:\n pass\n # Now the alpha versions:\n ents = set(html_entity_alpha_re.findall(s))\n ents = filter((lambda x : x != amp), ents)\n for ent in ents:\n entname = ent[1:-1]\n try: \n s = s.replace(ent, unichr(htmlentitydefs.name2codepoint[entname]))\n except:\n pass \n s = s.replace(amp, \" and \")\n return s", "def unescape(text):\n\n return __entity_regex.sub(__replacement_for_entity, text)", "def test_escape_tags(self):\n simple_replace = ('#', '$', '%', '_', '{', '}', '&')\n for character in simple_replace:\n escaped_char = u'\\\\{}'.format(character)\n self.assertEqual(tags.latex_safe(character), escaped_char)\n\n self.assertEqual(tags.latex_safe('\\\\'), '\\\\textbackslash{}')\n self.assertEqual(tags.latex_safe('~'), '\\\\textasciitidle{}')\n self.assertEqual(tags.latex_safe('^'), '\\\\^{}')", "def url_escape(self, text):\n return urllib.parse.quote(text, safe='~-._')", "def HTML(html): # pylint: disable=invalid-name\n return markupsafe.Markup(html)", "def html_unquote(s, encoding=None):\r\n if isinstance(s, str):\r\n if s == '':\r\n # workaround re.sub('', '', u'') returning '' < 2.5.2\r\n # instead of u'' >= 2.5.2\r\n return u''\r\n s = s.decode(encoding or default_encoding)\r\n return _unquote_re.sub(_entity_subber, s)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
See logging.Handler.emit(self, record) docs.
def emit(self, record): pass # do not emit the record. Other handlers can do that.
[ "def emit(self, record):\n try:\n if self.shouldRollover(record):\n self.doRollover()\n if self.header_msg is not None:\n for msg in self.header_msg:\n header_record = logging.LogRecord(\"\", 20, \"\", 0, msg, (), None, None)\n logging.FileHandler.emit(self, header_record)\n logging.FileHandler.emit(self, record)\n except (KeyboardInterrupt, SystemExit) as err:\n raise err\n except Exception as err:\n self.handleError(record)", "def emit(self, record: logging.LogRecord):\n self.model_backend.juju_log(record.levelname, self.format(record))", "def emit(self, record: LogRecord):\n self.buffer.append(record)", "def emit(self, record):\n try:\n if self.shouldRollover(record):\n self.doRollover()\n FileHandler.emit(self, record)\n except (KeyboardInterrupt, SystemExit):\n raise\n except:\n self.handleError(record)", "def emit(self, record):\n from jobcontrol.globals import current_app, execution_context\n\n try:\n # If we have no build, do nothing.\n # Note that execution_context.build_id should raise an exception\n # itself, as there will not be any execution_context..\n if execution_context.build_id is None:\n raise RuntimeError()\n except:\n return\n\n # Replace traceback with text representation, as traceback\n # objects cannot be pickled\n # if record.exc_info is not None:\n # tb = traceback.format_exception(*record.exc_info)\n # record.exc_info = record.exc_info[0], record.exc_info[1], tb\n\n # NOTE: This will be done by the storage!\n\n current_app.storage.log_message(\n build_id=execution_context.build_id,\n record=record)", "def handle(self, record):\n return self.logger.handle(record)", "def emit(self, record):\n\n record.colored_levelname = (self.colors[record.levelname] +\n record.levelname +\n self.colors[None])\n sys.stdout.write(self.format(record) + '\\n')", "def emit(self, record):\r\n try:\r\n import httplib, urllib\r\n host = self.host\r\n h = httplib.HTTP(host)\r\n url = self.url\r\n data = urllib.urlencode(self.mapLogRecord(record))\r\n if self.method == \"GET\":\r\n if (string.find(url, '?') >= 0):\r\n sep = '&'\r\n else:\r\n sep = '?'\r\n url = url + \"%c%s\" % (sep, data)\r\n h.putrequest(self.method, url)\r\n # support multiple hosts on one IP address...\r\n # need to strip optional :port from host, if present\r\n i = string.find(host, \":\")\r\n if i >= 0:\r\n host = host[:i]\r\n h.putheader(\"Host\", host)\r\n if self.method == \"POST\":\r\n h.putheader(\"Content-type\",\r\n \"application/x-www-form-urlencoded\")\r\n h.putheader(\"Content-length\", str(len(data)))\r\n h.endheaders()\r\n if self.method == \"POST\":\r\n h.send(data)\r\n h.getreply() #can't do anything with the result\r\n except (KeyboardInterrupt, SystemExit):\r\n raise\r\n except:\r\n self.handleError(record)", "def emit(self, record):\n record.source = self.source\n record.kind = self.kind\n return super(AggregatorHandler, self).emit(record)", "def emit(self, record):\n msg = self.format(record)\n syspri = self.mapPriority(record.levelname)\n # encodePriority() expects 1 for \"user\", shifts it to 8. but\n # syslog.LOG_USER is ALREADY shifted to 8, passing it to\n # encodePriority shifts it again to 64. No. Pass 0 for facility, then\n # do our own bitwise or.\n pri = self.encodePriority(0, syspri) | self.facility\n\n # Point syslog at our file. Syslog module remains pointed at our\n # log file until any other call to syslog.openlog(), such as those\n # in p4gf_audit_log.py.\n syslog.openlog(self.ident, syslog.LOG_PID)\n syslog.syslog(pri, msg)", "def emit(self, record):\n message = str(record.msg)\n\n\n max_message_size = 256000\n if len(message) <= max_message_size or six.PY2:\n super(SplitFileHandler, self).emit(record)\n else:\n chunks = [\n message[i:i + max_message_size]\n for i in range(0, len(message), max_message_size)\n ]\n\n for idx, chunk in enumerate(chunks):\n record.msg = 'Part {}/{}: {}'.format(str(idx + 1), len(chunks), chunk)\n super().emit(record)", "def emit(self, record):\r\n try:\r\n import smtplib\r\n try:\r\n from email.Utils import formatdate\r\n except:\r\n formatdate = self.date_time\r\n port = self.mailport\r\n if not port:\r\n port = smtplib.SMTP_PORT\r\n smtp = smtplib.SMTP(self.mailhost, port)\r\n msg = self.format(record)\r\n msg = \"From: %s\\r\\nTo: %s\\r\\nSubject: %s\\r\\nDate: %s\\r\\n\\r\\n%s\" % (\r\n self.fromaddr,\r\n string.join(self.toaddrs, \",\"),\r\n self.getSubject(record),\r\n formatdate(), msg)\r\n smtp.sendmail(self.fromaddr, self.toaddrs, msg)\r\n smtp.quit()\r\n except (KeyboardInterrupt, SystemExit):\r\n raise\r\n except:\r\n self.handleError(record)", "def handle(self, record):\n tag = record.name\n if tag not in self.loggers:\n self.loggers[tag] = SingleFileLogger(self.config, tag,\n formatter = self.formatter)\n return self.loggers[tag].handle(record)", "def emit(self, event_name, **kwargs):\n ...", "def record_call(self, record_call):\n\n self._record_call = record_call", "def test_emit(self):\n messages = []\n def observer(msg):\n messages.append((threading.current_thread().ident, msg))\n\n threadLog = ThreadLogObserver(observer)\n ident = threadLog._thread.ident\n msg1 = {}\n msg2 = {\"a\": \"b\"}\n threadLog(msg1)\n threadLog(msg2)\n threadLog.stop()\n # Wait for writing to finish:\n threadLog._thread.join()\n self.assertEqual(messages, [(ident, msg1), (ident, msg2)])", "def emit(self, event, *args):\n events = self.__events.get(event, [])\n if len(events):\n for e in events:\n e(*args)\n else:\n sink_event = getattr(self.__sink, event, None)\n if sink_event:\n sink_event(*args)", "def received_record(self):\n self._received_records += 1\n self.info.update({'received_records': self._received_records})", "def emitRecordDoubleClicked( self, record ):\n if ( not self.signalsBlocked() ):\n self.recordDoubleClicked.emit(record)", "def emit(self, ctx, modules, fd):\n return" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds a new switchPorts resource on the server and adds it to the container. Args
def add( self, Enabled=None, EthernetAddress=None, NumberOfPorts=None, PortName=None, PortNumber=None, ): # type: (bool, str, int, str, str) -> SwitchPorts return self._create(self._map_locals(self._SDM_ATT_MAP, locals()))
[ "def streaming_ports_add(ports: str):\n return _run_speedify_cmd([\"streaming\", \"ports\", \"add\", ports])", "def add_switch(session, **kwargs) -> Switch:\n\n # Check if switch already exists\n if 'name' not in kwargs:\n raise KeyError(\"Missing necessary argument 'name' for adding switch\")\n if query_switch(session, kwargs['name']) is not None:\n raise ValueError(\n \"Cannot add switch with name '{}' - switch already exists\"\n .format(kwargs['name']))\n\n # Replace list of port strings with list of port objects\n if 'ports' in kwargs:\n kwargs['ports'] = ports_from_dict(session, kwargs['ports'])\n\n # Replace switch model string with switch model object\n if 'model' in kwargs:\n kwargs['model'] = query_switch_model(session, kwargs['model'])\n\n # Create switch\n sw = Switch(**kwargs)\n session.add(sw)\n session.commit()\n return sw", "def create_and_attach_ports(self):\n self.validate()\n\n for nic_type, nic in self._validated:\n if nic_type != 'port':\n # The 'binding:host_id' must be set to ensure IP allocation\n # is not deferred.\n # See: https://storyboard.openstack.org/#!/story/2009715\n port = self._connection.network.create_port(\n binding_host_id=self._node.id, **nic)\n self.created_ports.append(port.id)\n LOG.info('Created port %(port)s for node %(node)s with '\n '%(nic)s', {'port': _utils.log_res(port),\n 'node': _utils.log_res(self._node),\n 'nic': nic})\n else:\n # The 'binding:host_id' must be set to ensure IP allocation\n # is not deferred.\n # See: https://storyboard.openstack.org/#!/story/2009715\n self._connection.network.update_port(\n nic, binding_host_id=self._node.id)\n port = nic\n\n self._connection.baremetal.attach_vif_to_node(self._node,\n port.id)\n LOG.info('Attached port %(port)s to node %(node)s',\n {'port': _utils.log_res(port),\n 'node': _utils.log_res(self._node)})\n self.attached_ports.append(port.id)", "def add_port_info(nodes, detail=True):\n ironic_client = get_ironic_client()\n ports = ironic_client.port.list(detail=detail)\n\n ports_by_node = {p.node_uuid: p for p in ports}\n\n for node in nodes:\n setattr(node, 'port', ports_by_node[node.uuid])", "def vrouter_iospf_vlan_ports_add(module, switch_name, cluster_ports, task, msg):\n output = ''\n vlan_id = module.params['pn_iospf_vlan']\n\n cli = pn_cli(module)\n clicopy = cli\n cli += ' switch %s vlan-show format id no-show-headers ' % switch_name\n existing_vlans = run_command(module, cli, task, msg).split()\n\n if vlan_id not in existing_vlans:\n cli = clicopy\n cli += ' switch %s vlan-create id %s scope cluster ' % (switch_name,\n vlan_id)\n cli += ' ports none description iOSPF-cluster-vlan '\n run_command(module, cli, task, msg)\n output = ' %s: Created vlan with id %s \\n' % (switch_name, vlan_id)\n\n cli = clicopy\n cli += ' switch %s vlan-port-add vlan-id %s ports %s' % (switch_name, vlan_id, cluster_ports)\n run_command(module, cli, task, msg)\n\n return output", "def add_server(self, host_ips):\t\t\n\t\tself.swarm_manager.add_server(host_ips)", "def create_ports(self, data):\n return self._bulk_create(_port.Port, data)", "def _add_fc_port_to_host(self, hostid, wwn, multipathtype=0):\n portname = HOST_PORT_PREFIX + wwn\n cli_cmd = ('addhostport -host %(id)s -type 1 '\n '-wwn %(wwn)s -n %(name)s -mtype %(multype)s'\n % {'id': hostid,\n 'wwn': wwn,\n 'name': portname,\n 'multype': multipathtype})\n self._execute_cli(cli_cmd)", "def enable_ports(self):\n pass", "def add_port_model(session, switch_model_resource_id: str, **kwargs) -> PortModel:\n\n # Check if switch model exists\n sm = query_switch_model(session, switch_model_resource_id)\n if sm is None:\n raise ValueError('Given switch model does not exist')\n\n # Check if port model already exists on given switch model\n if 'name' not in kwargs:\n raise KeyError(\"Missing necessary argument 'name' for adding port model\")\n if query_port_model(session, switch_model_resource_id, kwargs['name']) is not None:\n raise ValueError(\n \"Cannot add port model '{}' on switch model '{}' - port model already exists\"\n .format(kwargs['name'], str(sm)))\n\n # Create port model\n pm = port_model_from_dict(session, **kwargs)\n\n # Add port model to switch model\n ports = sm.ports\n ports.append(pm)\n sm.ports = ports\n\n session.commit()\n\n return pm", "def bind_switch_port_ip_host(self, switch_port, iphost_num):\n return [\"switchport-bind %s iphost %s\" % (switch_port, iphost_num)]", "def streamingbypass_ports_add(ports: str):\n return _run_speedify_cmd([\"streamingbypass\", \"ports\", \"add\", ports])", "def add_switch(self, name, inputs, outputs, export_switch=True,\n make_optional=()):\n # Check the unicity of the name we want to insert\n if name in self.nodes:\n raise ValueError(\"Pipeline cannot have two nodes with the same \"\n \"name: {0}\".format(name))\n\n # Create the node\n node = Switch(self, name, inputs, outputs, make_optional=make_optional)\n self.nodes[name] = node\n\n # Export the switch controller to the pipeline node\n if export_switch:\n self.export_parameter(name, \"switch\", name)", "def add_port_to_ovs_bridge(self, vlan):\n\n if self.test:\n return True\n try:\n port_name = 'ovim-{}'.format(str(vlan))\n command = 'sudo ovs-vsctl add-port br-int {} tag={}'.format(port_name, str(vlan))\n self.run_command(command)\n return True\n except RunCommandException as e:\n self.logger.error(\"add_port_to_ovs_bridge Exception: \" + str(e))\n return False", "def enable_ports(module, internal_ports, task, msg):\n cli = pn_cli(module)\n clicopy = cli\n cli += ' switch-local port-config-show format enable no-show-headers '\n if 'off' in run_command(module, cli, task, msg).split():\n cli = clicopy\n cli += ' switch-local port-config-show format port no-show-headers '\n out = run_command(module, cli, task, msg)\n\n cli = clicopy\n cli += ' switch-local port-config-show format port speed 40g '\n cli += ' no-show-headers '\n out_40g = run_command(module, cli, task, msg)\n out_remove10g = []\n\n if len(out_40g) > 0 and out_40g != 'Success':\n out_40g = out_40g.split()\n out_40g = list(set(out_40g))\n if len(out_40g) > 0:\n for port_number in out_40g:\n out_remove10g.append(str(int(port_number) + int(1)))\n out_remove10g.append(str(int(port_number) + int(2)))\n out_remove10g.append(str(int(port_number) + int(3)))\n\n if out:\n out = out.split()\n out = set(out) - set(out_remove10g + internal_ports)\n out = list(out)\n if out:\n ports = ','.join(out)\n cli = clicopy\n cli += ' switch-local port-config-modify port %s enable ' % (\n ports)\n return run_command(module, cli, task, msg)\n\n return 'Success'", "def _action_change_port(self, machine, node):\n # this exist here cause of docker host implementation\n if machine.machine_type == 'container-host':\n return\n container_info = self.inspect_node(node)\n\n try:\n port = container_info.extra[\n 'network_settings']['Ports']['22/tcp'][0]['HostPort']\n except (KeyError, TypeError):\n # add TypeError in case of 'Ports': {u'22/tcp': None}\n port = 22\n\n from mist.api.machines.models import KeyMachineAssociation\n key_associations = KeyMachineAssociation.objects(machine=machine)\n for key_assoc in key_associations:\n key_assoc.port = port\n key_assoc.save()\n return True", "def add_port_interface(self, name, iface_port):\n\n try:\n with self.ipdb_controller.interfaces[name] as iface:\n iface.add_port(iface_port)\n except Exception:\n logging.error('Cannot add port to interface')\n return", "def set_ports(r):\n ipc_port = str(r.netsim.config.IPC_PORT)\n netconf_ssh_port = str(r.netsim.config.NETCONF_SSH_PORT)\n netconf_tcp_port = str(r.netsim.config.NETCONF_SSH_PORT)\n snmp_port = str(r.netsim.config.SNMP_PORT)\n cli_ssh_port = str(r.netsim.config.CLI_SSH_PORT)\n\n os.environ[\"IPC_PORT\"] = ipc_port\n os.environ[\"NETCONF_SSH_PORT\"] = netconf_ssh_port\n os.environ[\"NETCONF_TCP_PORT\"] = netconf_tcp_port\n os.environ[\"SNMP_PORT\"] = snmp_port\n os.environ[\"CLI_SSH_PORT\"] = cli_ssh_port\n\n netsim_dir = r.netsim.config.netsim_dir\n os.environ[\"NETSIM_DIR\"] = netsim_dir", "def add_iscsi_port_to_host(self, hostid, connector,\n chapinfo=None, multipathtype=0,):\n\n initiator = connector['initiator']\n # Add an iSCSI initiator.\n if not self._initiator_added(initiator):\n self._add_initiator(initiator)\n # Add the initiator to host if not added before.\n port_name = HOST_PORT_PREFIX + six.text_type(hash(initiator))\n portadded = False\n hostport_info = self.get_host_port_info(hostid)\n if hostport_info:\n for hostport in hostport_info:\n if hostport[2] == initiator:\n portadded = True\n break\n\n if chapinfo:\n if self._chapuser_added_to_array(initiator, chapinfo[0]):\n self.change_chapuser_password(chapinfo)\n else:\n self.add_chapuser_to_array(chapinfo)\n if not self._chapuser_added_to_initiator(initiator, chapinfo[0]):\n self.add_chapuser_to_ini(chapinfo, initiator)\n\n self.active_chap(initiator)\n\n if not portadded:\n cli_cmd = ('addhostport -host %(id)s -type 5 '\n '-info %(info)s -n %(name)s -mtype %(multype)s'\n % {'id': hostid,\n 'info': initiator,\n 'name': port_name,\n 'multype': multipathtype})\n out = self._execute_cli(cli_cmd)\n\n msg = ('Failed to add iSCSI port %(port)s to host %(host)s'\n % {'port': port_name,\n 'host': hostid})\n self._assert_cli_operate_out('add_iscsi_port_to_host',\n msg, cli_cmd, out)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds and retrieves switchPorts resources from the server. All named parameters are evaluated on the server using regex. The named parameters can be used to selectively retrieve switchPorts resources from the server. To retrieve an exact match ensure the parameter value starts with ^ and ends with $ By default the find method takes no parameters and will retrieve all switchPorts resources from the server. Args
def find( self, Enabled=None, EthernetAddress=None, NumberOfPorts=None, PortName=None, PortNumber=None, ): # type: (bool, str, int, str, str) -> SwitchPorts return self._select(self._map_locals(self._SDM_ATT_MAP, locals()))
[ "def discover(self, pump_id = None):\n from serial import Serial\n\n from sys import version_info\n if pump_id is None:\n pump_id = self.pump_id\n\n available_ports = self.available_ports\n port = None\n for port_name in self.available_ports:\n try:\n debug(\"Trying self.port %s...\" % port_name)\n port = Serial(port_name, timeout = 2)\n port.close()\n except:\n available_ports.pop(available_ports.index(port_name))\n debug(\"available ports {}...\".format(available_ports))\n for port_name in available_ports:\n debug(\"Trying port %s...\" % port_name)\n port = Serial(port_name, timeout = 2)\n port.baudrate = 9600\n port.timeout = 2\n port.flushInput()\n port.flushOutput()\n full_reply = self.query(command = b\"/1?80\\r\", port = port)\n if len(full_reply) != 0:\n debug(\"port %r: full_reply %r\" % (port_name,full_reply))\n reply = full_reply[3:][:-3]\n status = reply[0:1]\n received_pump_id = int(reply[3:4].decode('Latin-1'))\n debug(\"self.ports %r: full_reply %r, status %r, pump_id %r\" % (port_name,full_reply, status, pump_id))\n else:\n received_pump_id = 0\n debug(\"port %r: full_reply %r\" % (port_name,full_reply))\n\n if received_pump_id == pump_id: # get pump id for new_pump\n info(\"self.port %r: found pump %r\" % (port_name,pump_id))\n break\n else:\n port.close()\n port = None\n debug(\"closing the serial connection\")\n return port", "def get_ports(module, switch, peer_switch, task, msg):\n cli = pn_cli(module)\n cli += ' switch %s port-show hostname %s' % (switch, peer_switch)\n cli += ' format port no-show-headers '\n return run_command(module, cli, task, msg).split()", "def get_ports(params):\n output = subprocess.Popen((\"/usr/bin/snmpwalk\", \"-On\", \"-v2c\", \"-c\",\n params['community'], params['target'], port_name_prefix),\n stdout=subprocess.PIPE).communicate()[0]\n ports = {}\n for line in output.split(\"\\n\"):\n m = re.match(\n r'[.0-9]+\\.(\\d+) = STRING: \"?(?:ethernet)?([0-9/]+)\"?', line)\n if m:\n if not params['pattern'] or re.match(params['pattern'], m.group(2)):\n ports[m.group(2)] = m.group(1)\n return ports", "def find(resource_name, paths: Optional[Any] = ...):\n ...", "def findServiceByNameAndIpAndPort(service_name, ip, port):\n DB_PATH = Config.getDbPath()\n conn = sqlite3.connect(DB_PATH)\n response = conn.execute(\n \"\"\"SELECT * FROM SERVICE_RD WHERE SERVICE_NAME = ? AND IP = ? AND PORT = ?\"\"\",\n (service_name,\n ip,\n port)).fetchall()\n conn.close()\n return response", "def test_get_logical_router_port_by_switch_id(self):\n fake_router_port = test_constants.FAKE_ROUTER_PORT.copy()\n resp_resources = {\n 'result_count': 1,\n 'results': [fake_router_port]\n }\n lrport = self.get_mocked_resource(response=resp_resources)\n\n switch_id = test_constants.FAKE_SWITCH_UUID\n lrport.get_by_lswitch_id(switch_id)\n test_client.assert_json_call(\n 'get', lrport,\n 'https://1.2.3.4/api/v1/logical-router-ports/?'\n 'logical_switch_id=%s' % switch_id,\n headers=self.default_headers())", "def _find(self):\n ports = [port\n for port\n in serial.tools.list_ports.comports()\n if port.device != '/dev/ttyAMA0']\n\n for port in ports:\n try:\n conn = serial.Serial(\n port.device,\n self._baud,\n timeout=DETECT_TIMEOUT\n )\n if Serial._knock(conn):\n conn.close()\n return conn.port\n except:\n continue", "def test_get_logical_router_port_by_switch_id(self):\n fake_router_port = test_constants_v3.FAKE_ROUTER_PORT.copy()\n resp_resources = {\n 'result_count': 1,\n 'results': [fake_router_port]\n }\n\n lrport = self._mocked_lrport(\n session_response=mocks.MockRequestsResponse(\n 200, jsonutils.dumps(resp_resources)))\n\n switch_id = test_constants_v3.FAKE_SWITCH_UUID\n lrport.get_by_lswitch_id(switch_id)\n test_client.assert_json_call(\n 'get', lrport,\n 'https://1.2.3.4/api/v1/logical-router-ports/?'\n 'logical_switch_id=%s' % switch_id)", "def __init__(__self__, *,\n name: pulumi.Input[str],\n parameters: pulumi.Input['ServerPortMatchConditionParametersArgs']):\n pulumi.set(__self__, \"name\", 'ServerPort')\n pulumi.set(__self__, \"parameters\", parameters)", "def listPorts(self):\n ports = glob.glob('/dev/tty[A-Za-z]*')\n print(ports)", "def get_matching_multiplex_port(self,name):\n\n # short circuit: if the attribute name already exists return none\n # if name in self._portnames: return None\n # if not len([p for p in self._portnames if name.startswith(p) and name != p]): return None\n\n matching_multiplex_ports = [self.__getattribute__(p) for p in self._portnames \n if name.startswith(p) \n and name != p \n and hasattr(self, p) \n and self.__getattribute__(p).is_multiplex\n ]\n\n for port in matching_multiplex_ports:\n return port\n\n return None", "def scan_instance(instance):\n scanner = PortScanner()\n scanner.target = instance.public_ip_address\n scanner.start_port = args.start_port[0]\n scanner.end_port = args.end_port[0]\n scanner.threads = args.jobs[0]\n scanner.timeout = args.timeout[0]\n ports = scanner.scan()\n\n if len(ports) > 0:\n for port in ports:\n print(\"\\t\\t\\tPort: \"+str(port['Port'])+\"\\t\"+\"Service: \"+port['Service'])\n else:\n print(\"\\t\\t\\tNo open ports detected\")", "def get_port_by_neutron_tag(cluster, lswitch_uuid, neutron_port_id):\n uri = _build_uri_path(LSWITCHPORT_RESOURCE,\n parent_resource_id=lswitch_uuid,\n fields='uuid',\n filters={'tag': neutron_port_id,\n 'tag_scope': 'q_port_id'})\n LOG.debug(_(\"Looking for port with q_port_id tag '%(neutron_port_id)s' \"\n \"on: '%(lswitch_uuid)s'\"),\n {'neutron_port_id': neutron_port_id,\n 'lswitch_uuid': lswitch_uuid})\n res = do_request(HTTP_GET, uri, cluster=cluster)\n num_results = len(res[\"results\"])\n if num_results >= 1:\n if num_results > 1:\n LOG.warn(_(\"Found '%(num_ports)d' ports with \"\n \"q_port_id tag: '%(neutron_port_id)s'. \"\n \"Only 1 was expected.\"),\n {'num_ports': num_results,\n 'neutron_port_id': neutron_port_id})\n return res[\"results\"][0]", "def get_ports(cli, n):\n used_ports = set()\n\n containers = cli.containers()\n for container in containers:\n for port in container.get('Ports', []):\n used_ports.add(port.get('PublicPort'))\n\n ports = []\n obtained = 0\n for i in range(5000, 10000):\n if i not in used_ports:\n ports.append(i)\n obtained += 1\n\n if obtained == n:\n break\n\n return ports", "def test_ports_scanning():\n host = ipaddress.ip_address(u\"92.222.10.88\")\n scanner = Scanner(host, mock=True)\n\n assert scanner.is_local() is False\n assert scanner.run_ping_test() is True\n\n scanner.perform_scan()\n ports = scanner.extract_ports(\"tcp\")\n\n assert len(ports) >= 3\n for port in ports:\n assert port.__class__ == PortReport\n\n expected_ports = [22, 80, 443]\n port_numbers = [port.port_number for port in ports]\n for expected_port in expected_ports:\n assert expected_port in port_numbers", "def _getNodePortList(ctx):\n return CmdShell().run(\n f'oc get service soos-{ctx.cf.refsys.nws4.sidL}-np'\n + ' -o template --template \"{{range .spec.ports}}{{.name}}:{{.nodePort}},{{end}}\"'\n ).out", "def scan(range: str, ports, timeout, outputformat: str, sockettype: str, rangetype: str, verbose: bool, activeonly: bool):\n loop = asyncio.get_event_loop()\n scanner = FastPortScanner(timeout, verbose)\n if rangetype.upper() == \"CIDR\":\n result = loop.run_until_complete(scanner.loadHostListByCidr(range))\n if not result[0]:\n conditionalClickEcho(verbose, result[1])\n sys.exit(1)\n elif rangetype.upper() == \"RANGE\":\n result = loop.run_until_complete(scanner.loadHostListByRange(range))\n if not result[0]:\n conditionalClickEcho(verbose, result[1])\n sys.exit(1)\n\n result = loop.run_until_complete(scanner.loadPortList(ports))\n if not result[0]:\n conditionalClickEcho(verbose, result[1])\n sys.exit(1)\n\n results = loop.run_until_complete(scanner.gatherResults())\n grouped = groupResults(results, activeonly)\n if(outputformat == \"JSON\"):\n click.echo(json.dumps(grouped))\n elif(outputformat == \"TEXT\"):\n for item in grouped:\n print(item, end = \"; \")\n for port in grouped[item][\"ports\"]:\n if(grouped[item][\"ports\"][port]):\n print(str(port), \"Open\", end = \"; \")\n else:\n print(str(port), \"Closed\", end = \"; \")\n print()", "def __init__(__self__, *,\n name: pulumi.Input[str],\n parameters: pulumi.Input['ClientPortMatchConditionParametersArgs']):\n pulumi.set(__self__, \"name\", 'ClientPort')\n pulumi.set(__self__, \"parameters\", parameters)", "def scan_ports():\n system = platform.system() # Checks the current operating system\n if system == 'Windows': # Windows\n print('Windows system')\n for i in range(256):\n try: \n serial_port = serial.Serial(i)\n serial_port.close()\n yield i\n except serial.SerialException:\n pass\n elif system == 'Linux' or 'Darwin': # Linux or osX\n print('Unix system')\n for port in list_ports.comports():\n yield port[0]" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Executes the simulatePortUpDown operation on the server. Exec to simulate port up and down. simulatePortUpDown(async_operation=bool)bool
def SimulatePortUpDown(self, *args, **kwargs): # type: (*Any, **Any) -> Union[bool, None] payload = {"Arg1": self.href} for i in range(len(args)): payload["Arg%s" % (i + 2)] = args[i] for item in kwargs.items(): payload[item[0]] = item[1] return self._execute( "simulatePortUpDown", payload=payload, response_object=None )
[ "def test_port_up_down_events(self):\n self.mech_driver.set_port_status_up = mock.Mock()\n self.mech_driver.set_port_status_down = mock.Mock()\n with self.port(name='port') as p:\n p = p['port']\n # using the monitor IDL connection to the NB DB, set the\n # Logical_Switch_Port.up to False first. This is to mock the\n # ovn-controller setting it to False when the logical switch\n # port is created.\n with self.nb_idl_transaction(self.fake_api,\n check_error=True) as txn:\n txn.add(cmd.SetLSwitchPortCommand(self.fake_api, p['id'], True,\n up=False))\n\n self._test_port_up_down_helper(p, self.mech_driver)", "def test_non_blocking_asyncio():\n pin1 = machine.Pin(pin_btn01, machine.Pin.IN, machine.Pin.PULL_UP)\n pin2 = machine.Pin(pin_btn02, machine.Pin.IN, machine.Pin.PULL_UP)\n\n loop = asyncio.get_event_loop(runq_len=40, waitq_len=40)\n asyncio.create_task(test_btn(pin1))\n asyncio.create_task(test_btn(pin2))\n asyncio.create_task(ticking_loop())\n loop.run_forever()", "def setup_uplink(rand_selected_dut, tbinfo):\n pytest_require(\"dualtor\" in tbinfo['topo']['name'], \"Only run on dualtor testbed\")\n mg_facts = rand_selected_dut.get_extended_minigraph_facts(tbinfo)\n portchannels = list(mg_facts['minigraph_portchannels'].keys())\n up_portchannel = random.choice(portchannels)\n logger.info(\"Select uplink {} for testing\".format(up_portchannel))\n # Shutdown other uplinks except for the selected one\n for pc in portchannels:\n if pc != up_portchannel:\n cmd = \"config interface shutdown {}\".format(pc)\n rand_selected_dut.shell(cmd)\n # Update the LAG if it has more than one member\n pc_members = mg_facts['minigraph_portchannels'][up_portchannel]['members']\n if len(pc_members) > 1:\n # Update min_links\n min_link_cmd = \"sonic-db-cli CONFIG_DB hset 'PORTCHANNEL|{}' 'min_links' 1\".format(up_portchannel)\n rand_selected_dut.shell(min_link_cmd)\n # Delete to min_links\n cmds = \"config portchannel member del {} {}\".format(up_portchannel, pc_members[len(pc_members) - 1])\n rand_selected_dut.shell_cmds(cmds=cmds)\n # Ensure delete to complete before restarting service\n time.sleep(5)\n # Unmask the service\n rand_selected_dut.shell_cmds(cmds=\"systemctl unmask teamd\")\n # Restart teamd\n rand_selected_dut.shell_cmds(cmds=\"systemctl restart teamd\")\n _wait_portchannel_up(rand_selected_dut, up_portchannel)\n up_member = pc_members[0]\n\n yield mg_facts['minigraph_ptf_indices'][up_member]\n\n # Startup the uplinks that were shutdown\n for pc in portchannels:\n if pc != up_portchannel:\n cmd = \"config interface startup {}\".format(pc)\n rand_selected_dut.shell(cmd)\n # Restore the LAG\n if len(pc_members) > 1:\n cmds = [\n # Update min_links\n \"sonic-db-cli CONFIG_DB hset 'PORTCHANNEL|{}' 'min_links' 2\".format(up_portchannel),\n # Add back portchannel member\n \"config portchannel member add {} {}\".format(up_portchannel, pc_members[1]),\n # Unmask the service\n \"systemctl unmask teamd\",\n # Resart teamd\n \"systemctl restart teamd\"\n ]\n rand_selected_dut.shell_cmds(cmds=cmds)\n _wait_portchannel_up(rand_selected_dut, up_portchannel)", "def test_channel_up_down(self, m):\n self._update_test_mock(m)\n m.register_uri('GET', '/api/remotecontrol?command=402', json=SAMPLE_CHANNEL_CHANGE_RESPONSE, status_code=200)\n m.register_uri('GET', '/api/remotecontrol?command=403', json=SAMPLE_CHANNEL_CHANGE_RESPONSE, status_code=200)\n\n device = enigma2.api.Enigma2Connection(host='123.123.123.123')\n status = device.channel_up()\n self.assertTrue(status)\n status = device.channel_down()\n self.assertTrue(status)", "async def run(self) -> None:\n while self.manager.is_running:\n async for _ in every(UPNP_PORTMAP_DURATION):\n with trio.move_on_after(UPNP_DISCOVER_TIMEOUT_SECONDS) as scope:\n try:\n internal_ip, external_ip = await trio.to_thread.run_sync(\n setup_port_map,\n self.port,\n UPNP_PORTMAP_DURATION,\n )\n event = UPnPMapping(external_ip)\n self.logger.debug(\n \"NAT portmap created, broadcasting UPnPMapping event: %s\", event)\n await self.event_bus.broadcast(event, FIRE_AND_FORGET_BROADCASTING)\n except PortMapFailed as err:\n self.logger.error(\"Failed to setup NAT portmap: %s\", err)\n except Exception:\n self.logger.exception(\"Error setuping NAT portmap\")\n\n if scope.cancelled_caught:\n self.logger.error(\"Timeout attempting to setup UPnP port map\")", "def get_async_monoprice(port_url, loop):\n\n lock = asyncio.Lock()\n\n def locked_coro(coro):\n @asyncio.coroutine\n @wraps(coro)\n def wrapper(*args, **kwargs):\n with (yield from lock):\n return (yield from coro(*args, **kwargs))\n return wrapper\n\n class MonopriceAsync(Monoprice):\n def __init__(self, monoprice_protocol):\n self._protocol = monoprice_protocol\n\n @locked_coro\n @asyncio.coroutine\n def zone_status(self, zone: int):\n # Ignore first 6 bytes as they will contain 3 byte command and 3 bytes of EOL\n string = yield from self._protocol.send(_format_zone_status_request(zone), skip=6)\n return ZoneStatus.from_string(string)\n\n @locked_coro\n @asyncio.coroutine\n def set_power(self, zone: int, power: bool):\n yield from self._protocol.send(_format_set_power(zone, power))\n\n @locked_coro\n @asyncio.coroutine\n def set_mute(self, zone: int, mute: bool):\n yield from self._protocol.send(_format_set_mute(zone, mute))\n\n @locked_coro\n @asyncio.coroutine\n def set_volume(self, zone: int, volume: int):\n yield from self._protocol.send(_format_set_volume(zone, volume))\n\n @locked_coro\n @asyncio.coroutine\n def set_treble(self, zone: int, treble: int):\n yield from self._protocol.send(_format_set_treble(zone, treble))\n\n @locked_coro\n @asyncio.coroutine\n def set_bass(self, zone: int, bass: int):\n yield from self._protocol.send(_format_set_bass(zone, bass))\n\n @locked_coro\n @asyncio.coroutine\n def set_balance(self, zone: int, balance: int):\n yield from self._protocol.send(_format_set_balance(zone, balance))\n\n @locked_coro\n @asyncio.coroutine\n def set_source(self, zone: int, source: int):\n yield from self._protocol.send(_format_set_source(zone, source))\n\n @locked_coro\n @asyncio.coroutine\n def restore_zone(self, status: ZoneStatus):\n yield from self._protocol.send(_format_set_power(status.zone, status.power))\n yield from self._protocol.send(_format_set_mute(status.zone, status.mute))\n yield from self._protocol.send(_format_set_volume(status.zone, status.volume))\n yield from self._protocol.send(_format_set_treble(status.zone, status.treble))\n yield from self._protocol.send(_format_set_bass(status.zone, status.bass))\n yield from self._protocol.send(_format_set_balance(status.zone, status.balance))\n yield from self._protocol.send(_format_set_source(status.zone, status.source))\n\n class MonopriceProtocol(asyncio.Protocol):\n def __init__(self, loop):\n super().__init__()\n self._loop = loop\n self._lock = asyncio.Lock()\n self._transport = None\n self._connected = asyncio.Event(loop=loop)\n self.q = asyncio.Queue(loop=loop)\n\n def connection_made(self, transport):\n self._transport = transport\n self._connected.set()\n _LOGGER.debug('port opened %s', self._transport)\n\n def data_received(self, data):\n asyncio.ensure_future(self.q.put(data), loop=self._loop)\n\n @asyncio.coroutine\n def send(self, request: bytes, skip=0):\n yield from self._connected.wait()\n result = bytearray()\n # Only one transaction at a time\n with (yield from self._lock):\n self._transport.serial.reset_output_buffer()\n self._transport.serial.reset_input_buffer()\n while not self.q.empty():\n self.q.get_nowait()\n self._transport.write(request)\n try:\n while True:\n result += yield from asyncio.wait_for(self.q.get(), TIMEOUT, loop=self._loop)\n if len(result) > skip and result[-LEN_EOL:] == EOL:\n ret = bytes(result)\n _LOGGER.debug('Received \"%s\"', ret)\n return ret.decode('ascii')\n except asyncio.TimeoutError:\n _LOGGER.error(\"Timeout during receiving response for command '%s', received='%s'\", request, result)\n raise\n\n _, protocol = yield from create_serial_connection(loop, functools.partial(MonopriceProtocol, loop),\n port_url, baudrate=9600)\n return MonopriceAsync(protocol)", "async def test_wireup_async(self):\n with patch('iota.commands.extended.is_promotable.IsPromotableCommand.__call__',\n MagicMock(return_value=async_return('You found me!'))\n ) as mocked_command:\n\n api = AsyncIota(self.adapter)\n\n # Don't need to call with proper args here.\n response = await api.is_promotable('tails')\n\n self.assertTrue(mocked_command.called)\n\n self.assertEqual(\n response,\n 'You found me!'\n )", "def set_pp_pullup(self, pullup):\r\n service = uss_service(uss_service.SET_PP_PULLUP)\r\n self._send_message(service, bytearray([pullup]))\r\n data = self._get_message(service)\r\n if not data or (data[0] != 0):\r\n return False\r\n else:\r\n return True", "async def async_update(self):\n if not self.available:\n await self.device.async_connect()", "def setup_mirror_session(rand_selected_dut, setup_uplink):\n session_name = \"dummy_session\"\n cmd = \"config mirror_session add {} 25.192.243.243 20.2.214.125 8 100 1234 0\".format(session_name)\n rand_selected_dut.shell(cmd=cmd)\n uplink_port_id = setup_uplink\n yield uplink_port_id\n\n cmd = \"config mirror_session remove {}\".format(session_name)\n rand_selected_dut.shell(cmd=cmd)", "def test_north_python_service_with_enable_disable(self, setup_local, setup_remote, read_data_from_pi_web_api,\n remote_ip,\n skip_verify_north_interface, fledge_url, wait_time, retries,\n pi_host,\n pi_admin, pi_passwd, pi_db):\n\n # Wait until south and north services are created and some data is loaded\n time.sleep(wait_time)\n\n fledge_url_remote = \"{}:8081\".format(remote_ip)\n\n # Verify on local machine\n verify_ping(fledge_url, skip_verify_north_interface, wait_time, retries)\n verify_asset(fledge_url, local_south_asset_name)\n verify_service_added(fledge_url, local_south_service_name, local_north_service_name)\n verify_statistics_map(fledge_url, local_south_asset_name, local_north_service_name, skip_verify_north_interface)\n verify_asset_tracking_details(fledge_url, local_south_service_name, local_south_asset_name, local_south_plugin,\n local_north_service_name, local_north_plugin, verify_asset_tracking_details)\n\n # Verify on remote machine\n verify_ping(fledge_url_remote, skip_verify_north_interface, wait_time, retries)\n verify_asset(fledge_url_remote, remote_south_asset_name)\n verify_service_added(fledge_url_remote, remote_south_service_name, remote_north_service_name)\n verify_statistics_map(fledge_url_remote, remote_south_asset_name, remote_north_service_name,\n skip_verify_north_interface)\n verify_asset_tracking_details(fledge_url_remote, remote_south_service_name, remote_south_asset_name,\n remote_south_plugin, remote_north_service_name, remote_north_plugin,\n verify_asset_tracking_details)\n\n # Disabling local machine north service\n data = {\"enabled\": \"false\"}\n put_url = \"/fledge/schedule/{}\".format(north_schedule_id)\n resp = utils.put_request(fledge_url, urllib.parse.quote(put_url), data)\n assert False == resp['schedule']['enabled']\n\n # Enabling local machine north service\n data = {\"enabled\": \"true\"}\n put_url = \"/fledge/schedule/{}\".format(north_schedule_id)\n resp = utils.put_request(fledge_url, urllib.parse.quote(put_url), data)\n assert True == resp['schedule']['enabled']\n\n old_ping_result = verify_ping(fledge_url, skip_verify_north_interface, wait_time, retries)\n old_ping_result_remote = verify_ping(fledge_url_remote, skip_verify_north_interface, wait_time, retries)\n # Wait for read and sent readings to increase\n time.sleep(wait_time)\n new_ping_result = verify_ping(fledge_url, skip_verify_north_interface, wait_time, retries)\n new_ping_result_remote = verify_ping(fledge_url_remote, skip_verify_north_interface, wait_time, retries)\n # Verifies whether Read and Sent readings are increasing after restart\n assert old_ping_result['dataRead'] < new_ping_result['dataRead']\n assert old_ping_result_remote['dataRead'] < new_ping_result_remote['dataRead']\n\n if not skip_verify_north_interface:\n assert old_ping_result['dataSent'] < new_ping_result['dataSent']\n assert old_ping_result_remote['dataSent'] < new_ping_result_remote['dataSent']\n _verify_egress(read_data_from_pi_web_api, pi_host, pi_admin, pi_passwd, pi_db, wait_time, retries,\n remote_south_asset_name)", "async def test_nodeport_service_endpoint():\n\n try:\n # Create Deployment\n sh.kubectl.create(\n \"deployment\", \"hello-world\", image=\"gcr.io/google-samples/node-hello:1.0\"\n )\n sh.kubectl.set(\"env\", \"deployment/hello-world\", \"PORT=50000\")\n\n # Create NodePort Service\n sh.kubectl.expose(\n \"deployment\",\n \"hello-world\",\n type=\"NodePort\",\n name=\"hello-world\",\n protocol=\"TCP\",\n port=80,\n target_port=50000,\n )\n\n # Grab the port\n svc = get_svc_yaml()\n port = svc[\"items\"][0][\"spec\"][\"ports\"][0][\"nodePort\"]\n\n # Wait for Pods to stabilize\n await retry_async_with_timeout(is_pod_running, ())\n\n # Grab Pod IP\n pod = get_pod_yaml()\n ip = pod[\"items\"][0][\"status\"][\"hostIP\"]\n\n # Build the url\n set_url = f\"http://{ip}:{port}\"\n html = await asyncify(requests.get)(set_url)\n\n assert \"Hello Kubernetes!\" in html.content.decode()\n\n finally:\n # Cleanup\n sh.kubectl.delete(\"deployment\", \"hello-world\")\n sh.kubectl.delete(\"service\", \"hello-world\")\n await retry_async_with_timeout(is_pod_cleaned, ())", "def test_create_logical_port_admin_down(self):\n fake_port = test_constants_v3.FAKE_PORT\n fake_port['admin_state'] = \"DOWN\"\n\n mocked_resource = self._mocked_lport(\n session_response=mocks.MockRequestsResponse(\n 200, jsonutils.dumps(fake_port)))\n\n result = mocked_resource.create(\n test_constants_v3.FAKE_PORT['logical_switch_id'],\n test_constants_v3.FAKE_PORT['attachment']['id'],\n tags={}, admin_state=False)\n\n self.assertEqual(fake_port, result)", "def test_create_logical_port_admin_down(self):\n fake_port = test_constants.FAKE_PORT\n fake_port['admin_state'] = \"DOWN\"\n mocked_resource = self.get_mocked_resource(response=fake_port)\n\n result = mocked_resource.create(\n test_constants.FAKE_PORT['logical_switch_id'],\n test_constants.FAKE_PORT['attachment']['id'],\n tags={}, admin_state=False)\n\n self.assertEqual(fake_port, result)", "def ResetResonUDP(self, event):\n dlg = ChangePortDialog(self)\n dlg.ShowModal()\n dlg.Destroy()\n if dlg.usevalues:\n reset = sevenpy.com7P(self.ipaddress, self.sonartype, self.ownip)\n reset.command7P('stoprequest',(dlg.dataport, 0))\n reset.closeUDP()\n # print 'Sent request to end UDP data connection on port ' + str(dlg.dataport)", "def press(self, button, wait=0.0, port=0):", "def run(self):\r\n\r\n self.wait_answer(['vagrant', 'up', self.machine])", "async def main(unpacker: Unpacker) -> None:\n LOG.info(\"Starting asynchronous code\")\n await work_loop(unpacker)\n LOG.info(\"Ending asynchronous code\")", "def run():\n board = SimpleGoBoard(7)\n con = GtpConnection(SimulationPlayer(), board)\n con.start_connection()", "def run():\n board = SimpleGoBoard(7)\n con = GtpConnection(SimulationPlayer(10), board)\n con.start_connection()" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Increasing the change probability should be reflected in the probability.
def test_increasing_change_probability(self): initial_probability = self.default_sim.probability('A', 'T', 1.0) sim = GeneralizedReversibleSimulator(frac_a=0.25, frac_c=0.25, frac_g=0.25, a_c=0.25, a_g=0.25, a_t=0.4, c_g=0.25, c_t=0.25, g_t=0.25) self.assertGreater(sim.probability('A', 'T', 1.0), initial_probability)
[ "def mutate_prob(self) -> float:\n return self._mutate_prob", "def uniform_probability(self, args = []):\n\t\tself.probability = 1", "def update_prob(self):\n size = len(self.options)\n\n # Complete the ranking\n improvements = np.array(self.improvements.values())\n totals = np.array(self.count_total.values())\n assert (np.all(totals > 0))\n ratio = improvements / totals + 0.01\n\n total_ratio = float(ratio.sum())\n prob = ratio / total_ratio\n\n self.cumProb = prob.cumsum()", "def modify_rate(rate, change):\n return rate + change * (1 - random.random() * 2)", "def mutate(self, probability, per_gene=False):\n for i in range(0, self.cnf.num_variables):\n if random.uniform(0,1) < (probability[i] if per_gene else probability):\n self.assignments[:,i] = 1-self.assignments[:,i]", "def changeProbability(delta, temperature):\n\n\treturn exp(delta/temperature)", "def get_probability(self, state, observation):\n return 1", "def transition_prob(self, action, nextState):\n nextPossible = self.next_states(action)\n if nextState in nextPossible:\n return 1.0/float(len(nextPossible))\n return 0.0", "def state_probability(self, num_customers):\n raise NotImplementedError()", "def toss_biased(p=GLOBAL_PROB):\n coin = np.random.rand()\n return 1 if coin < p else 0", "def update_prob(self, minimum):\n # Complete the ranking\n if np.any(self.total.values() == 0):\n return\n\n improvements = np.array(\n self.improvements.values()) / self.total.values()\n nonzero = np.nonzero(~np.isnan(improvements))\n\n total = float(improvements[nonzero].sum())\n\n if total == 0:\n return\n\n prob_local = improvements[nonzero] / total\n dim = len(self.improvements)\n prob = np.zeros(dim)\n prob[nonzero] = prob_local\n # add a minimum value\n prob = np.maximum(minimum, prob)\n # Check that it its sum is 1\n total = float(prob.sum())\n prob = prob / total\n\n self.cumProb = prob.cumsum()\n # Init again the list and the count", "def test_increasing_proportion(self):\n for char in ['A', 'C', 'G']:\n params = self.default_params.copy()\n params[self.char_to_frac_param[char]] = 0.4\n other_chars = [c for c in ['A', 'C', 'G'] if c != char]\n for other_char in other_chars:\n params[self.char_to_frac_param[other_char]] = 0.2\n sim = GeneralizedReversibleSimulator(**params)\n initial_probability = self.default_sim.probability(char, char, 1.0)\n self.assertGreater(sim.probability(char, char, 1.0), initial_probability)", "async def test_probability_updates(hass: HomeAssistant) -> None:\n prob_given_true = [0.3, 0.6, 0.8]\n prob_given_false = [0.7, 0.4, 0.2]\n prior = 0.5\n\n for p_t, p_f in zip(prob_given_true, prob_given_false):\n prior = bayesian.update_probability(prior, p_t, p_f)\n\n assert round(abs(0.720000 - prior), 7) == 0\n\n prob_given_true = [0.8, 0.3, 0.9]\n prob_given_false = [0.6, 0.4, 0.2]\n prior = 0.7\n\n for p_t, p_f in zip(prob_given_true, prob_given_false):\n prior = bayesian.update_probability(prior, p_t, p_f)\n\n assert round(abs(0.9130434782608695 - prior), 7) == 0", "def migration_probability(cell):\n return 1", "def log_prob_increment(self):\n return self._log_prob_increment", "def modify_happiness(self, happiness):\n if self.happiness < 0:\n self.happiness = 0\n elif self.happiness < 0:\n self.happiness = 0\n elif self.happiness > 100:\n self.happiness = 100\n else:\n self.happiness += happiness", "async def joseprob(self, ctx, jccount: float, amount: float):\n prob = (1 + (Decimal(jccount) / Decimal(amount))) * Decimal(0.42)\n prob = round(prob, 2)\n await ctx.send(f\"Probability: `{prob}`\")", "def update_probabilities(self):\n ideal_counts = self.item_balanced_view_prob*(1+self.num_running_trips)\n current_portions = self.item_trip_counts / ideal_counts\n # To avoid edge cases 0.999 is used instead of 1.0\n current_portions[current_portions >= 1.0] = 0.999\n self.item_draw_probs = 1.0 - current_portions\n if np.all(self.item_draw_probs == 0.0):\n self.item_draw_probs = np.ones(self.num_items) / self.num_items\n else:\n self.item_draw_probs = self.item_draw_probs/np.sum(self.item_draw_probs)", "def update_probability_log(self, symbol):\n\n # Initialize a value to store the counts of all symbols stored\n total_count = 0\n\n # For each count value, add it to the total_count\n for key, count in self.counts.items():\n total_count += count\n\n # By removing the estimated probability from the current summation\n # It is possible to then change it, and re-add it to the probability\n self.tree.fixed_depth_probabilities[self.level] -= self.estimated_probability\n self.tree.fixed_depth_probabilities_alpha[self.level] -= self.estimated_probability_alpha\n\n # Calculation of the estimated probability with alpha = 0.5\n # Ths is the KT-Estimater as described for standard CTW usage.\n # The '-1' is to account for the fact that the symbol counts have already been incremented\n self.estimated_probability += math.log((self.counts[symbol] - 1 + 0.5)\n / (total_count - 1 + 4*0.5), 2)\n\n # Calculation of the estimated probability (PINHO)\n # This is the same KT-estimater, expect with an alpha of 0.05 instead of 0.5\n self.estimated_probability_alpha += math.log((self.counts[symbol] - 1 + 0.05)\n / (total_count - 1 + 4*0.05), 2)\n\n # Re-adding to the fixed depth proabilities to account for the change\n # These are the probabilities as described in the Pinho paper\n self.tree.fixed_depth_probabilities[self.level] += self.estimated_probability\n self.tree.fixed_depth_probabilities_alpha[self.level] += self.estimated_probability_alpha\n\n # stores the probability of the children to this node\n children_prob = 0\n\n # Begin by going through all of the weighted probabilities\n # These are the probabilities as described for CTW\n for key,value in self.weighted_probabilities.items():\n # If the level of the weighted probability of is the same as the level of the node:\n # only return the estimated value.\n # For example when calculating for a max depth of 8, the Pw of nodes at depth 8 is\n # only the estimated probability.\n if key is self.level:\n # If the level is greater than 11\n if key > 11:\n # If the tree is supposed to use the 0.05 alpha value\n # then store the 0.05 value\n if self.tree.alpha:\n self.weighted_probabilities[key] = self.estimated_probability_alpha\n else:\n self.weighted_probabilities[key] = self.estimated_probability\n else:\n # below 12, nominal estimated probability\n self.weighted_probabilities[key] = self.estimated_probability\n else:\n # So now we know that the children to this node should be taken into consideration\n # when calculating the weighted probability of this node\n\n # Stores the weighted probability of the children such that it can be used\n # to update the weighted probability at this node\n child_weight = 0\n\n # Begins by looping through all the children of this node\n for child_key, child in self.children.items():\n # Check to see if the child exists\n if child is not None:\n # If it exist, add to child_weight\n child_weight += child.weighted_probabilities[key]\n if key > 11:\n # check to see if it is needed to use the 0.05 alpha value\n if self.tree.alpha:\n self.weighted_probabilities[key] = add_logs(child_weight, self.estimated_probability_alpha) + math.log(1 / 2, 2)\n else:\n self.weighted_probabilities[key] = add_logs(child_weight, self.estimated_probability) + math.log(1 / 2, 2)\n else:\n # NOTE: the math.log(1/2,2) is equivalent to dividing the resulting sum by 2\n # since pw = (pe + pw_children)/2 the division by 2 is necessary\n self.weighted_probabilities[key] = add_logs(child_weight, self.estimated_probability) + math.log(1 / 2, 2)\n\n # This portion of code is used to update the singular\n # weighted probability, this was used before an update was made to consider\n # weighted probabilities of different levels\n # These values are not used but is a hold over from a previous\n # version of the implementation\n\n # First check to see if the depth is equal to level\n # Will affect the value used in the weighted prob.\n if self.level is not self.tree.depth:\n # Loop through all the children\n for key, child in self.children.items():\n # if the child exists..\n if child is not None:\n # add to child prob\n children_prob += child.weighted_probability\n # Once all children have been added\n # log(1/2,2) is equivalent to multiplying it all 1/2\n self.weighted_probability = (\n children_prob\n + math.log(1 + pow(2, (self.estimated_probability - children_prob)), 2)\n + math.log(1 / 2, 2))\n else:\n # If at the max-depth only use the estimated prob.\n # because there are no children available.\n self.weighted_probability = self.estimated_probability" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Increasing the proportion of a character should be reflected in the probability.
def test_increasing_proportion(self): for char in ['A', 'C', 'G']: params = self.default_params.copy() params[self.char_to_frac_param[char]] = 0.4 other_chars = [c for c in ['A', 'C', 'G'] if c != char] for other_char in other_chars: params[self.char_to_frac_param[other_char]] = 0.2 sim = GeneralizedReversibleSimulator(**params) initial_probability = self.default_sim.probability(char, char, 1.0) self.assertGreater(sim.probability(char, char, 1.0), initial_probability)
[ "def mutate_prob(self) -> float:\n return self._mutate_prob", "async def joseprob(self, ctx, jccount: float, amount: float):\n prob = (1 + (Decimal(jccount) / Decimal(amount))) * Decimal(0.42)\n prob = round(prob, 2)\n await ctx.send(f\"Probability: `{prob}`\")", "def probability(self, total):\n return self.count / total", "def update_prob(self):\n size = len(self.options)\n\n # Complete the ranking\n improvements = np.array(self.improvements.values())\n totals = np.array(self.count_total.values())\n assert (np.all(totals > 0))\n ratio = improvements / totals + 0.01\n\n total_ratio = float(ratio.sum())\n prob = ratio / total_ratio\n\n self.cumProb = prob.cumsum()", "def _calculateAttributeProbability(self, attr_count):\n numerator = attr_count + 1\n denominator = self.total_class_count + self.total_attributes\n return numerator / denominator", "def probability(self):\n totale=self.count_class()[2]\n return (self.count_class()[0]/totale) , (self.count_class()[1]/totale)", "def test_probability_sums_to_1(self, sim, char, distance):\n assume(distance > 0)\n total_probability = sim.probability(char, 'A', distance) + sim.probability(char, 'C', distance) + sim.probability(char, 'G', distance) + sim.probability(char, 'T', distance)\n self.assertAlmostEqual(total_probability, 1.0)", "def update_probabilities(self):\n ideal_counts = self.item_balanced_view_prob*(1+self.num_running_trips)\n current_portions = self.item_trip_counts / ideal_counts\n # To avoid edge cases 0.999 is used instead of 1.0\n current_portions[current_portions >= 1.0] = 0.999\n self.item_draw_probs = 1.0 - current_portions\n if np.all(self.item_draw_probs == 0.0):\n self.item_draw_probs = np.ones(self.num_items) / self.num_items\n else:\n self.item_draw_probs = self.item_draw_probs/np.sum(self.item_draw_probs)", "def probability_points(pt_margin: float) -> float:\n return probability(25 * pt_margin)", "async def coinprob(self, ctx, person: discord.User=None):\n if not person:\n person = ctx.author\n\n data = await self.jc_get(f'/wallets/{person.id}/probability')\n p = float(data['probability'])\n await ctx.send(f'You have a {p * 100}%/message chance')", "def get_pct_caps( msg ):\n num_caps = get_num_caps( msg )\n return float( num_caps ) / len( msg )", "def test_probs(self):\n u = self.abUsage([1,3])\n self.assertEqual(u.probs(), self.abUsage([0.25,0.75]))", "def division_probability(cell):\n return 1", "def prob(substring, profile):\n prob = 1\n for i in range (0, len(substring)):\n char_index = char_to_index(substring[i])\n prob *= profile[char_index][i]\n return prob", "def addToSetWithProbability(self, word):\n # If p is greater than the random number drawn from a uniform distribution\n if random.uniform(0, 1) < self.probability: \n self.setOfWords.add(word)", "def Probability(self, word):\n voc_len = Document._vocabulary.len()\n SumN = 0\n for i in range(voc_len):\n SumN = DocumentClass._vocabulary.WordFreq(word)\n N = self._words_and_freq.WordFreq(word)\n erg = 1 + N\n erg /= voc_len + SumN\n return erg", "def uniform_probability(self, args = []):\n\t\tself.probability = 1", "def string_prob(string, GC_content):\n\n s = string.upper()\n\n p_gc = GC_content / 2\n p_at = (1 - GC_content) / 2\n\n p = p_at ** (s.count('A') + s.count('T'))\n p *= p_gc ** (s.count('G') + s.count('C'))\n\n return p", "def get_probability(self, state, observation):\n return 1" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that the probability from a character to all characters sums to 1.0.
def test_probability_sums_to_1(self, sim, char, distance): assume(distance > 0) total_probability = sim.probability(char, 'A', distance) + sim.probability(char, 'C', distance) + sim.probability(char, 'G', distance) + sim.probability(char, 'T', distance) self.assertAlmostEqual(total_probability, 1.0)
[ "def test_increasing_proportion(self):\n for char in ['A', 'C', 'G']:\n params = self.default_params.copy()\n params[self.char_to_frac_param[char]] = 0.4\n other_chars = [c for c in ['A', 'C', 'G'] if c != char]\n for other_char in other_chars:\n params[self.char_to_frac_param[other_char]] = 0.2\n sim = GeneralizedReversibleSimulator(**params)\n initial_probability = self.default_sim.probability(char, char, 1.0)\n self.assertGreater(sim.probability(char, char, 1.0), initial_probability)", "def string_prob(string, GC_content):\n\n s = string.upper()\n\n p_gc = GC_content / 2\n p_at = (1 - GC_content) / 2\n\n p = p_at ** (s.count('A') + s.count('T'))\n p *= p_gc ** (s.count('G') + s.count('C'))\n\n return p", "def prob(substring, profile):\n prob = 1\n for i in range (0, len(substring)):\n char_index = char_to_index(substring[i])\n prob *= profile[char_index][i]\n return prob", "def probability(self):\r\n batcoins = arrayofcoins(1000) #code can be messed with to make a custom value for x in arrayofcoins(x), but theoretical probability calculation must also be changed\r\n for m in range(0,self.trials):\r\n if batcoins.successnumber() == 1:\r\n self.successruns = self.successruns + 1\r\n return float(self.successruns) / self.trials", "def character_frequency(input_str):\n expected_character_frequency = {\n 'a': 8.167,\n 'b': 1.492,\n 'c': 2.782,\n 'd': 4.253,\n 'e': 12.702,\n 'f': 2.228,\n 'g': 2.015,\n 'h': 6.094,\n 'i': 6.966,\n 'j': 0.153,\n 'k': 0.772,\n 'l': 4.025,\n 'm': 2.406,\n 'n': 6.749,\n 'o': 7.507,\n 'p': 1.929,\n 'q': 0.095,\n 'r': 5.987,\n 's': 6.327,\n 't': 9.056,\n 'u': 2.758,\n 'v': 0.978,\n 'w': 2.360,\n 'x': 0.150,\n 'y': 1.974,\n 'z': 0.074,\n # FIXME for challenge 4 I've had to fudge this list by including the\n # below space character in order to ensure the score alg chose the\n # correct sentance. The current value (5.00) is probably a tad high.\n ' ': 5.00\n }\n occurance_count = {char: 0 for char in string.ascii_lowercase+' '}\n ignored = 0\n for character in input_str:\n if character in string.ascii_letters + ' ':\n occurance_count[character.lower()] += 1\n else:\n ignored += 1\n\n chi_squared = 0\n length_of_input = len(input_str)\n if ignored == length_of_input:\n return 0\n for char, occurance in occurance_count.items():\n expected = (\n float(length_of_input - ignored)\n * expected_character_frequency[char]\n )\n if not expected:\n # Sometimes the expected value is zero.\n print((\n length_of_input,\n ignored,\n expected_character_frequency[char]\n ))\n continue\n difference = occurance - expected\n chi_squared += difference * difference / expected\n return chi_squared", "def ascii_percentage(string):\n count = 0\n for char in string:\n if ord(char)<128:\n count += 1\n if len(string) == 0:\n return 1\n else:\n return float(count)/len(string)", "def ratio_repeated_character_testing(self):\n domain = self.hostname\n psl = PublicSuffixList()\n psl.accept_unknown = False\n if domain is None:\n domain = \"\"\n else:\n try:\n domain = domain[:len(domain) - (len(psl.publicsuffix(domain)) + 1)]\n except TypeError:\n pass\n\n domain.replace(\".\", \"\")\n card = sum(list(map(lambda x: 1 if x.isalpha() else 0, domain)))\n if card in [None, 0, \"error\"] or type(card) is not int:\n self.ratioRepeatedCharacterWeight = 1\n return\n\n setDomain = list(set(domain))\n countRepeated = 0\n\n for character in setDomain:\n if domain.count(character) > 1:\n countRepeated += 1\n\n if countRepeated / card > 0.17:\n self.ratioRepeatedCharacterWeight = 1\n return\n self.ratioRepeatedCharacterWeight = 0", "def score_distribution(text):\n # calculate distribution\n counts = dict((letter, 0) for letter in lowercase)\n total_count = 0\n for char in text:\n if char in counts:\n counts[char] += 1\n total_count += 1\n\n # Sum squared errors\n error = 0\n for letter in lowercase:\n freq = float(counts[letter]) / total_count\n error += (freq - LETTER_FREQUENCIES[letter])**2\n\n return error", "def chi_squared(s: str) -> float:\n assert s\n\n c = char_distribution(s)\n # Counter[NOT_IN_COUNTER] = 0, useful! :)\n\n e = {\n k: v * float(len(s))\n for k, v\n in english_frequencies.items()\n }\n\n return sum(\n math.pow(c[k] - e[k], 2) / e[k]\n for k in e\n ) + sum( # Penalize non-alpha ascii chars\n math.pow(c[k], 4) for k in set(c.keys()) - set(e.keys()) - {' '}\n )", "def test_probs(self):\n u = self.abUsage([1,3])\n self.assertEqual(u.probs(), self.abUsage([0.25,0.75]))", "def general_analysis(ciphertext):\n print('Total length of ciphertext:', len(ciphertext))\n print('Unique letters:',len(find_letter_distribution(ciphertext)))", "def calculateCost(given_text, actual_text):\n total_correct = 0\n\n for bit in range(len(given_text)):\n if given_text[bit] == actual_text[bit]:\n total_correct += 1\n\n return int((float(total_correct)/len(given_text))*100)", "def log_probability(self, text):\n\t\tdef _access_values(key):\n\t\t\t\"\"\"\n\t\t\t_access_values(key)\n\t\t\tA helper closure to allow for a try except inside a list comp for\n\t\t\tthe total log prob calculation. If the table is a dict, then it \n\t\t\twill throw keyerrors if the key isn't found which for our purposes\n\t\t\tis a 0. \n\n\t\t\tGets: key, a string of length k or k+1\n\t\t\tReturns: an int\n\t\t\t\"\"\"\n\t\t\ttry:\n\t\t\t\treturn self.table[key]\n\t\t\texcept KeyError:\n\t\t\t\treturn 0\n\t\tk_k1_len_substrings = [(text[i-1:i+self.k-1], text[i-1:i+self.k]) for i in range(len(text)) if i+self.k-1 < len(text)][1:]\n\t\tk_k1_len_substrings.append((text[-self.k:], text[-self.k:]+text[0]))\n\t\tif self.k > 1:\n\t\t\tfor char_index, char in enumerate(text[-self.k+1:]):\n\t\t\t\tk_k1_len_substrings.append((text[-self.k +1 + char_index:]+text[:char_index+1], text[-self.k +1 + char_index:]+text[:char_index+2]))\n\t\ttotal_log_prob = sum([log((_access_values(str_tuple[1])+1) / (_access_values(str_tuple[0])+self.alphabet_len)) for str_tuple in k_k1_len_substrings])\n\t\treturn total_log_prob", "def test_probability_by_state_sequence(self):\n observations = [0,1,1]\n probabilities = Algs.analysis_of_state_sequences(self.model3, observations)\n total_probability = sum(prob for sequence, prob in probabilities)\n self.assertAlmostEquals(total_probability,\n Algs.probability_of_observations(self.model3, observations))", "def get_chi_square_value(text):\n\n # Values if ignoring non-alphabetic characters and spaces is desired\n # behavior.\n alpha_freq = [\n 0.0651738, 0.0124248, 0.0217339, 0.0349835, 0.1041442, 0.0197881, 0.0158610,\n 0.0492888, 0.0558094, 0.0009033, 0.0050529, 0.0331490, 0.0202124, 0.0564513,\n 0.0596302, 0.0137645, 0.0008606, 0.0497563, 0.0515760, 0.0729357, 0.0225134,\n 0.0082903, 0.0171272, 0.0013692, 0.0145984, 0.0007836]\n space_freq = 0.1918182\n unexpected_freq = 0.0001 # decided by client\n\n # Values if you don't want to ignore other non-alphabetic letters\n # and spaces.\n #\n # alpha_freq = [ \n # 0.0609, 0.0105, 0.0284, 0.0292, 0.1136, 0.0179, 0.0138,\n # 0.0341, 0.0544, 0.0024, 0.0041, 0.0292, 0.0276, 0.0544, \n # 0.0600, 0.0195, 0.0024, 0.0495, 0.0568, 0.0803, 0.0243, \n # 0.0097, 0.0138, 0.0024, 0.0130, 0.0003]\n # space_freq = 0.1217\n # other_freq = 0.0657\n\n counts = [0] * 28 # First 26 spots for alphas, 27 for spaces, 28 for other\n length = len(text)\n\n for i in range(length):\n c = text[i]\n if is_byte_lowercase_letter(c):\n index = c - ord('a')\n counts[index] = counts[index] + 1\n elif is_byte_uppercase_letter(c):\n index = c - ord('A')\n counts[index] = counts[index] + 1\n elif c == ord(' '):\n counts[26] = counts[26] + 1\n else:\n counts[27] = counts[27] + 1\n\n # Compute the chi square statistic of the letters and return it.\n res = 0\n for i in range(len(alpha_freq)):\n expected = length * alpha_freq[i]\n res = res + ((counts[i] - expected) ** 2) / expected\n\n expected = length * space_freq\n res = res + ((counts[26] - expected) ** 2) / expected\n\n expected = length * unexpected_freq\n res = res + ((counts[27] - expected) ** 2) / expected\n return res", "def score_char(m):\n def lnPc(c):\n if c not in printset: return min(freq.values()) - math.log(1000000)\n return freq.get(c.lower(), min(freq.values()) - math.log(1000))\n return sum(lnPc(c) for c in m)", "def phredprob(Qchar):\n phredscore = ord(Qchar)-33\n return pow(10,-float(phredscore)/10)", "def score_probability(statement):\n # Set key Words\n key_words = ['age', 'year', 'born', 'date of birth'] \n\n # Zero word counts\n words_total = 0\n occurences = 0 \n\n # You could also just set words_total as:\n # words_total = len(statement) \n\n # Iterate over elements in statement\n for word in statement:\n words_total += 1 # incerement total words\n if word in key_words: # check if word in key_words\n occurences += 1 # if so, increment occurences\n return (occurences / words_total) > 0.7 # return true if 70% of all words are key_words", "def getAlphaRatio(word):\n\tlength = len(word)\n\talpha = 0.0\n\tfor letter in word:\n\t\tif letter.isalpha():\n\t\t\talpha += 1.0\n\t#print \"ALPHA\", word, alpha/length\n\treturn alpha/length" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Represent data in DAS plain view for queries with filters.
def plainview(self, head, data): dasquery = head['dasquery'] fields = dasquery.mongo_query.get('fields', []) filters = dasquery.filters results = "" status = head.get('status', None) if status == 'fail': reason = head.get('reason', '') if reason: results += 'ERROR: %s' % reason for row in data: if filters: for flt in filters: if flt.find('=') != -1 or flt.find('>') != -1 or \ flt.find('<') != -1: continue try: for obj in DotDict(row).get_values(flt): results += str(obj) + '\n' except: pass results += '\n' else: for item in fields: try: mapkey = '%s.name' % item key, att = mapkey.split('.') if key in row: val = row[key] if isinstance(val, dict): results += val.get(att, '') elif isinstance(val, list): for item in val: results += item.get(att, '') results += '\n' except: pass results += '\n' return results
[ "def show(self, **kwargs):\n if _is_dataframe(self.encrypt):\n viz_data = self.encrypt\n\n elif _is_dataframe(self.redact):\n viz_data = self.redact\n\n elif self.infotypes:\n viz_data = self.infotypes\n\n return viz_data", "def show(table,**kwargs):\n\n date_column_name = kwargs.get('date_column_name', 'date')\n date_range = kwargs.get('date_range', None)\n date_format = kwargs.get('date_format', 'yyyy-mm-dd')\n\n slices = kwargs.get('slices', None)\n\n summary_operator = kwargs.get('summary_operator', None)\n\n metric = kwargs.get('metric',None)\n\n dimensions = kwargs.get('dimensions',None)\n\n table = aspects.apply_date_range(table, date_range, date_column_name, date_format)\n\n table = aspects.slice_table(table, slices)\n\n # collecting the colums not to be removed\n required_columns = []\n if dimensions is not None:\n \trequired_columns = dimensions.copy()\n # metric is optional in show\t\n if metric is not None:\n required_columns.append(metric)\n\n table = aspects.crop_other_columns(table, required_columns)\n\n # When there is no dimension to group by but a summary_operator exists ,\n # we assume that user wants to apply the summary operator on whole data\n if( (dimensions is None) and (summary_operator is not None) ):\n # We add temporary column of 'Summary Operator' by which we can groupby\n # to obtain the final result\n _add_temporary_column_of_summary_operator(table, summary_operator)\n\n dimensions = []\n\n # To groupby 'Summary Operator' column inserted\n dimensions.append('Summary Operator')\n\n table = aspects.group_by(table, dimensions, summary_operator)\n\n return table", "def run(self):\n # count before filtering\n self.cardinality = self.query.count()\n\n # the term entered in the datatable's search box\n self.filtering()\n\n # field chosen to sort on\n self.sorting()\n\n # pages have a 'start' and 'length' attributes\n self.paging()\n\n # fetch the result of the queries\n self.results = self.query.all()\n\n # return formatted results with correct filters applied\n formatted_results = []\n for i in range(len(self.results)):\n row = dict()\n for j in range(len(self.columns)):\n col = self.columns[j]\n if col.filter:\n if col.filterarg == 'cell':\n tmp_row = get_attr(self.results[i], col.column_name)\n if sys.version_info < (3, 0) \\\n and hasattr(tmp_row, 'encode'):\n tmp_row = tmp_row.encode('utf-8')\n tmp_row = col.filter(tmp_row)\n elif col.filterarg == 'row':\n tmp_row = col.filter(self.results[i])\n else:\n raise InvalidParameter(\n \"invalid filterarg %s for \\ column_name %s: \\\n filterarg must be 'row' or 'cell'\"\n % col.filterarg, col.column_name)\n else:\n tmp_row = get_attr(self.results[i], col.column_name)\n row[col.mData if col.mData else str(j)] = tmp_row\n formatted_results.append(row)\n\n self.results = formatted_results", "def _create_query_data(self):\n # TODO support composite data type properties\n # TODO support enum value\n return {\n \"data\": {\n \"name\": self.name,\n \"schema\": self.schema,\n \"typtype\": self.typtype,\n \"collname\": self.collname,\n \"opcname\": self.opcname,\n \"rngcanonical\": self.rngcanonical,\n \"rngsubdiff\": self.rngsubdiff,\n \"description\": self.description,\n \"composite\": self.composite\n }\n }", "def display_filters():\n states = storage.all(\"State\").values()\n amenities = storage.all(\"Amenity\").values()\n return(render_template('10-hbnb_filters.html', states=states,\n amenity=amenities))", "def create_filterable_data_set():\n\n source = CalculationSource('Dummy', {})\n carbon_substance = create_dummy_substance(number_of_components=1, elements=['C'])\n\n density_property = Density(thermodynamic_state=ThermodynamicState(temperature=298 * unit.kelvin,\n pressure=0.5 * unit.atmosphere),\n phase=PropertyPhase.Liquid,\n substance=carbon_substance,\n value=1 * unit.gram / unit.milliliter,\n uncertainty=0.11 * unit.gram / unit.milliliter,\n source=source)\n\n nitrogen_substance = create_dummy_substance(number_of_components=2, elements=['N'])\n\n dielectric_property = DielectricConstant(thermodynamic_state=ThermodynamicState(temperature=288 * unit.kelvin,\n pressure=1 * unit.atmosphere),\n phase=PropertyPhase.Gas,\n substance=nitrogen_substance,\n value=1 * unit.dimensionless,\n uncertainty=0.11 * unit.dimensionless,\n source=source)\n\n oxygen_substance = create_dummy_substance(number_of_components=3, elements=['O'])\n\n enthalpy_property = EnthalpyOfMixing(thermodynamic_state=ThermodynamicState(temperature=308 * unit.kelvin,\n pressure=1.5 * unit.atmosphere),\n phase=PropertyPhase.Solid,\n substance=oxygen_substance,\n value=1 * unit.kilojoules / unit.mole,\n uncertainty=0.11 * unit.kilojoules / unit.mole,\n source=source)\n\n data_set = PhysicalPropertyDataSet()\n data_set.properties[carbon_substance.identifier] = [density_property]\n data_set.properties[nitrogen_substance.identifier] = [dielectric_property]\n data_set.properties[oxygen_substance.identifier] = [enthalpy_property]\n\n return data_set", "def query_result() -> Any:\n query = request.args.get(\"query_string\", \"\")\n table = get_template_attribute(\"_query_table.html\", \"querytable\")\n contents, types, rows = g.ledger.query_shell.execute_query(query)\n if contents:\n if \"ERROR\" in contents:\n raise FavaAPIException(contents)\n table = table(g.ledger, contents, types, rows)\n\n if types and g.ledger.charts.can_plot_query(types):\n return {\n \"chart\": g.ledger.charts.query(types, rows),\n \"table\": table,\n }\n return {\"table\": table}", "def create_filterable_data_set():\n\n source = CalculationSource(\"Dummy\", {})\n carbon_substance = create_dummy_substance(number_of_components=1, elements=[\"C\"])\n\n density_property = Density(\n thermodynamic_state=ThermodynamicState(\n temperature=298 * unit.kelvin, pressure=0.5 * unit.atmosphere\n ),\n phase=PropertyPhase.Liquid,\n substance=carbon_substance,\n value=1 * unit.gram / unit.milliliter,\n uncertainty=0.11 * unit.gram / unit.milliliter,\n source=source,\n )\n\n nitrogen_substance = create_dummy_substance(number_of_components=2, elements=[\"N\"])\n\n dielectric_property = DielectricConstant(\n thermodynamic_state=ThermodynamicState(\n temperature=288 * unit.kelvin, pressure=1 * unit.atmosphere\n ),\n phase=PropertyPhase.Gas,\n substance=nitrogen_substance,\n value=1 * unit.dimensionless,\n uncertainty=0.11 * unit.dimensionless,\n source=source,\n )\n\n oxygen_substance = create_dummy_substance(number_of_components=3, elements=[\"O\"])\n\n enthalpy_property = EnthalpyOfMixing(\n thermodynamic_state=ThermodynamicState(\n temperature=308 * unit.kelvin, pressure=1.5 * unit.atmosphere\n ),\n phase=PropertyPhase.Solid,\n substance=oxygen_substance,\n value=1 * unit.kilojoules / unit.mole,\n uncertainty=0.11 * unit.kilojoules / unit.mole,\n source=source,\n )\n\n data_set = PhysicalPropertyDataSet()\n data_set.add_properties(density_property, dielectric_property, enthalpy_property)\n\n return data_set", "def display_query(query, index): # pragma: no cover\n QueryPlot(query, index)", "def show(table,**kwargs):\n\n date_column_name = kwargs.get('date_column_name', 'date')\n date_range = kwargs.get('date_range', None)\n day_first = kwargs.get('day_first', False)\n\n slices = kwargs.get('slices', None)\n\n summary_operator = kwargs.get('summary_operator', None)\n\n metric = kwargs.get('metric',None)\n\n dimensions = kwargs.get('dimensions',None)\n\n table = aspects.apply_date_range(table, date_range, date_column_name, day_first)\n\n table = aspects.slice_table(table, slices)\n\n # collecting the colums not to be removed\n required_columns = []\n if dimensions is not None:\n required_columns = dimensions.copy()\n # metric is optional in show \n if metric is not None:\n required_columns.append(metric)\n\n table = aspects.crop_other_columns(table, required_columns)\n\n # When there is no dimension to group by but a summary_operator exists ,\n # we assume that user wants to apply the summary operator on whole data\n if( (dimensions is None) and (summary_operator is not None) ):\n # We add temporary column of 'Summary Operator' by which we can groupby\n # to obtain the final result\n _add_temporary_column_of_summary_operator(table, summary_operator)\n\n dimensions = []\n\n # To groupby 'Summary Operator' column inserted\n dimensions.append('Summary Operator')\n\n after_group_by = aspects.group_by(table, dimensions, summary_operator)\n \n table = after_group_by['table']\n\n suggestions = []\n\n if len(after_group_by['suggestions']) > 0:\n suggestions.extend(after_group_by['suggestions'])\n\n # Droping the 'Summary Operator' column which was inserted above\n table = table.drop(columns=['Summary Operator'])\n \n table = aspects.update_metric_column_name(table, summary_operator, metric)\n \n return (table, suggestions)\n \n after_group_by = aspects.group_by(table, dimensions, summary_operator)\n\n table = after_group_by['table']\n\n suggestions = []\n\n different_weight_suggestion = weighted_mean_with_different_weights.\\\n weighted_mean_with_different_weights(table, metric)\n\n if different_weight_suggestion is not None:\n suggestions.append(different_weight_suggestion)\n\n if len(after_group_by['suggestions']) > 0:\n suggestions.extend(after_group_by['suggestions'])\n\n order = oversights_order.ORDER_IN_SHOW\n suggestions = rank_oversights.rank_oversights(suggestions, order)\n\n if summary_operator is not None:\n table = aspects.update_metric_column_name(table, summary_operator, metric)\n\n return (table , suggestions)\n\n order = oversights_order.ORDER_IN_SHOW\n suggestions = rank_oversights.rank_oversights(suggestions, order)\n\n return (table , suggestions)", "def views(self):\n yield self.sql_create_view", "def get_datatables_object(self) -> object:\n return {\"name\": self.mongo_name, \"filter\": self.get_filter()}", "def viz(self):\n return (self.header(), self.data)", "def display(ctx, name, address, phone):\n\n click.echo(ctx.obj['RECORDS'].filter_records(name, address, phone).display())", "def query():\n return render_template(\"dashboard/query.html\", tagname = 'query', form = QueryForm())", "def list_filters(self):\n\n def _row_gen(attributes):\n for attr in attributes.values():\n yield (attr.name, attr.type, attr.description)\n\n return pd.DataFrame.from_records(\n _row_gen(self.filters), columns=['name', 'type', 'description'])", "def sample_custom_query_5():\n return pd.DataFrame({'X': ['d'], 'Numerical': [25]})", "def dataframe(self) -> pd.DataFrame:\n data = []\n columns = [\"lection\", 'season', 'week', 'day']\n for lection_membership in self.lections_in_system():\n if type(lection_membership.day) != MovableDay:\n raise NotImplementedError(f\"Cannot yet export for days of type {type(lection_membership.day)}.\")\n data.append(\n [\n lection_membership.lection.description, \n lection_membership.day.get_season_display(), \n lection_membership.day.week, \n lection_membership.day.get_day_of_week_display(), \n ]\n )\n df = pd.DataFrame(data, columns=columns)\n return df", "def _filter_view(self, map_body):\n if map_body is True:\n map_body = \"function(doc) { emit(doc._id, null); };\"\n assert isinstance(map_body, str), \"View map must be a string\"\n view_doc = \"%s_viewdoc\" % self.prefix\n view_name = \"%s_viewname\" % self.prefix\n ddoc = {\"_id\": \"_design/%s\" % view_doc, \"views\": {view_name: {\"map\": map_body}}}\n rep_params = {\n \"filter\": \"_view\",\n \"query_params\": {\"view\": \"%s/%s\" % (view_doc, view_name)},\n }\n return (ddoc, rep_params)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converti une phrase de texte en son
def convertir(phrase): global indice phrase_convertie = [] while indice < len(phrase): if debug: print("[{}] '{}' -> ".format(indice,phrase[indice]),end="") son,increment = transcrire(indice) phrase_convertie.append(son) if debug: print("'{}' +{}".format(son,increment)) indice += increment return "".join(phrase_convertie)
[ "def convert_word(self,word,font='preeti'):\n converted = word\n if font == 'preeti':\n converted = self.convert_preeti(word)\n return converted", "def translation(text):\n\tinput_text = TextBlob(text)\n\tclick.secho(\"Text Translation\",fg='black',bg='white')\n\tclick.secho(\"Original Text: {}\".format(text),fg='yellow')\n\tclick.secho(\"Translated Text {}\".format(input_text.translate(to='en')),fg='green')", "def convert_text(self, text, to):\n retval = ''\n if to == 'rich':\n self.progress_text.set_contents(text)\n retval = str(self.progress_text.get_contents())\n elif to == 'plain':\n retval = text # self.progress_text.GetValue()\n return retval", "def process_text(trove_key, article_id):\n data = troveAPI.trove_api_get(trove_key, article_id)\n text = data['article']['articleText']\n processed_text = pre_process(text)\n return processed_text", "def replace_foreign_phrase(text, dic=load_dic()):\n # matches 15 words or quotation in front of the parantheses\n regex = re.compile(\"((?:(\\w+\\s+|\\w+')){1,15}\\(((d|D)eutsch:|zu (d|D)eutsch).*?\\)|\\\"([^\\\"]*)\\\" \\(((d|D)eutsch:|zu (d|D)eutsch):.*?\\))\")\n original_and_translation = regex.search(remove_nonlatin(text))\n \n if original_and_translation != None:\n original = re.search(\"^.*?\\(\", original_and_translation.group()).group()[:-1]\n \n if re.search(\"\\\"([^\\\"]*)\\\"\", original) == None:\n original = find_foreign_phrase(original, dic)\n \n paranthesis = re.search(\"\\(((d|D)eutsch:|zu (d|D)eutsch).*?\\)\", original_and_translation.group())\n if paranthesis != None:\n translation = re.sub(\"\\(((d|D)eutsch:|zu (d|D)eutsch). |\\)\", \"\", paranthesis.group())\n \n return text[:text.find(original)] + translation + text[text.find(paranthesis.group()) + len(paranthesis.group()):]\n else:\n return text", "def _visit_translation(self, s):\r\n return s", "def apertium_translate(phenny, input):\n line = input.group(2)\n if not line:\n raise GrumbleError(\"Need something to translate!\")\n #line = line.encode('utf-8')\n\n pairs = []\n guidelines = line.split('|')\n if len(guidelines) > 1:\n for guideline in guidelines[1:]:\n #phenny.say(guideline)\n pairs.append(guideline.strip().split('-'))\n guidelines = guidelines[0]\n #phenny.say(\"guidelines: \"+str(guidelines))\n stuff = re.search('(.*) ([a-z]+-[a-z]+)', guidelines)\n #phenny.say('groups: '+str(stuff.groups()))\n pairs.insert(0, stuff.group(2).split('-'))\n translate_me = stuff.group(1)\n #phenny.say(str(pairs))\n\n #output_lang = line.split(' ')[-1]\n #input_lang = line.split(' ')[-2]\n #translate_me = ' '.join(line.split(' ')[:-2])\n\n if (len(translate_me) > 350) and (not input.admin): \n raise GrumbleError('Phrase must be under 350 characters.')\n\n msg = translate_me\n finalmsg = False\n translated = \"\"\n for (input_lang, output_lang) in pairs:\n if input_lang == output_lang: \n raise GrumbleError('Stop trying to confuse me! Pick different languages ;)')\n msg = translate(msg, input_lang, output_lang)\n if not msg:\n raise GrumbleError('The %s to %s translation failed, sorry!' % (input_lang, output_lang))\n msg = web.decode(msg) # msg.replace('&#39;', \"'\")\n this_translated = \"(%s-%s) %s\" % (input_lang, output_lang, msg)\n translated = msg\n\n #if not finalmsg:\n # finalmsg = translated\n #phenny.reply(finalmsg)\n phenny.reply(translated)", "def preprocess(in_sentence, language):\r\n # TODO: Implement Function\r\n # if language is english\r\n start = \"SENTSTART \"\r\n end = \" SENTEND\"\r\n out_sentence = in_sentence.strip().lower()\r\n \r\n if language == \"e\":\r\n out_sentence = re.sub(r'([,:;()\\-+<>=.?!*/\"])',r' \\1 ',out_sentence)\r\n\r\n \r\n if language == \"f\":\r\n out_sentence = re.sub(r'([,:;()\\-+<>=.?!*/\"])',r' \\1 ',out_sentence)\r\n\r\n #for l', I think this we do not have to do this step since next step covers this\r\n out_sentence = re.sub(r'(\\b)(l\\')(\\w+)',r'\\1\\2 \\3',out_sentence)\r\n #for consonant assume y is not a consonant\r\n out_sentence = re.sub(r'(\\b)([aeiouqwrtypsdfghjklzxcvbnm]\\')(\\w+)',r'\\1\\2 \\3',out_sentence)\r\n #for que\r\n out_sentence = re.sub(r'(\\b)(qu\\')(\\w+)',r'\\1\\2 \\3',out_sentence)\r\n #for on and il\r\n out_sentence = re.sub(r'(\\w+)(\\')(on|il)(\\b)',r'\\1\\2 \\3\\4',out_sentence)\r\n #for d’abord, d’accord, d’ailleurs, d’habitude special cases\r\n out_sentence = re.sub(r'(d\\') (abord|accord|ailleurs|habitude)(\\b)',r'\\1\\2\\3',out_sentence)\r\n \r\n out_sentence = start + out_sentence + end\r\n out_sentence = re.sub(r' {2,}',r' ',out_sentence) \r\n return out_sentence", "def spanish_to_english(self, text):\n\n src_text = [text]\n translated = self.model_es_t_en.generate(\n **self.tokenizer_es_t_en.prepare_seq2seq_batch(src_text, return_tensors=\"pt\", padding=True)\n )\n tgt_text = [\n self.tokenizer_es_t_en.decode(t, skip_special_tokens=True)\n for t in translated\n ]\n return tgt_text[0]", "def english_to_spanish(self, text):\n\n src_text = [\">>es<< {}\".format(text)]\n translated = self.model_en_t_es.generate(\n **self.tokenizer_en_t_es.prepare_seq2seq_batch(src_text, return_tensors=\"pt\", padding=True)\n )\n tgt_text = [\n self.tokenizer_en_t_es.decode(t, skip_special_tokens=True)\n for t in translated\n ]\n return tgt_text[0]", "def translate(text, conversion_dict, before=None):\n # if empty:\n if not text: return text\n # preliminary transformation:\n before = before or str\n t = before(text)\n for key, value in conversion_dict.items():\n t = t.replace(key, value)\n return t", "def phrase(word):\n\n return [child.text for child in word.subtree]", "def postprocess(sent: str, lang: str) -> str:\n return pipeline.postprocess([sent], lang=lang, tokenizer=\"\")[0]", "def prep_text(mission):\n sentences = nltk.sent_tokenize(mission)\n sentences = [nltk.word_tokenize(sent) for sent in sentences]\n return sentences", "def highlight(text, phrase, hilighter='<strong class=\"hilight\">\\\\1</strong>'):\n if not phrase or not text:\n return text\n return re.sub(re.compile('(%s)' % re.escape(phrase)), hilighter, text, re.I)", "def _text_ru_inflection_normalize(word, arg):\n if word in [\"тысяч\", \"тысячи\"]:\n return \"тысяча\"\n\n if arg == 1: # _extract_whole_number_with_text_ru\n if word in [\"одна\", \"одним\", \"одно\", \"одной\"]:\n return \"один\"\n if word == \"две\":\n return \"два\"\n if word == \"пару\":\n return \"пара\"\n\n elif arg == 2: # extract_datetime_ru\n if word in [\"часа\", \"часам\", \"часами\", \"часов\", \"часу\"]:\n return \"час\"\n if word in [\"минут\", \"минутам\", \"минутами\", \"минуту\", \"минуты\"]:\n return \"минута\"\n if word in [\"секунд\", \"секундам\", \"секундами\", \"секунду\", \"секунды\"]:\n return \"секунда\"\n if word in [\"дней\", \"дни\"]:\n return \"день\"\n if word in [\"неделе\", \"недели\", \"недель\"]:\n return \"неделя\"\n if word in [\"месяца\", \"месяцев\"]:\n return \"месяц\"\n if word in [\"года\", \"лет\"]:\n return \"год\"\n if word in _WORDS_MORNING_RU:\n return \"утром\"\n if word in [\"полудне\", \"полудня\"]:\n return \"полдень\"\n if word in _WORDS_EVENING_RU:\n return \"вечером\"\n if word in _WORDS_NIGHT_RU:\n return \"ночь\"\n if word in [\"викенд\", \"выходным\", \"выходных\"]:\n return \"выходные\"\n if word in [\"столетие\", \"столетий\", \"столетия\"]:\n return \"век\"\n\n # Week days\n if word in [\"среду\", \"среды\"]:\n return \"среда\"\n if word in [\"пятницу\", \"пятницы\"]:\n return \"пятница\"\n if word in [\"субботу\", \"субботы\"]:\n return \"суббота\"\n\n # Months\n if word in [\"марта\", \"марте\"]:\n return \"март\"\n if word in [\"мае\", \"мая\"]:\n return \"май\"\n if word in [\"августа\", \"августе\"]:\n return \"август\"\n\n if word[-2:] in [\"ле\", \"ля\", \"не\", \"ня\", \"ре\", \"ря\"]:\n tmp = word[:-1] + \"ь\"\n for name in _MONTHS_RU:\n if name == tmp:\n return name\n\n return word", "def format_portuguese_sentence(sentence):\n\n # Removes div tags and extra whitespace\n sentence = re.sub(r\"\\s\\s+\", \" \", sentence)\n sentence = sentence.replace(\"\"\"<div class=\"post__player-text\">\"\"\", \"\")\n sentence = sentence.replace(\"</div>\", \"\")\n # print(sentence)\n\n # Replaces <strong> tags with bold and underline\n sentence = re.sub(r\"<strong>\\s*\", \"<b><u>\", sentence)\n sentence = re.sub(r\"(\\W*)\\s*<\\/strong>\", r\"</u></b>\\1\", sentence)\n sentence = re.sub(r\"(<\\/u><\\/b>)(\\w+)\", r\"\\1 \\2\", sentence)\n\n # Removes extra whitespace\n sentence = sentence.replace(\" \", \" \").strip()\n\n # Adds full stop if necessary\n sentence = re.sub(r\"(\\w+)\\Z\", r\"\\1.\", sentence)\n sentence = re.sub(r\"(<\\/u><\\/b>)\\Z\", r\"\\1.\", sentence)\n # print(sentence)\n\n return sentence", "def process_tweet(tweet):\r\n em_split_emoji = emoji.get_emoji_regexp().split(tweet)\r\n em_split_whitespace = [substr.split() for substr in em_split_emoji]\r\n em_split = functools.reduce(operator.concat, em_split_whitespace)\r\n tweet = emoji.demojize(\" \".join(em_split)).translate(str.maketrans('', '', string.punctuation))\r\n return tweet.lower()", "def _translate_WWML(self, text):\n # XXX change this, not reliable on linux\n lines = text.split('\\n')\n lines = self.translator.translate(lines)\n text = '\\n'.join(lines)\n return text" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
convert patch embedding weight from manual patchify + linear proj to conv
def _conv_filter(state_dict, patch_size=16): out_dict = {} for k, v in state_dict.items(): if 'patch_embed.proj.weight' in k: v = v.reshape((v.shape[0], 3, patch_size, patch_size)) out_dict[k] = v return out_dict
[ "def _conv_filter(state_dict, patch_size=16):\n out_dict = {}\n for k, v in state_dict.items():\n if 'patch_embed.proj.weight' in k and len(v.shape) < 4:\n v = v.reshape((v.shape[0], 3, patch_size, patch_size))\n out_dict[k] = v\n return out_dict", "def __interpolate_positional_embeddings(\n self, embedding, height, width, patch_size\n ):\n\n dimensionality = embedding.shape[-1]\n\n class_token = tf.expand_dims(embedding[:1, :], 0)\n patch_positional_embeddings = embedding[1:, :]\n\n h0 = height // patch_size\n w0 = width // patch_size\n\n new_shape = tf.constant(int(math.sqrt(self.num_patches)))\n\n interpolated_embeddings = tf.image.resize(\n images=tf.reshape(\n patch_positional_embeddings,\n shape=(\n 1,\n new_shape,\n new_shape,\n dimensionality,\n ),\n ),\n size=(h0, w0),\n method=\"bicubic\",\n )\n\n reshaped_embeddings = tf.reshape(\n tensor=interpolated_embeddings, shape=(1, -1, dimensionality)\n )\n\n # linear_projection = self.linear_projection(reshaped_embeddings)\n # addition = linear_projection + reshaped_embeddings\n\n # return tf.concat([class_token, addition], 1)\n return reshaped_embeddings, class_token", "def project(v: np.ndarray, w: np.ndarray) -> np.ndarray:\n return np.dot(v, w) * (w / np.linalg.norm(w))", "def transform_to_patch_format(mask):\n im = mask\n patch_size = 16\n for j in range(0, im.shape[1], patch_size):\n for i in range(0, im.shape[0], patch_size):\n patch = im[i:i + patch_size, j:j + patch_size]\n # is a road of not?\n label = patch_to_label(patch)\n # convert whole patch to be the same as label\n im[i:i + patch_size, j:j + patch_size] = np.ones_like(patch) if label else np.zeros_like(patch)\n return im", "def projection_v3(v, w):\n return dot_v3(v, w) / w.length()", "def polyProjection(uvSetName=\"string\", projectionScaleU=float, imageScaleU=float, rotateX=float, insertBeforeDeformers=bool, keepImageRatio=bool, projectionScaleV=float, type=\"string\", mapDirection=\"string\", imageScaleV=float, rotationAngle=float, projectionCenterY=float, seamCorrect=bool, imageCenterY=float, smartFit=bool, rotateZ=float, rotateY=float, createNewMap=bool, projectionCenterZ=float, projectionCenterX=float, constructionHistory=bool, imageCenterX=float):\n pass", "def _get_projections(self, embeds):\n \n if self.normalize_e:\n embeds = F.normalize(embeds, p=2, dim=1)\n if self.training:\n embeds = self.dropout(embeds)\n p = torch.matmul(self.pmats, embeds.transpose(0,1))\n if self.normalize_p:\n proj = F.normalize(proj, p=2, dim=1)\n if self.training:\n p = self.dropout(p)\n p = p.transpose(0,1).transpose(0,2)\n return p", "def project_params(self, lp, lp_bound):\n\n assert isinstance(lp, int) or lp == 'inf'\n\n diff = self.xform_params.data - self.identity_params(self.img_shape)\n new_diff = utils.batchwise_lp_project(diff, lp, lp_bound)\n self.xform_params.data.add_(new_diff - diff)", "def makeFullACTMap(params):\n\n # read in the template map\n kmap = liteMap.liteMapFromFits(params['fullTemplate'])\n\n # pixel scale of the template map\n Ni=kmap.Nx\n Nj=kmap.Ny\n\n # make a copy of input template map\n template=kmap.copy()\n x0 = template.x0\n if x0 > 180.0:\n x0 -= 360.0\n x1 = template.x1\n if x1 > 180.0:\n x1 -= 360.0\n\n # zero out a weight map and the template map\n weight=np.ndarray(shape=(Nj,Ni), dtype=float)\n weight[:,:]=0.0\n template.data[:,:]=0.0\n\n wscore=0.0\n\n # read in the patches\n patches = params['patches']\n\n N_patches = len(patches) # the number of patches\n error = 0.0\n error_weight = 0.0\n \n # loop over each patch which we need to interpolate\n for k in range(0, N_patches):\n\n print \"interpolating map %s\" %patches[k]\n\n patch = liteMap.liteMapFromFits(params['patchDir']+patches[k])\n \n # make sure RA of patch is (-180, 180)\n if patch.x0 > 180.0: \n patch.x0 -= 360.0\n if patch.x1 > 180.0:\n patch.x1 -= 360.0\n\n # check that the patch overlaps with the template map at all:\n if patch.x0 > x0 and patch.x1 > x0:\n print 'map %s does not overlap...' %patches[k]\n continue\n if patch.x0 < x1 and patch.x1 < x1:\n print 'map %s does not overlap...' %patches[k]\n continue\n\n # new pixel size is smaller by 2^2\n patch_finer=liteMap.upgradePixelPitch(patch, 2.0)\n\n # new pixel scale for input patch\n N1=patch_finer.Nx\n N2=patch_finer.Ny\n\n score = 0 # keep score of how we do\n \n # loop over the pixels of the finer patch\n for i in xrange(0,N1-1):\n for j in xrange(0,N2-1):\n\n # ra, dec of pixel location (i, j) in input patch\n ra, dec = patch_finer.pixToSky(i,j)\n\n # interpolate the value of the patch at (ra, dec) onto the correct template pixel\n try: \n i_opt, j_opt = template.skyToPix(ra,dec)\n\n j_opt = np.round(j_opt)\n i_opt = np.round(i_opt)\n if (i_opt > 0 and i_opt < template.Nx) and (j_opt > 0 and j_opt < template.Ny):\n\n template.data[j_opt,i_opt] += patch_finer.data[j,i]\n score += 1\n weight[j_opt,i_opt] += 1.0 \n\n except IndexError:\n error += 1\n pass\n \n print score/(1.0*N1*N2)\n\n # divide out the weights to get the correct mean in each pixel\n inds = np.where(weight > 0.0)\n template.data[inds] /= weight[inds]\n \n # save the full map\n template.writeFits(params['outDir']+'act_kmap_resampled_filtered_%s.fits' %params['fileTag'], overWrite=True)\n \n return", "def pixel_to_proj(self, p):\n\n p = np.matrix(p).transpose()\n p = np.vstack((p, np.ones((1, p.shape[1]))))\n out = self.geo_transform[:2,:] * p\n out = out.transpose()\n return np.array(out)", "def cube2latlon_preprocess(x, y, xi, yi):", "def project(K, X):\r\n if X.shape[0] == 3:\r\n uv = K @ X\r\n elif X.shape[0] == 4:\r\n uv = K @ X[:3,:]\r\n\r\n uv /= uv[-1,:]\r\n return uv[0,:], uv[1,:]", "def reconstruct_infer_patches_3d(predictions, infer_dir, params):\n\n # define params - converting all to python native variables as they may be imported as numpy\n patch_size = params.infer_dims\n overlap = params.infer_patch_overlap\n data_prefix = [str(item) for item in params.data_prefix]\n data_format = params.data_format\n data_plane = params.data_plane\n norm = params.norm_data\n norm_mode = params.norm_mode\n\n # for sliding window 3d slabs - must be same as in _tf_patches_3d_infer above\n ksizes = [1] + patch_size + [1]\n strides = [1, patch_size[0] / overlap[0], patch_size[1] / overlap[1], patch_size[2] / overlap[2], 1]\n\n # define necessary functions\n def extract_patches(x):\n return tf.extract_volume_patches(x, ksizes=ksizes, strides=strides, padding='SAME')\n\n def extract_patches_inverse(x, y):\n with tf.GradientTape(persistent=True) as tape:\n _x = tf.zeros_like(x)\n tape.watch(_x)\n _y = extract_patches(_x)\n grad = tape.gradient(_y, _x)\n # Divide by grad, to \"average\" together the overlapping patches\n # otherwise they would simply sum up\n return tape.gradient(_y, _x, output_gradients=y) / grad\n\n # load original data as a dummy and convert channel dim size to match output [batch, x, y, z, channel]\n data = load_multicon_preserve_size_3d(infer_dir, data_prefix, data_format, data_plane, norm, norm_mode)\n data = np.zeros((data.shape[0:4] + (params.output_filters,)), dtype=np.float32)\n # data = data[:, :, :, :, [0]] if params.data_format == 'channels_last' else data[:, [0], :, :, :]\n\n # get shape of patches as they would have been generated during inference\n dummy_patches = extract_patches(data)\n\n # reshape predictions to original patch shape\n predictions = tf.reshape(predictions, tf.shape(input=dummy_patches))\n\n # reconstruct\n reconstructed = extract_patches_inverse(data, predictions)\n output = np.squeeze(reconstructed.numpy())\n\n return output", "def unproject(win, modelView, modelProj, viewport):\n # Compute the inverse transform\n m = np.linalg.inv(modelProj @ modelView) # 4 x 4\n winx = win[:, 0]\n winy = win[:, 1]\n winz = win[:, 2]\n # [B, 4]\n input_ = np.zeros((win.shape[0], 4), dtype=win.dtype)\n input_[:, 0] = (winx - viewport[0]) / viewport[2] * 2.0 - 1.0\n input_[:, 1] = (winy - viewport[1]) / viewport[3] * 2.0 - 1.0\n input_[:, 2] = winz * 2.0 - 1.0\n input_[:, 3] = 1.0\n out = (m @ input_.T).T\n # Check if out[3] == 0 ?\n out[:, 3] = 1 / out[:, 3]\n out[:, 0] = out[:, 0] * out[:, 3]\n out[:, 1] = out[:, 1] * out[:, 3]\n out[:, 2] = out[:, 2] * out[:, 3]\n return out[:, :3]", "def scipy_pinv(partial_semantics, delta_target):\n partial_semantics_inverse = sp_pinv(partial_semantics)\n optimal_weights = dot(partial_semantics_inverse, delta_target)\n return optimal_weights", "def translate_weights(self):\n pass", "def vectToPatch(vect):\n h=int(math.sqrt(np.shape(vect)[0]/3))\n return np.reshape(vect, (h,h,3))", "def proj(self, u, vec):\n return (vec + adj(vec)) / 2", "def input_projection(self, input_embed):\n net_config = self.net_config\n initializer = self.get_initializer()\n ret_dict = {}\n\n output = input_embed\n if net_config.d_embed != net_config.d_model:\n tf.logging.info(\"Project input embedding: %s -> %s\",\n net_config.d_embed, net_config.d_model)\n output = ops.dense(\n output,\n net_config.d_model,\n inp_shape=net_config.d_embed,\n initializer=initializer,\n scope=\"input_projection\")\n\n return output, ret_dict", "def unpak(self, w):\n\n errstring = self.consist('som')\n if errstring != None:\n raise Exception(errstring)\n \n # Put weights back into network data structure\n self.map = np.reshape(w.T, (self.nin, self.map_size[0], self.map_size[1]), order='F')" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete license from cluster
def license_v2_delete(self): license_delete = netapp_utils.zapi.NaElement.create_node_with_children( 'license-v2-delete', **{'package': self.license_package, 'serial-number': self.node_serial_number}) try: self.server.invoke_successfully(license_delete, enable_tunneling=True) except netapp_utils.zapi.NaApiError as error: self.module.fail_json(msg='Error deleting license from cluster %s : %s' % (self.cluster_name, to_native(error)), exception=traceback.format_exc())
[ "def delete_license(self, license_key):\n return self._xjtrans(\"/settings/licenses/%s\" % license_key, \"DELETE\", None, True, APITimestampFormat.NANOSECOND)", "def delete(self, license_key):\n\n try:\n lic = urllib.parse.quote(license_key) # python 2\n except:\n lic = urllib.pathname2url(license_key) # python 3\n\n return self.client._request(url='/api/v2/hpelicense/{}/'.format(lic), http_method='delete', description='license/delete')", "def step_erase_licenses(context):\n jlink = context.jlink\n assert jlink.erase_licenses()", "async def remove(self) -> None:\n await self._state.http.remove_license(self.id)", "async def licensing_info_delete(req):\n state = req.app[\"state\"]\n\n # Removing license information implies terminating MATLAB\n await state.stop_matlab()\n\n # Unset licensing information\n state.unset_licensing()\n\n # Persist licensing information\n state.persist_licensing()\n\n return create_status_response(req.app)", "def destroy_cluster(self, cluster_id):", "def test_delete_iceberg_delete_license_by_id(self):\n pass", "def cli_cosmosdb_mongocluster_delete(client,\r\n resource_group_name, cluster_name):\r\n\r\n return client.begin_delete(resource_group_name, cluster_name)", "def test_delete_license_by_authenticated_user_passes(self):\n response = self.client.delete(\n self.single_licence_url,\n headers={\"Authorization\": self.test_user_token},\n )\n response_body = response.get_json()\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response_body[\"Success\"], \"License deleted\")", "def test_delete_iceberg_delete_all_license(self):\n pass", "def delete(self, cluster: str, namespace: str) -> None:\n with self._lock:\n self._inv.get(cluster, {}).pop(namespace, None)", "def clear_license_terms(self):\n pass", "def delete(profile, snapshot_identifier, cluster_identifier, wait):\n if not snapshot_identifier:\n snapshot_identifier = \"staging-horizon-2021-07-29-133932\"\n if not cluster_identifier:\n cluster_identifier = \"staging-horizon-a\"\n rds_client = get_rds_client(profile)\n destroy_cluster(\n cluster_identifier,\n snapshot_identifier,\n wait,\n rds_client,\n )", "def destroy(self, log_level=\"DEBUG\"):\n ocm.destroy_cluster(self.cluster_name)", "def delete_cluster(self, ClusterArn: str, CurrentVersion: str = None) -> Dict:\n pass", "def test_delete_license_by_unauthenticated_user_fails(self):\n response = self.client.delete(self.single_licence_url)\n response_body = response.get_json()\n self.assertEqual(response.status_code, 401)\n self.assertEqual(response_body[\"SubCode\"], \"InvalidToken\")", "def clear_license_terms(self):\n raise errors.Unimplemented()", "def unbind_license(name):\n engine = Engine(name).load()\n for node in engine.nodes:\n return node.unbind_license()", "def delete_cluster(cluster_config: str):\n with open(cluster_config) as f:\n config = yaml.safe_load(f)\n\n p = subprocess.run(\n [\"cortex\", \"cluster\", \"down\", \"-y\", \"--config\", cluster_config],\n stdout=sys.stdout,\n stderr=sys.stderr,\n )\n\n if p.returncode != 0:\n raise ClusterDeletionException(f\"failed to delete cluster with config: {cluster_config}\")" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates CSV file of every teams' unique id
def get_team_id(): team_abb = [] for team in Teams(): team_abb.append(team.abbreviation) with open('Data/team_abb.csv','w',newline='') as result_file: wr = csv.writer(result_file, quoting=csv.QUOTE_ALL) wr.writerow(team_abb)
[ "def generate_TeamImportData(session, output_directory):\n with open(\n output_directory / Path(\"TeamImportData.csv\"), \"w\", newline=\"\"\n ) as csvfile:\n csvwriter = csv.writer(csvfile)\n\n for school in session.query(School).order_by(School.SchoolID):\n row = [\n school.SchoolID,\n school.SchoolName,\n school.Address1,\n school.Address2,\n school.City,\n school.State,\n school.ZipCode,\n \"MEDIUM\", # Division\n \"MEDIUM\", # Category\n \"Kansas\", # Region\n ]\n logging.debug(row)\n csvwriter.writerow(row)", "def make_participant_dump_csv(self):\n columns = collections.OrderedDict([\n ('id','study_id'),\n ('created',lambda c: c.created.date()),\n ('facility','facility'),\n ('group','study_group'),\n ('shared',lambda c: 1 if c.phone_shared else 0) ,\n ('validation',lambda c: 1 if c.is_validated else 0),\n ('age','age'),\n ])\n p_all = cont.Contact.objects.all()\n file_path = os.path.join(self.options['dir'],'participant_dump.csv')\n make_csv(columns,p_all,file_path)\n return file_path", "def csv(self, fileName, allfields=False):\r\n import csv\r\n\r\n fields, rows = set([]), []\r\n players = list(self)\r\n for p in players:\r\n for field, stat in p.stats.iteritems():\r\n fields.add(field)\r\n if allfields:\r\n for statId, info in statmap.idmap.iteritems():\r\n for field in info['fields']:\r\n fields.add(field)\r\n fields = sorted(list(fields))\r\n\r\n for p in players:\r\n d = {\r\n 'name': p.name,\r\n 'id': p.playerid,\r\n 'home': p.home and 'yes' or 'no',\r\n 'team': p.team,\r\n 'pos': 'N/A',\r\n }\r\n if p.player is not None:\r\n d['pos'] = p.player.position\r\n\r\n for field in fields:\r\n if field in p.__dict__:\r\n d[field] = p.__dict__[field]\r\n else:\r\n d[field] = \"\"\r\n rows.append(d)\r\n\r\n fieldNames = [\"name\", \"id\", \"home\", \"team\", \"pos\"] + fields\r\n rows = [dict((f, f) for f in fieldNames)] + rows\r\n csv.DictWriter(open(fileName, 'w+'), fieldNames).writerows(rows)", "def create_csv(li, assignment_ids):\n\n\twith open('results.csv', 'w', encoding=\"utf-8\") as f:\n\t\tw = csv.writer(f)\n\n\t\t\"\"\"\n\t\tHeaders\n\t\t\"\"\"\n\t\tw.writerow(['assignment_id', 'subject', 'trial_number', 'white_balls', 'black_balls', 'quantifier', 'colour',\n\t\t\t'QUANT', 'of', 'the1', 'balls', 'are', 'TGW', 'IN', 'the2', 'picture',\n\t\t\t'answer', 'answer_time',\n\t\t\t'age', 'gender', 'languages', 'education', 'comments'])\n\n\t\t# for each assignment\n\t\tfor assignment in range(0, len(li)):\n\n\t\t\t# for each trial\n\t\t\tfor trial in li[assignment]['results']:\n\t\t\t\tassignment_id = assignment_ids[assignment][1:-1]\n\t\t\t\tage = li[assignment]['subjectInfo']['age']\n\t\t\t\tgender = li[assignment]['subjectInfo']['gender']\n\t\t\t\tlanguages = li[assignment]['subjectInfo']['languages']\n\t\t\t\teducation = li[assignment]['subjectInfo']['education']\n\t\t\t\tcomments = li[assignment]['subjectInfo']['comments']\n\n\t\t\t\tif (trial['colour'] == \"white\"):\n\t\t\t\t\tw.writerow([\n\t\t\t\t\t\tassignment_id,\n\t\t\t\t\t\tassignment + 1,\n\t\t\t\t\t\ttrial['trialNumber'],\n\t\t\t\t\t\ttrial['TCBalls'],\n\t\t\t\t\t\ttrial['OCBalls'],\n\t\t\t\t\t\ttrial['quantifier'],\n\t\t\t\t\t\ttrial['colour'],\n\t\t\t\t\t\ttrial['readingTimes'][0],\n\t\t\t\t\t\ttrial['readingTimes'][1],\n\t\t\t\t\t\ttrial['readingTimes'][2],\n\t\t\t\t\t\ttrial['readingTimes'][3],\n\t\t\t\t\t\ttrial['readingTimes'][4],\n\t\t\t\t\t\ttrial['readingTimes'][5],\n\t\t\t\t\t\ttrial['readingTimes'][6],\n\t\t\t\t\t\ttrial['readingTimes'][7],\n\t\t\t\t\t\ttrial['readingTimes'][8],\n\t\t\t\t\t\ttrial['response'][0],\n\t\t\t\t\t\ttrial['response'][1],\n\t\t\t\t\t\tage,\n\t\t\t\t\t\tgender,\n\t\t\t\t\t\tlanguages,\n\t\t\t\t\t\teducation,\n\t\t\t\t\t\tcomments\n\t\t\t\t\t\t])\n\t\t\t\telse:\n\t\t\t\t\tw.writerow([\n\t\t\t\t\t\tassignment_id,\n\t\t\t\t\t\tassignment + 1,\n\t\t\t\t\t\ttrial['trialNumber'],\n\t\t\t\t\t\ttrial['OCBalls'],\n\t\t\t\t\t\ttrial['TCBalls'],\n\t\t\t\t\t\ttrial['quantifier'],\n\t\t\t\t\t\ttrial['colour'],\n\t\t\t\t\t\ttrial['readingTimes'][0],\n\t\t\t\t\t\ttrial['readingTimes'][1],\n\t\t\t\t\t\ttrial['readingTimes'][2],\n\t\t\t\t\t\ttrial['readingTimes'][3],\n\t\t\t\t\t\ttrial['readingTimes'][4],\n\t\t\t\t\t\ttrial['readingTimes'][5],\n\t\t\t\t\t\ttrial['readingTimes'][6],\n\t\t\t\t\t\ttrial['readingTimes'][7],\n\t\t\t\t\t\ttrial['readingTimes'][8],\n\t\t\t\t\t\ttrial['response'][0],\n\t\t\t\t\t\ttrial['response'][1],\n\t\t\t\t\t\tage,\n\t\t\t\t\t\tgender,\n\t\t\t\t\t\tlanguages,\n\t\t\t\t\t\teducation,\n\t\t\t\t\t\tcomments\n\t\t\t\t\t\t])", "def get_file_of_players():\n file_name = 'players.csv'\n file_path = os.path.join(settings.DOWNLOAD_ROOT, file_name)\n with open(file_path, 'w') as csv_file:\n fieldnames = ['ranking', 'first_name', 'last_name', 'email', 'contact_number']\n\n csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)\n csv_writer.writeheader()\n players = Player.objects.all().order_by('ranking')\n for player in players:\n csv_writer.writerow(\n {'ranking': player.ranking,\n 'first_name': player.first_name,\n 'last_name': player.last_name,\n 'email': player.last_name,\n 'contact_number': player.contact_number\n })\n\n return file_path", "def writePlayerCSV(self) -> None:\r\n with open(self.csv_location, \"w\", encoding=\"utf-16\") as file:\r\n for extracted_player in self._extracted_players:\r\n player_name = extracted_player\r\n print(self._extracted_players[extracted_player])\r\n assert len(self._extracted_players[extracted_player]) == 4 #ensures length is 5 to confirm the values can be unpacked\r\n player_long_name, player_position, player_rating, player_club = self._extracted_players[extracted_player]\r\n csv_format = re.compile(\r\n player_name + \",\" + player_long_name + \",\" + player_position + \",\" + player_rating + \",\" + player_club + \",\" + self._season + \"\\n\")\r\n file.write(csv_format.pattern) #Writes the compiled RegEx pattern with the values inserted\r", "def get_player_id(school,start,end):\n player_id = []\n for i in range(start,end):\n for player in Roster(school,i).players:\n player_id.append(player.player_id)\n \n # \n player_id = set(player_id)\n \n # Output list of player_id to a csv file\n with open('sportsref_Data/%s_player_id.csv' %school,'w',newline='') as result_file:\n wr = csv.writer(result_file, quoting=csv.QUOTE_ALL)\n wr.writerow(player_id)", "def write_to_CSV(api_data):\n\n with open(\"player_data.csv\", 'w') as fp:\n writer = csv.DictWriter(fp, fieldnames=['first', 'last', 'cost', 'position', 'team', 'selected by %', 'form', 'pts'])\n writer.writeheader()\n for player_name, player_info in api_data.items(): \n writer.writerow((player_info)) \n print(\"Data exported to CSV.\")", "def _export_users():\n csv_file_obj = io.StringIO()\n csv_writer = csv.writer(csv_file_obj, dialect=\"unix\")\n for user in User.query.all():\n csv_writer.writerow(\n [user.id_, user.email, user.access_token, user.username, user.full_name]\n )\n return csv_file_obj", "def writeIDs(self, fileName):\n fileOut = open(fileName, 'w')\n while True:\n if(len(self.tweetQueue) > 0):\n fileOut.write(self.tweetQueue.popleft())\n fileOut.write(',')\n fileOut.close()", "def write_games(games, filename):\n fieldnames = 'date,season,phase,flight,team1,team2,result1,elo1,elo2,elo_prob1'.split(',')\n\n with open(filename, 'w', newline='') as csvfile:\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n writer.writeheader()\n writer.writerows(map(Util.format_game_entry, games))\n\n print(\"Games data saved to \" + filename)", "def sample_data(tweet_object_list):\n with open(\"sample_data.csv\", \"w+\") as file:\n for tweet in tweet_object_list:\n file.write(\n '{},\"{}\",\"{}\"\\n'.format(tweet[\"_id\"], tweet[\"name\"], tweet[\"text\"])\n )", "def write_to_submit_CSV(players,arrayOfResults):\n\twith open('../../datayasp/results.csv', 'w') as csvfile:\n\t\twriter = csv.DictWriter(csvfile, fieldresults)\n\t\twriter.writeheader()\n\t\tfor i in range(len(arrayOfResults)):\n\t\t\twriter.writerow({\"row ID\": players[i], \"battleneturl\":arrayOfResults[i]})", "def save(self, name=None):\n if name is None:\n name = self.file_path\n ids = name + '.ids.csv'\n print('saving ids to {:s}'.format(ids))\n lists2csv(self.ids, ids, delimiter=' ')\n dictionary = name + '.dict.csv'\n print('saving dictionary to {:s}'.format(dictionary))\n lists2csv([[word, i] for word, i in self.word_to_id.items()], dictionary, \" \", encoding='utf-8')", "def create_csv(topN):\n all_dates = os.listdir(articles_path)\n header = ['month', 'entities']\n output = []\n for date in all_dates[0:11]:\n output.append([date[:-3], get_entities(date, topN)])\n file = open(csv_path / 'entity_vectors.csv', mode='w+', newline='', encoding='utf-8')\n with file:\n write = csv.writer(file)\n write.writerow(header)\n write.writerows(output)", "async def dump_all_participants(channel,url):\n\n all_phone_participants = []\n\n #to override 10000 limit, we use client.get_participants(aggressive=True)\n participants = await client.get_participants(channel,None,aggressive=True)\n print(f\"All participants: {len(participants)}\")\n for participant in participants:\n participant:User\n if participant.phone is not None:\n all_phone_participants.append(participant)\n print(f\"All phone participants: {len(all_phone_participants)}\")\n\n filename = url+'.csv'\n full_file_name = os.path.join(csv_dir,filename)\n with open(full_file_name,mode=\"w\",encoding='utf-8',newline='') as csv_file:\n fieldnames = ['phone','first_name', 'last_name', 'username']\n writer = csv.DictWriter(csv_file, fieldnames=fieldnames)\n writer.writeheader()\n for participant in all_phone_participants:\n participant:User\n writer.writerow({'phone':participant.phone,'first_name':participant.first_name,'last_name':participant.last_name,\n 'username':participant.username})", "def save(self, name=None):\n if name is None:\n name = self.file_path\n ids = name+'.ids.csv'\n print('saving ids to {:s}'.format(ids))\n lists2csv(self.ids, ids, delimiter=' ')\n dictionary = name+'.dict.csv'\n print('saving dictionary to {:s}'.format(dictionary))\n lists2csv([[word, i] for word, i in self.word_to_id.items()], dictionary, \" \")", "def gen_twid_list(dst, srcs):\r\n fdst = open(dst, 'w+')\r\n\r\n cnt = 0\r\n for line in fileinput.input(srcs, openhook = fileinput.hook_compressed):\r\n try:\r\n status = json.loads(line)\r\n if status.has_key('place') and status['place'] != None:\r\n if status['place']['type'] != 'poi':\r\n continue\r\n print >> fdst, status['id']\r\n cnt += 1\r\n except ValueError:\r\n print 'ValueError'\r\n\r\n fdst.flush()\r\n fdst.close()\r\n logging.info('Generate tweet_id ::{0} tweet IDs are generated.'.format(cnt))\r\n logging.info('------------------------------------------')", "def saveToCSV(office, sport, matches, driver):\r\n # fill .csv file with the scraped matches (rewrites the existing values in provided datafile with fresh ones)\r\n with open(office + '/' + sport + '.csv', 'w', newline='', encoding='utf-8') as f:\r\n write = csv.writer(f)\r\n write.writerow(['name', 'date', 'home', 'draw', 'away'])\r\n write.writerows(matches)\r\n # close chrome driver\r\n driver.quit()" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates csv with all player_ids from [X] school
def get_player_id(school,start,end): player_id = [] for i in range(start,end): for player in Roster(school,i).players: player_id.append(player.player_id) # player_id = set(player_id) # Output list of player_id to a csv file with open('sportsref_Data/%s_player_id.csv' %school,'w',newline='') as result_file: wr = csv.writer(result_file, quoting=csv.QUOTE_ALL) wr.writerow(player_id)
[ "def writePlayerCSV(self) -> None:\r\n with open(self.csv_location, \"w\", encoding=\"utf-16\") as file:\r\n for extracted_player in self._extracted_players:\r\n player_name = extracted_player\r\n print(self._extracted_players[extracted_player])\r\n assert len(self._extracted_players[extracted_player]) == 4 #ensures length is 5 to confirm the values can be unpacked\r\n player_long_name, player_position, player_rating, player_club = self._extracted_players[extracted_player]\r\n csv_format = re.compile(\r\n player_name + \",\" + player_long_name + \",\" + player_position + \",\" + player_rating + \",\" + player_club + \",\" + self._season + \"\\n\")\r\n file.write(csv_format.pattern) #Writes the compiled RegEx pattern with the values inserted\r", "def generate_TeamImportData(session, output_directory):\n with open(\n output_directory / Path(\"TeamImportData.csv\"), \"w\", newline=\"\"\n ) as csvfile:\n csvwriter = csv.writer(csvfile)\n\n for school in session.query(School).order_by(School.SchoolID):\n row = [\n school.SchoolID,\n school.SchoolName,\n school.Address1,\n school.Address2,\n school.City,\n school.State,\n school.ZipCode,\n \"MEDIUM\", # Division\n \"MEDIUM\", # Category\n \"Kansas\", # Region\n ]\n logging.debug(row)\n csvwriter.writerow(row)", "def create_csv(li, assignment_ids):\n\n\twith open('results.csv', 'w', encoding=\"utf-8\") as f:\n\t\tw = csv.writer(f)\n\n\t\t\"\"\"\n\t\tHeaders\n\t\t\"\"\"\n\t\tw.writerow(['assignment_id', 'subject', 'trial_number', 'white_balls', 'black_balls', 'quantifier', 'colour',\n\t\t\t'QUANT', 'of', 'the1', 'balls', 'are', 'TGW', 'IN', 'the2', 'picture',\n\t\t\t'answer', 'answer_time',\n\t\t\t'age', 'gender', 'languages', 'education', 'comments'])\n\n\t\t# for each assignment\n\t\tfor assignment in range(0, len(li)):\n\n\t\t\t# for each trial\n\t\t\tfor trial in li[assignment]['results']:\n\t\t\t\tassignment_id = assignment_ids[assignment][1:-1]\n\t\t\t\tage = li[assignment]['subjectInfo']['age']\n\t\t\t\tgender = li[assignment]['subjectInfo']['gender']\n\t\t\t\tlanguages = li[assignment]['subjectInfo']['languages']\n\t\t\t\teducation = li[assignment]['subjectInfo']['education']\n\t\t\t\tcomments = li[assignment]['subjectInfo']['comments']\n\n\t\t\t\tif (trial['colour'] == \"white\"):\n\t\t\t\t\tw.writerow([\n\t\t\t\t\t\tassignment_id,\n\t\t\t\t\t\tassignment + 1,\n\t\t\t\t\t\ttrial['trialNumber'],\n\t\t\t\t\t\ttrial['TCBalls'],\n\t\t\t\t\t\ttrial['OCBalls'],\n\t\t\t\t\t\ttrial['quantifier'],\n\t\t\t\t\t\ttrial['colour'],\n\t\t\t\t\t\ttrial['readingTimes'][0],\n\t\t\t\t\t\ttrial['readingTimes'][1],\n\t\t\t\t\t\ttrial['readingTimes'][2],\n\t\t\t\t\t\ttrial['readingTimes'][3],\n\t\t\t\t\t\ttrial['readingTimes'][4],\n\t\t\t\t\t\ttrial['readingTimes'][5],\n\t\t\t\t\t\ttrial['readingTimes'][6],\n\t\t\t\t\t\ttrial['readingTimes'][7],\n\t\t\t\t\t\ttrial['readingTimes'][8],\n\t\t\t\t\t\ttrial['response'][0],\n\t\t\t\t\t\ttrial['response'][1],\n\t\t\t\t\t\tage,\n\t\t\t\t\t\tgender,\n\t\t\t\t\t\tlanguages,\n\t\t\t\t\t\teducation,\n\t\t\t\t\t\tcomments\n\t\t\t\t\t\t])\n\t\t\t\telse:\n\t\t\t\t\tw.writerow([\n\t\t\t\t\t\tassignment_id,\n\t\t\t\t\t\tassignment + 1,\n\t\t\t\t\t\ttrial['trialNumber'],\n\t\t\t\t\t\ttrial['OCBalls'],\n\t\t\t\t\t\ttrial['TCBalls'],\n\t\t\t\t\t\ttrial['quantifier'],\n\t\t\t\t\t\ttrial['colour'],\n\t\t\t\t\t\ttrial['readingTimes'][0],\n\t\t\t\t\t\ttrial['readingTimes'][1],\n\t\t\t\t\t\ttrial['readingTimes'][2],\n\t\t\t\t\t\ttrial['readingTimes'][3],\n\t\t\t\t\t\ttrial['readingTimes'][4],\n\t\t\t\t\t\ttrial['readingTimes'][5],\n\t\t\t\t\t\ttrial['readingTimes'][6],\n\t\t\t\t\t\ttrial['readingTimes'][7],\n\t\t\t\t\t\ttrial['readingTimes'][8],\n\t\t\t\t\t\ttrial['response'][0],\n\t\t\t\t\t\ttrial['response'][1],\n\t\t\t\t\t\tage,\n\t\t\t\t\t\tgender,\n\t\t\t\t\t\tlanguages,\n\t\t\t\t\t\teducation,\n\t\t\t\t\t\tcomments\n\t\t\t\t\t\t])", "def make_participant_dump_csv(self):\n columns = collections.OrderedDict([\n ('id','study_id'),\n ('created',lambda c: c.created.date()),\n ('facility','facility'),\n ('group','study_group'),\n ('shared',lambda c: 1 if c.phone_shared else 0) ,\n ('validation',lambda c: 1 if c.is_validated else 0),\n ('age','age'),\n ])\n p_all = cont.Contact.objects.all()\n file_path = os.path.join(self.options['dir'],'participant_dump.csv')\n make_csv(columns,p_all,file_path)\n return file_path", "def get_file_of_players():\n file_name = 'players.csv'\n file_path = os.path.join(settings.DOWNLOAD_ROOT, file_name)\n with open(file_path, 'w') as csv_file:\n fieldnames = ['ranking', 'first_name', 'last_name', 'email', 'contact_number']\n\n csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)\n csv_writer.writeheader()\n players = Player.objects.all().order_by('ranking')\n for player in players:\n csv_writer.writerow(\n {'ranking': player.ranking,\n 'first_name': player.first_name,\n 'last_name': player.last_name,\n 'email': player.last_name,\n 'contact_number': player.contact_number\n })\n\n return file_path", "def get_team_id():\n team_abb = []\n for team in Teams():\n team_abb.append(team.abbreviation)\n \n with open('Data/team_abb.csv','w',newline='') as result_file:\n wr = csv.writer(result_file, quoting=csv.QUOTE_ALL)\n wr.writerow(team_abb)", "def csv(self, fileName, allfields=False):\r\n import csv\r\n\r\n fields, rows = set([]), []\r\n players = list(self)\r\n for p in players:\r\n for field, stat in p.stats.iteritems():\r\n fields.add(field)\r\n if allfields:\r\n for statId, info in statmap.idmap.iteritems():\r\n for field in info['fields']:\r\n fields.add(field)\r\n fields = sorted(list(fields))\r\n\r\n for p in players:\r\n d = {\r\n 'name': p.name,\r\n 'id': p.playerid,\r\n 'home': p.home and 'yes' or 'no',\r\n 'team': p.team,\r\n 'pos': 'N/A',\r\n }\r\n if p.player is not None:\r\n d['pos'] = p.player.position\r\n\r\n for field in fields:\r\n if field in p.__dict__:\r\n d[field] = p.__dict__[field]\r\n else:\r\n d[field] = \"\"\r\n rows.append(d)\r\n\r\n fieldNames = [\"name\", \"id\", \"home\", \"team\", \"pos\"] + fields\r\n rows = [dict((f, f) for f in fieldNames)] + rows\r\n csv.DictWriter(open(fileName, 'w+'), fieldNames).writerows(rows)", "def generate_CoachImport(session, output_directory):\n with open(output_directory / Path(\"CoachImport.csv\"), \"w\", newline=\"\") as csvfile:\n csvwriter = csv.writer(csvfile)\n\n coaches = (\n session.query(Category).filter_by(CategoryDescription=\"Coach\").one().people\n )\n for coach in coaches:\n row = [\n coach.SchoolID,\n coach.FirstName,\n coach.LastName,\n coach.Email,\n \"\",\n \"\",\n \"\",\n \"www\",\n ]\n logging.debug(row)\n csvwriter.writerow(row)", "def csv_lesson(request, course, lesson):\n course = get_object_or_404(Course, slug=course)\n lesson = get_object_or_404(Lesson, slug=lesson, course=course)\n \n buffer = StringIO()\n writer = csv.writer(buffer)\n \n # Headers\n writer.writerow(\n [\"Section\", \"Task\", \"Attempts\", \"Correct\", \"Revealed\"]\n )\n \n section_number = 0\n for s in lesson.sections.all():\n section_number += 1\n task_number = 0\n for t in s.tasks.all():\n task_number += 1\n writer.writerow(\n [section_number, task_number, utils.attempts(task=t), utils.correct(task=t), utils.revealed(task=t)]\n )\n \n return HttpResponse(buffer.getvalue(), \"text/csv\")", "def songs_to_Csv(songs,songs_at_start):\n songs_added = len(songs) - songs_at_start\n songs_final = songs_added + songs_at_start\n print(\"\"\"\n {} Songs saved to Songs.csv\n Have a nice day!\n \"\"\".format(songs_final))\n for i in range(len(songs)):\n songs[i][1] = str(songs[i][1])\n out_file = open(\"songs.csv\", 'w',newline='') #Opening the file in write mode, newline='' is for avoiding the blank rows while writing in the csv\n writer=csv.writer(out_file) #passing the file in writer function\n writer.writerows(songs) #writing the songs list in Csv\n out_file.close() # closing the file", "def write_train_csv(self):\n smiles_only = pd.DataFrame({\"SMILES\": list(self.assays[self.smiles_type])})\n smiles_only.to_csv(self.ligands_csv)", "def get_speakers_as_csv(self):\n # iterate through all of the speakers and return the csv\n is_first_speaker = True\n list_of_speakers_as_csv = \"\"\n for speaker in self.speakers.all():\n if is_first_speaker != True:\n # if not the first speaker, add in a comma in CSV string\n list_of_speakers_as_csv += \", \"\n list_of_speakers_as_csv += speaker.get_full_name()\n is_first_speaker = False\n return list_of_speakers_as_csv", "def write_to_CSV(api_data):\n\n with open(\"player_data.csv\", 'w') as fp:\n writer = csv.DictWriter(fp, fieldnames=['first', 'last', 'cost', 'position', 'team', 'selected by %', 'form', 'pts'])\n writer.writeheader()\n for player_name, player_info in api_data.items(): \n writer.writerow((player_info)) \n print(\"Data exported to CSV.\")", "def generate_csv(self, cards, out):\n writer = csv.writer(out)\n\n # Header row\n writer.writerow([\"Number\", \"Short ID\", \"Active\"])\n for card in cards:\n writer.writerow([card.number, card.short_id(), card.active])", "def asteroids_csv(self, payload):\n csv_file=open(f\"/tmp/asteroids_{self.today}.csv\",'w', newline='\\n')\n fields=list(payload[0].keys())\n writer=csv.DictWriter(csv_file, fieldnames=fields)\n writer.writeheader()\n writer.writerows(payload)\n csv_file.close()", "def _export_users():\n csv_file_obj = io.StringIO()\n csv_writer = csv.writer(csv_file_obj, dialect=\"unix\")\n for user in User.query.all():\n csv_writer.writerow(\n [user.id_, user.email, user.access_token, user.username, user.full_name]\n )\n return csv_file_obj", "def outputCSV(sheet, fileObj):\n import csv\n combined = csv.writer(fileObj, delimiter=\",\", quoting=csv.QUOTE_ALL)\n i = 0\n for row in sheet:\n combined.writerow(row)\n i += 1\n print(\"Successfully wrote \"+str(i)+\" rows to file '\"+os.getcwd()+\"/\"+fileObj.name+\"'\")", "def test_export_fk_as_id(self):\n from nomnom.tests.models import Instructor\n request_factory = RequestFactory()\n req = request_factory.get('/admin/test/instructor/')\n \n response = export_as_csv(modeladmin=self.instructor1.__class__, \n request=req, \n queryset=Instructor.objects.all(), \n export_type=\"D\")\n \n expected_response = 'department,title,id,name,courses\\r\\n1,Capt.,1,James Kirk,\\r\\n2,Dr.,2,Peter Venkman,'\n\n self.assertContains(response, expected_response)", "def create_seed_quizzes(file_name, family, num):\n\n with open(f'{file_name}.csv', 'w') as question_csv:\n question_headers = ['url', \n 'correct_answer', \n 'wrong_answer_1', \n 'wrong_answer_2',\n 'wrong_answer_3', \n 'slug']\n question_writer = csv.DictWriter(question_csv, fieldnames=question_headers)\n question_writer.writeheader()\n\n for i in range(num):\n questions = create_quiz(family)\n if questions:\n for question in questions:\n question_writer.writerow(question)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calls get_player_id() function and loops
def start_script(team_id,start,end): for i in team_id: try: get_player_id(i,start,end) print(f'Successful : {i}') except: print(f'ERROR : {i}')
[ "def next_player(self):\n self.current_player = self.players[(self.current_player.identity.id + 1) % len(self.players)]", "def get_id(self):\n return self.__player_id", "def test_get_player(self):\n player23 = self.player_manager.get_player(3)\n self.assertEqual(3, player23.get_player_id(), \"Player should be number 23\")", "def get_player(self, player_id):\n for player in self.players:\n if player.get_id() == player_id:\n return player", "def when_to_run_func(): \n global run\n run += 1\n if run == 1:\n clean_players()\n exp_players()\n team_sel()", "def welcome_run(self):\n self.broadcast_message({'ready': True})\n print \"Waiting for all players to be ready...\"\n while not all(self.players_ready.values()):\n time.sleep(1)\n print \"...\"\n print \"Ready to play! Starting game in 3 seconds...\"\n self.all_uids = [c.their_uid for c in self.client_connections] + [self.uid]\n self.player_number = ui.uid_to_friendly(self.uid, self.all_uids)\n print \"You are player\", self.player_number\n time.sleep(3)\n self.phase += 1", "def start_play():", "def test_get_id(self):\n player1 = player.Player(1, \"Kalle\")\n exp = player1.player_id\n res = player1.get_id()\n self.assertEqual(exp, res)", "def play_again(server):\n server.player_handler.current_player = (\n server.player_handler.get_player(-server.player_handler.order))", "def next_play(board, selection, active_player):", "def increment_player(self):\n self.currentPlayer += 1\n if self.currentPlayer > self.maxPlayers:\n self.currentPlayer = 1", "def game_playing(self):", "def int_player(self):\n if self.current_player == self.first_player:\n return 0\n else:\n return 1", "def continue_game(self):\n self.game()", "def player():\n\n name_id = 1\n return card_game.Player(name_id)", "def getId(wp_page='', player_name=''):\n\n\tif player_name:\n\t\ttext = ''\n\t\ttext = searchPlayer(wp_page=wp_page, player_name=player_name)\n\n\t\tif text:\n\t\t\tsoccerway_id = re.findall(r'<td class=\"player\"><a href=\"/players/([\\/\\-\\w]*)\" class=\"[\\_\\s\\/\\-\\w]*\">.*</a></td>', text, re.IGNORECASE)\n\t\t\tsoccerway_id = soccerway_id[0].strip('/')\n\t\t\treturn soccerway_id\n\n\t\telse:\n\t\t\tprint('No player was found on the official site.\\n')\n\t\t\treturn ''\n\n\telse:\n\t\tprint('No player name is given.\\n')\n\t\treturn ''\n\n\treturn ''", "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 getPlayerForId(self, id):\n for player in self.players:\n if player.id == id:\n return player\n return None", "def skip_player(server):\n server.player_handler.next_player()" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Automatically populates the WorkerList object with the worker URLs for the GPUdb server to support multihead ingest. (If the specified GPUdb instance has multihead ingest disabled, the worker list will be empty and multihead ingest will not be used.) Note that in some cases, workers may be configured to use more than one IP address, not all of which may be accessible to the client; this constructor uses the first IP returned by the server for each worker. gpudb The GPUdb client handle from which to obtain the worker URLs. ip_regex Optional IP regular expression to match for the worker URLs.
def __init__( self, gpudb, ip_regex = "" ): # Check the input parameter type assert isinstance(gpudb, GPUdb), ("Parameter 'gpudb' must be of " "type GPUdb; given %s" % type(gpudb) ) self.worker_urls = [] # Get system properties system_prop_rsp = gpudb.show_system_properties() if system_prop_rsp[ C._info ][ C._status ] == C._error: raise ValueError( "Unable to retrieve system properties; error:" " %s" % system_prop_rsp[ C._info ][ C._msg ] ) system_properties = system_prop_rsp[ C._sys_properties ] # Is multi-head ingest enabled on the server? if C._multihead_enabled not in system_properties: raise ValueError( "Missing value for %s" % C._multihead_enabled) self.multihead_enabled = (system_properties[ C._multihead_enabled ] == C._TRUE) if not self.multihead_enabled: # Multihead ingest is not enabled. Just return the main/only ingestor self.worker_urls.append( gpudb.get_url() ) return # nothing to do # Get the worker IP addresses (per rank) if C._worker_IPs not in system_properties: raise ValueError( "Missing value for %s" % C._worker_IPs) self.worker_IPs_per_rank = system_properties[ C._worker_IPs ].split( ";" ) # Get the worker ports if C._worker_ports not in system_properties: raise ValueError( "Missing value for %s" % C._worker_ports) self.worker_ports = system_properties[ C._worker_ports ].split( ";" ) # Check that the IP and port list lengths match if (len(self.worker_IPs_per_rank) != len(self.worker_ports)): raise ValueError("Inconsistent number of values for %s and %s." % (C._worker_IPs_per_rank, C._worker_ports) ) # Process the IP addresses per rank for i in range(0, len(self.worker_IPs_per_rank)): ip_address = self.worker_IPs_per_rank[ i ] # ips_per_rank = self.worker_IPs_per_rank[ i ] found = False # Validate the IP address's syntax if not self.validate_ip_address( ip_address ): raise ValueError( "Malformed IP address: %s" % ip_address ) # Generate the URL using the IP address and the port # url = (ip_address + ":" + self.worker_ports[i]) url = ("http://" + ip_address + ":" + self.worker_ports[i]) if (ip_regex == ""): # no regex given # so, include all IP addresses self.worker_urls.append( url ) found = True else: # check for matching regex match = re.match(ip_regex, ip_address) if match: # match found self.worker_urls.append( url ) found = True # skip the rest of IP addresses for this rank continue # end found match # end if-else # if no worker found for this rank, throw exception if not found: raise ValueError("No matching IP address found for worker" "%d." % i) # end outer loop of processing worker IPs # if no worker found, throw error if not self.worker_urls: raise ValueError( "No worker HTTP servers found." )
[ "def request_register_default_worker_servers(self, req):\n for idx in range(8):\n self._server_pool.add(\"apscn{:02d}.mpifr-be.mkat.karoo.kat.ac.za\".format(idx), 6000)\n return (\"ok\",)", "def AddWorkerpoolArgs(parser, release_track, update=False):\n verb = 'update' if update else 'create'\n parser.add_argument(\n 'WORKER_POOL',\n help=(\n 'Unique identifier for the worker pool to %s. This value should be'\n ' 1-63 characters, and valid characters are [a-z][0-9]-'\n )\n % verb,\n )\n parser.add_argument(\n '--region',\n required=True,\n help=(\n 'Cloud region where the worker pool is %sd. See'\n ' https://cloud.google.com/build/docs/locations for available'\n ' locations.'\n )\n % verb,\n )\n file_or_flags = parser.add_mutually_exclusive_group(required=update)\n if release_track != base.ReleaseTrack.ALPHA:\n file_or_flags.add_argument(\n '--config-from-file',\n help=(_UPDATE_FILE_DESC if update else _CREATE_FILE_DESC),\n )\n else:\n file_or_flags.add_argument(\n '--config-from-file',\n help=(_UPDATE_FILE_DESC_ALPHA if update else _CREATE_FILE_DESC_ALPHA),\n )\n private_or_hybrid = file_or_flags.add_mutually_exclusive_group()\n private_flags = private_or_hybrid.add_argument_group(\n 'Command-line flags to configure the private pool:'\n )\n if not update:\n private_flags.add_argument(\n '--peered-network',\n help=\"\"\"\\\nExisting network to which workers are peered. The network is specified in\nresource URL format\nprojects/{network_project}/global/networks/{network_name}.\n\nIf not specified, the workers are not peered to any network.\n\"\"\",\n )\n\n if not update:\n private_flags.add_argument(\n '--peered-network-ip-range',\n help=\"\"\"\\\nAn IP range for your peered network. Specify the IP range using Classless\nInter-Domain Routing (CIDR) notation with a slash and the subnet prefix size,\nsuch as `/29`.\n\nYour subnet prefix size must be between 1 and 29. Optional: you can specify an\nIP address before the subnet prefix value - for example `192.168.0.0/24`.\n\nIf no IP address is specified, your VPC automatically determines the starting\nIP for the range. If no IP range is specified, Cloud Build uses `/24` as the\ndefault network IP range.\n\"\"\",\n )\n\n if release_track == base.ReleaseTrack.ALPHA:\n hybrid_flags = private_or_hybrid.add_argument_group(\n 'Command-line flags for creating or updating a hybrid pool:',\n hidden=True,\n )\n if not update:\n hybrid_flags.add_argument(\n '--membership',\n required=True,\n help=\"\"\"\\\n Hub member to install Cloud Build hybrid pools on.\n \"\"\",\n )\n hybrid_flags.add_argument(\n '--builder-image-caching',\n hidden=True,\n choices={\n 'CACHING_DISABLED': 'Disable image caching.',\n 'VOLUME_CACHING': (\n 'Enable image caching of Cloud Builders and Skaffold.'\n ),\n },\n default=DEFAULT_FLAG_VALUES['BUILDER_IMAGE_CACHING'],\n help=\"\"\"\\\n Controls whether the hybrid pool should cache Cloud Builders (https://cloud.google.com/build/docs/cloud-builders) and Skaffold.\n Enabling VOLUME_CACHING may signficantly shorten build execution times.\n \"\"\",\n )\n hybrid_flags.add_argument(\n '--caching-storage-class',\n hidden=True,\n type=str,\n help=\"\"\"\\\n Name of the Kubernetes StorageClass used by any PersistentVolumeClaims installed on the hybrid pool.\n If this flag is omitted, PersistentVolumeClaims are created without a spec.storageClassName field during installation.\n The name should be formatted according to http://kubernetes.io/docs/user-guide/identifiers#names.\n \"\"\",\n )\n\n worker_flags = private_flags.add_argument_group(\n 'Configuration to be used for creating workers in the worker pool:'\n )\n worker_flags.add_argument(\n '--worker-machine-type',\n help=\"\"\"\\\nCompute Engine machine type for a worker pool.\n\nIf unspecified, Cloud Build uses a standard machine type.\n\"\"\",\n )\n worker_flags.add_argument(\n '--worker-disk-size',\n type=arg_parsers.BinarySize(lower_bound='100GB'),\n help=\"\"\"\\\nSize of the disk attached to the worker.\n\nIf not given, Cloud Build will use a standard disk size.\n\"\"\",\n )\n\n if release_track == base.ReleaseTrack.GA:\n worker_flags.add_argument(\n '--no-external-ip',\n hidden=release_track == base.ReleaseTrack.GA,\n action=actions.DeprecationAction(\n '--no-external-ip',\n warn=(\n 'The `--no-external-ip` option is deprecated; use'\n ' `--no-public-egress` and/or `--public-egress instead`.'\n ),\n removed=False,\n action='store_true',\n ),\n help=\"\"\"\\\n If set, workers in the worker pool are created without an external IP address.\n\n If the worker pool is within a VPC Service Control perimeter, use this flag.\n \"\"\",\n )\n\n if release_track == base.ReleaseTrack.ALPHA:\n default_build_disk_size = (\n DEFAULT_FLAG_VALUES['DISK_SIZE'] if not update else None\n )\n hybrid_flags.add_argument(\n '--default-build-disk-size',\n type=arg_parsers.BinarySize(lower_bound='10GB', default_unit='GB'),\n default=default_build_disk_size,\n help=\"\"\"\\\n Default disk size that each build requires.\n \"\"\",\n )\n default_build_memory_gb = (\n DEFAULT_FLAG_VALUES['MEMORY'] if not update else None\n )\n hybrid_flags.add_argument(\n '--default-build-memory',\n type=arg_parsers.BinarySize(default_unit='GB'),\n default=default_build_memory_gb,\n help=\"\"\"\\\n Default memory size that each build requires.\n \"\"\",\n )\n default_build_vcpu_count = (\n DEFAULT_FLAG_VALUES['VCPU_COUNT'] if not update else None\n )\n hybrid_flags.add_argument(\n '--default-build-vcpu-count',\n type=float,\n default=default_build_vcpu_count,\n help=\"\"\"\\\n Default vcpu count that each build requires.\n \"\"\",\n )\n\n if update:\n egress_flags = private_flags.add_mutually_exclusive_group()\n egress_flags.add_argument(\n '--no-public-egress',\n action='store_true',\n help=\"\"\"\\\nIf set, workers in the worker pool are created without an external IP address.\n\nIf the worker pool is within a VPC Service Control perimeter, use this flag.\n \"\"\",\n )\n\n egress_flags.add_argument(\n '--public-egress',\n action='store_true',\n help=\"\"\"\\\nIf set, workers in the worker pool are created with an external IP address.\n\"\"\",\n )\n else:\n private_flags.add_argument(\n '--no-public-egress',\n action='store_true',\n help=\"\"\"\\\nIf set, workers in the worker pool are created without an external IP address.\n\nIf the worker pool is within a VPC Service Control perimeter, use this flag.\n\"\"\",\n )\n\n return parser", "def launch(self):\n self.proxy = ZmqProxyThread(in_add=self.serving_frontend_add,\n out_add=self.serving_backend_add,\n pattern='router-dealer')\n self.proxy.start()\n\n self.workers = []\n for i in range(self.shards):\n worker = ParameterServer(\n publisher_host=self.publisher_host,\n publisher_port=self.publisher_port,\n serving_host='localhost',\n serving_port=self.backend_port,\n load_balanced=True,\n )\n worker.start()\n self.workers.append(worker)", "def __init__(self, **kwargs):\n return super(DjangoGearmanWorker, self).__init__(\n settings.GEARMAN_SERVERS, **kwargs)", "def split_by_worker(urls, env=None):\n env = env or get_worker_environment()\n urls = [url for url in urls]\n assert isinstance(urls, list)\n gopen.info[\"worker_id\"] = env.worker\n gopen.info[\"num_workers\"] = env.nworkers\n if too_few_shards_warning and env.worker == 0 and len(urls) < env.nworkers:\n warnings.warn(f\"num_workers {env.nworkers} > num_shards {len(urls)}\")\n return urls[env.worker :: env.nworkers]", "def _AddSearchServers(dbroot,\n search_def_list,\n search_tab_id,\n supplemental_search_label,\n supplemental_search_url,\n log):\n if not search_def_list:\n search_server = dbroot.end_snippet.search_config.search_server.add()\n search_server.name.value = \"\"\n search_server.url.value = \"about:blank\"\n search_server.html_transform_url.value = \"about:blank\"\n search_server.kml_transform_url.value = \"about:blank\"\n search_server.suggest_server.value = \"about:blank\"\n return\n\n log.debug(\"_AddSearchServers()...\")\n for search_def in search_def_list:\n log.debug(\"Configure search server: %s\", search_def.label)\n search_server = dbroot.end_snippet.search_config.search_server.add()\n search_server.name.value = (\n \"%s [%s]\" % (\n search_def.label,\n search_tab_id) if search_tab_id else search_def.label)\n search_server.url.value = search_def.service_url\n\n # Building query string and appending to search server URL.\n add_query = search_def.additional_query_param\n add_config = search_def.additional_config_param\n query_string = None\n if add_query:\n query_string = (\"%s&%s\" % (\n query_string, add_query) if query_string else add_query)\n\n if add_config:\n query_string = (\"%s&%s\" % (\n query_string, add_config) if query_string else add_config)\n\n if query_string:\n search_server.url.value = \"%s?%s\" % (search_server.url.value,\n query_string)\n\n if search_def.fields and search_def.fields[0].suggestion:\n suggestion = search_server.suggestion.add()\n suggestion.value = search_def.fields[0].suggestion\n\n # Write 'html_transform_url' value to dbroot file.\n search_server.html_transform_url.value = search_def.html_transform_url\n\n # Write 'kml_transform_url' value to dbroot file.\n search_server.kml_transform_url.value = search_def.kml_transform_url\n\n # Write 'suggest_server' value to dbroot file.\n search_server.suggest_server.value = search_def.suggest_server\n\n # Write 'result_type' to dbroot file.\n if search_def.result_type == \"XML\":\n search_server.type = ResultType.RESULT_TYPE_XML\n\n # Set supplemental UI properties.\n if supplemental_search_label:\n search_server.supplemental_ui.url.value = supplemental_search_url\n search_server.supplemental_ui.label.value = supplemental_search_label\n\n log.debug(\"_AddSearchServers() done.\")", "def __init__(self, addresses: List[str], graph_maker: Callable[[Device, tf.Session], T]) -> None:\n self.cluster = tf.train.ClusterSpec({\"worker\": addresses})\n self.population = []\n for task_index in range(len(addresses)):\n device = '/job:worker/task:' + str(task_index)\n server = tf.train.Server(self.cluster, job_name=\"worker\", task_index=task_index)\n sess = tf.Session(server.target)\n self.population.append(graph_maker(device, sess))", "def __init_pool(self, pool_size):\n for _ in xrange(int(pool_size)):\n self.pool.append(WorkingStation())", "def initialize_workers(self):\n # Create pipes as communicators between master and workers\n self.master_conns, self.worker_conns = zip(*[Pipe() for _ in range(self.num_worker)])\n \n # Create a Process for each worker\n self.list_process = [Process(target=self.worker_class(), # individual instantiation for each Process\n args=[master_conn, worker_conn], \n daemon=self.daemonic_worker) \n for master_conn, worker_conn in zip(self.master_conns, self.worker_conns)]\n \n # Start (fork) all processes, so all workers are stand by waiting for master's command to work\n # Note that Linux OS will fork all connection terminals, so it's good to close unused ones here.\n [process.start() for process in self.list_process]\n \n # Close all worker connections here as they are not used in master process\n # Note that this should come after all the processes started\n [worker_conn.close() for worker_conn in self.worker_conns]", "def list_floating_ip_pools():\n return IMPL.list_floating_ip_pools()", "def parallel_fetch(urllist: list, \n nodelist: list, \n cores: int,\n username: str, \n password:str):\n \n flatten_metrics = []\n try:\n # Partition\n urls_group = partition(urllist, cores)\n nodes_group = partition(nodelist, cores)\n\n fetch_args = []\n for i in range(cores):\n urls = urls_group[i]\n nodes = nodes_group[i]\n fetch_args.append((urls, nodes, username, password))\n\n with multiprocessing.Pool() as pool:\n metrics = pool.starmap(fetch, fetch_args)\n\n flatten_metrics = [item for sublist in metrics for item in sublist]\n except Exception as err:\n log.error(f\"Cannot parallel fetch data from idrac urls: {err}\")\n\n return flatten_metrics", "def run_multiproccesing():\n\n print('--- Multiprocessing ---')\n with Pool(5) as executor:\n return list(executor.map(load_url, URLS))", "def get_worker_urls( self ):\n return self.worker_urls", "def allocate_worker(self):\n # Allocate DOWNPOUR worker.\n worker = DOWNPOURWorker(self.master_model, self.worker_optimizer, self.loss, self.loss_weights, self.metrics,\n self.features_column, self.label_column, self.batch_size, self.num_epoch,\n self.master_host, self.master_port, self.communication_window)\n\n return worker", "def __init__(self, ip, port, capture_interface, numa_node, exec_mode=FULL):\n self._dc_ip = None\n self._dc_port = None\n self._delay_client = None\n self._delays = None\n self._numa = numa_node\n self._exec_mode = exec_mode\n self._dada_input_key = \"dada\"\n self._dada_coh_output_key = \"caca\"\n self._dada_incoh_output_key = \"baba\"\n self._capture_interface = capture_interface\n self._capture_monitor = None\n self._autoscaling_key = \"autoscaling_trigger\"\n self._autoscaling_trigger = AutoscalingTrigger(\n key=self._autoscaling_key)\n self._output_level = 10.0\n self._partition_bandwidth = None\n self._centre_frequency = None\n self._transient_buffer = None\n self._feng_config = None\n self._tb_params = {}\n\n super(FbfWorkerServer, self).__init__(ip, port)", "def _init_workers(self):\n self._shared_map = {}\n self._workers = []\n self._medias_queue = six.moves.queue.Queue()\n for _ in six.moves.range(self.jobs):\n worker = InstaDownloader(self)\n worker.start()\n self._workers.append(worker)", "def update_proxy_pool(self):\n proxy_list = []\n try:\n resp = requests.get(self.url)\n except ConnectionError as ce:\n print(ce)\n return(1)\n soup = bs(resp.text, \"html.parser\")\n proxy_table = soup.find_all(id='proxylisttable')\n for tr in proxy_table[0].find_all('tbody')[0].find_all('tr'):\n td = tr.find_all('td')\n proxy_list.append({\n 'ip': td[0].text,\n 'port': td[1].text,\n 'anonymity': td[4].text.upper(),\n 'https': td[6].text\n })\n self._data_frame = pd.DataFrame(proxy_list)", "def __init__ (self, *funcs_workers):\n self.numpools = len(funcs_workers)\n self.numworkerslist = []\n #self.pools = [[] for _ in xrange(numpools)]\n self.queues = [Queue.Queue() for _ in xrange(self.numpools + 1)]\n for i, (func, numworkers) in enumerate(funcs_workers):\n self.numworkerslist.append(numworkers)\n for _ in xrange(numworkers):\n t = threading.Thread(target=worker, args=(\n func, self.queues[i], self.queues[i+1]\n ))\n #t.daemon = True # unnecessary\n t.start()\n #self.pools[i].append(t)", "def __init__(self,\n pools: List['LoadBalancerPool']) -> None:\n self.pools = pools" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a list of the URLs for the GPUdb workers.
def get_worker_urls( self ): return self.worker_urls
[ "def workers(self):\n return self._wrap_get('/workers')", "def get_workers(self):\n with self._engine.begin() as conn:\n worker_rows = conn.execute(\n select([cl_worker, cl_worker_dependency.c.dependencies]).select_from(\n cl_worker.outerjoin(\n cl_worker_dependency,\n cl_worker.c.worker_id == cl_worker_dependency.c.worker_id,\n )\n )\n ).fetchall()\n worker_run_rows = conn.execute(cl_worker_run.select()).fetchall()\n\n worker_dict = {\n (row.user_id, row.worker_id): {\n 'user_id': row.user_id,\n 'worker_id': row.worker_id,\n 'group_uuid': row.group_uuid,\n 'tag': row.tag,\n 'cpus': row.cpus,\n 'gpus': row.gpus,\n 'memory_bytes': row.memory_bytes,\n 'free_disk_bytes': row.free_disk_bytes,\n 'checkin_time': row.checkin_time,\n 'socket_id': row.socket_id,\n # run_uuids will be set later\n 'run_uuids': [],\n 'dependencies': row.dependencies\n and self._deserialize_dependencies(row.dependencies),\n 'shared_file_system': row.shared_file_system,\n 'tag_exclusive': row.tag_exclusive,\n 'exit_after_num_runs': row.exit_after_num_runs,\n 'is_terminating': row.is_terminating,\n 'preemptible': row.preemptible,\n }\n for row in worker_rows\n }\n for row in worker_run_rows:\n worker_dict[(row.user_id, row.worker_id)]['run_uuids'].append(row.run_uuid)\n return list(worker_dict.values())", "def get_workers(self):\n r = requests.get(self.get_url()+ \"/workers\", auth=self.auth)\n return self._process_response(r)", "def get_workers_from_database():\n return [unicode(w) for w in _worker_state_cache.data]", "def get_all_worker_infos():\n return core.rpc_get_all_worker_infos()", "def workers(self) -> WorkerManager:\n return self.app.workers", "def urls(self) -> List[str]:\n return self.default_storage_location.urls", "def workers(self):\n # type: () -> Dict\n return self.__workers", "def get_host_list(self):", "def workers(self):\n return self.instance.get_task_workers(self.name)", "async def get_api_urls(self):\n \n if self.google_dev_query or self.google_games_query:\n cx_broad1 = self.cx1\n cx_broad2 = self.cx2\n cx_broad3 = self.cx3\n cx_broad4 = self.cx4\n cx_broad5 = self.cx5\n\n if self.google_dev_query or self.google_games_query:\n google_query = await self.database_fetches()\n # Proprietary\n\n \n if self.fetch_dev_games:\n dev_slugs = await self.database_fetches()\n # Proprietary\n\n if self.api_fetch_bool:\n # Proprietary\n\n if self.database_query_bool:\n # Proprietary", "def urls():\n projects = ccmenu.preferences.read().get(\"Projects\",[])\n return list(sorted(map(lambda p:p[\"serverUrl\"],projects)))", "def list_floating_ip_pools():\n return IMPL.list_floating_ip_pools()", "def split_by_worker(urls, env=None):\n env = env or get_worker_environment()\n urls = [url for url in urls]\n assert isinstance(urls, list)\n gopen.info[\"worker_id\"] = env.worker\n gopen.info[\"num_workers\"] = env.nworkers\n if too_few_shards_warning and env.worker == 0 and len(urls) < env.nworkers:\n warnings.warn(f\"num_workers {env.nworkers} > num_shards {len(urls)}\")\n return urls[env.worker :: env.nworkers]", "def data_urls(self):\n return [dinfo.data_url for dinfo in self.datainfo]", "def network_paths(self):\n return self.conn_info.network_paths", "def get_admin_urls_for_registration(self):\n urls = ()\n for instance in self.modeladmin_instances:\n urls += instance.get_admin_urls_for_registration()\n return urls", "def __init__( self, gpudb, ip_regex = \"\" ):\n # Check the input parameter type\n assert isinstance(gpudb, GPUdb), (\"Parameter 'gpudb' must be of \"\n \"type GPUdb; given %s\"\n % type(gpudb) )\n\n self.worker_urls = []\n\n # Get system properties\n system_prop_rsp = gpudb.show_system_properties()\n if system_prop_rsp[ C._info ][ C._status ] == C._error:\n raise ValueError( \"Unable to retrieve system properties; error:\"\n \" %s\" % system_prop_rsp[ C._info ][ C._msg ] )\n\n system_properties = system_prop_rsp[ C._sys_properties ]\n\n # Is multi-head ingest enabled on the server?\n if C._multihead_enabled not in system_properties:\n raise ValueError( \"Missing value for %s\" % C._multihead_enabled)\n\n self.multihead_enabled = (system_properties[ C._multihead_enabled ] == C._TRUE)\n if not self.multihead_enabled:\n # Multihead ingest is not enabled. Just return the main/only ingestor\n self.worker_urls.append( gpudb.get_url() )\n return # nothing to do\n\n # Get the worker IP addresses (per rank)\n if C._worker_IPs not in system_properties:\n raise ValueError( \"Missing value for %s\" % C._worker_IPs)\n\n self.worker_IPs_per_rank = system_properties[ C._worker_IPs ].split( \";\" )\n\n # Get the worker ports\n if C._worker_ports not in system_properties:\n raise ValueError( \"Missing value for %s\" % C._worker_ports)\n\n self.worker_ports = system_properties[ C._worker_ports ].split( \";\" )\n\n # Check that the IP and port list lengths match\n if (len(self.worker_IPs_per_rank) != len(self.worker_ports)):\n raise ValueError(\"Inconsistent number of values for %s and %s.\"\n % (C._worker_IPs_per_rank, C._worker_ports) )\n\n # Process the IP addresses per rank\n for i in range(0, len(self.worker_IPs_per_rank)):\n ip_address = self.worker_IPs_per_rank[ i ]\n # ips_per_rank = self.worker_IPs_per_rank[ i ]\n found = False\n\n # Validate the IP address's syntax\n if not self.validate_ip_address( ip_address ):\n raise ValueError( \"Malformed IP address: %s\" % ip_address )\n\n # Generate the URL using the IP address and the port\n # url = (ip_address + \":\" + self.worker_ports[i])\n url = (\"http://\" + ip_address + \":\" + self.worker_ports[i])\n\n if (ip_regex == \"\"): # no regex given\n # so, include all IP addresses\n self.worker_urls.append( url )\n found = True\n else: # check for matching regex\n match = re.match(ip_regex, ip_address)\n if match: # match found\n self.worker_urls.append( url )\n found = True\n # skip the rest of IP addresses for this rank\n continue\n # end found match\n # end if-else\n\n # if no worker found for this rank, throw exception\n if not found:\n raise ValueError(\"No matching IP address found for worker\"\n \"%d.\" % i)\n # end outer loop of processing worker IPs\n\n # if no worker found, throw error\n if not self.worker_urls:\n raise ValueError( \"No worker HTTP servers found.\" )", "def ListBackends():\n return _backends.itervalues()" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds some characters to the record key byte array.
def add_char( self, value ): self.buffer_value.append( bytearray( value ) )
[ "def encode(message, key):\n encoded_message = ''\n print('encoding message...')\n\n for letter in message:\n letter_num = (ord(letter) * key - 32) % Cipher.alphabet_size\n encoded_message += Cipher.alphabet[letter_num]\n return encoded_message", "def extend_key(message, key):\n ext_key = ''\n for pair in itertools.zip_longest(message, itertools.cycle(key)):\n if pair[0] is None: break\n ext_key += pair[1]\n return ext_key", "async def addkey(cls, character, key_name, key_level):\n session = Session()\n character.m_plus_key = key_name\n character.m_plus_key_level = key_level\n try:\n session.add(character)\n session.commit()\n except Exception as e:\n print('An error occurred when adding a key:\\n{e}')\n session.rollback()\n finally:\n session.close()", "def as_bin_str(self):\n return \"\".join(format(b, \"0>8b\") for b in six.iterbytes(self.key))", "def _set_key(self, key, hexkey=False):\n self.key = self.converter.to_bin(key, hexkey)", "def store3270(self, char ):\n\t\tself.tn_buffer += char", "def bytes_key(string):\n return key_to_bytes(key(string))", "def addAlpha(self, char):\n self._alphabet[char] = True", "def addChar(self, *args):\r\n return _osgDB.Field_addChar(self, *args)", "def key_str(self, key):\n res = ''\n tmp = binascii.hexlify(key)\n for i, x in enumerate(tmp):\n if i > 0 and i % 2 == 0:\n res += ':'\n res += x\n return res", "def add(self, key: int, assyrec: AssembleRecord):\n self.entries[key] = assyrec", "def AddKey(self, *args):\n return _snap.TIntStrH_AddKey(self, *args)", "def __init__(self, key):\n # self.key = key.decode(\"hex\") # Python 2\n self.key = bytes.fromhex(key)", "def add_string( self, value ):\n string_hash = mmh3.hash_bytes( value )\n self.buffer_value.append( bytearray( string_hash ) )", "def _prepare_key(self, key: bytes):\n if len(key) * 8 > self.hash_class.block_size:\n key = self.hash_class(key).bytes\n\n return Bits(key.ljust(self.hash_class.block_size // 8, b'\\x00'))", "def generate_binary_key(length):\n key = [str(random.randint(0,1)) for x in range(length)]\n return \"\".join(key)", "def key( self, digram ):\n\t\ta,b = digram.refdigram()\n\t\treturn str( a ) + self.keyseparator + str( b )", "def add_key(self, key):\n if key > self._header.eieio_type.max_value:\n raise SpinnmanInvalidParameterException(\n \"key\", key,\n \"Larger than the maximum allowed of {}\".format(\n self._header.eieio_type.max_value))\n self.add_element(KeyDataElement(key))", "def safeappend(self, key, item):\n ..." ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds numeric value to the record key byte array.
def add_number( self, value ): self.buffer_value.append( bytearray( value ) )
[ "def add(self, key, value):\n\n assert isinstance(key, bytes_type)\n assert isinstance(value, bytes_type)\n\n dbfile = self.dbfile\n pos = dbfile.tell()\n dbfile.write(_lengths.pack(len(key), len(value)))\n dbfile.write(key)\n dbfile.write(value)\n\n # Get hash value for the key\n h = self.hashfn(key)\n # Add hash and on-disk position to appropriate bucket\n self.buckets[h & 255].append((h, pos))", "def add(self, key: int, assyrec: AssembleRecord):\n self.entries[key] = assyrec", "def Incr(self,key):\n if key in self.data:\n self.data[key]+=1\n else:\n self.data[key]=1", "def add_key(self, key):\n if key > self._header.eieio_type.max_value:\n raise SpinnmanInvalidParameterException(\n \"key\", key,\n \"Larger than the maximum allowed of {}\".format(\n self._header.eieio_type.max_value))\n self.add_element(KeyDataElement(key))", "def AddKey(self, *args):\n return _snap.TIntSet_AddKey(self, *args)", "def AddKey(self, *args):\n return _snap.TIntStrH_AddKey(self, *args)", "def add_char( self, value ):\n self.buffer_value.append( bytearray( value ) )", "def add(self, key, N=1):\n assert isinstance(key, str)\n for index in self.get_indexes(key):\n self.num_non_zero += (self.data[index] == 0)\n self.data[index] += N", "def AddKeyV(self, *args):\n return _snap.TIntSet_AddKeyV(self, *args)", "def add(self, key, value):\n log.debug(f\"key: {key} value: {value}\")\n log.debug(f\"key type: {type(key)} value type: {type(value)}\")\n # if it's a list then we serialize to json string format so we can load it back later\n if isinstance(value, list) or isinstance(value, dict):\n self.report[key] = json.dumps(value)\n elif isinstance(value, np.ndarray):\n self.report[key] = json.dumps(value.tolist())\n else:\n self.report[key] = value", "def AddKey(self, *args):\n return _snap.TIntFltH_AddKey(self, *args)", "def add(self, key, value):\n self.__dataset[key] = value", "def add_string( self, value ):\n string_hash = mmh3.hash_bytes( value )\n self.buffer_value.append( bytearray( string_hash ) )", "def insert(self, key, value):\n h = hashlib.sha256(key)\n index = int(h.hexdigest(), 16) % 10000\n self.hash_table[index].append([key, value])", "def AddKey(self, key, data=[], index=-1):\n\n # Default index simply appends\n if index == -1:\n index = len(self.header)\n\n self.header.insert(index, key)\n\n # Loop over data\n for i, item in enumerate(self.data):\n\n # Check value types\n if not data or type(data) != list:\n element = data\n else:\n element = data[i]\n\n # Add element at corresponding key\n self.data[i][key] = element", "def pack(self, key, value):\n return value", "def _set_key(self, key, hexkey=False):\n self.key = self.converter.to_bin(key, hexkey)", "def add_byte(self, value):\n if isinstance(value, int):\n if value < 0 or value > 255:\n raise Exception(\"byte overflow: invaid value of {}\".format(value))\n self._data += value.to_bytes(1, byteorder=\"little\")\n else:\n if isinstance(value, str):\n value = value.encode(\"utf-8\")\n elif not isinstance(value, (bytes, bytearray)):\n raise Exception(\"value of type {} cannot be added as a single byte\".format(type(value)))\n if len(value) != 1:\n raise Exception(\"a single byte has to be accepted, amount of bytes given: {}\".format(len(value)))\n self._data += value", "def add(self, key, value): # 3\r\n self._data.append(self._Item(key, value))\r\n self._upheap(len(self._data) - 1) # upheap newly added position\r" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds a string to the record key byte array.
def add_string( self, value ): string_hash = mmh3.hash_bytes( value ) self.buffer_value.append( bytearray( string_hash ) )
[ "def bytes_key(string):\n return key_to_bytes(key(string))", "def AddKey(self, *args):\n return _snap.TIntStrH_AddKey(self, *args)", "def add(self, key: int, assyrec: AssembleRecord):\n self.entries[key] = assyrec", "async def add_key_for_did(self, did: str, key: str):\n record = StorageRecord(\n DIDXManager.RECORD_TYPE_DID_KEY, key, {\"did\": did, \"key\": key}\n )\n storage = self._session.inject(BaseStorage)\n await storage.add_record(record)", "def add(self, key, value):\n\n assert isinstance(key, bytes_type)\n assert isinstance(value, bytes_type)\n\n dbfile = self.dbfile\n pos = dbfile.tell()\n dbfile.write(_lengths.pack(len(key), len(value)))\n dbfile.write(key)\n dbfile.write(value)\n\n # Get hash value for the key\n h = self.hashfn(key)\n # Add hash and on-disk position to appropriate bucket\n self.buckets[h & 255].append((h, pos))", "def set_string_object(bucket, key, string_data):\n ObjectStore.set_object(bucket, key,\n string_data.encode(\"utf-8\"))", "async def addkey(cls, character, key_name, key_level):\n session = Session()\n character.m_plus_key = key_name\n character.m_plus_key_level = key_level\n try:\n session.add(character)\n session.commit()\n except Exception as e:\n print('An error occurred when adding a key:\\n{e}')\n session.rollback()\n finally:\n session.close()", "def append(self, binaryString, attributeMap2=None):\n if self.usedBufferSize > len(self.buffer):\n # unused data must be removed\n object.__setattr__(self, \"buffer\", self.buffer[:self.usedBufferSize])\n if type(binaryString) == ARRAY_TYPE:\n self.buffer.extend(binaryString)\n elif type(binaryString) == STRING_TYPE:\n self.buffer.extend(array.array(\"B\", binaryString.encode()))\n else:\n self.buffer.extend(array.array(\"B\", binaryString))\n object.__setattr__(self, \"usedBufferSize\", len(self.buffer))\n if attributeMap2 != None:\n object.__setattr__(self, \"attributeMap2\", attributeMap2)", "def append_data(self, key: str, data):\n self.__storage[key] = data", "def store_from_string(self, name, string):\n k = boto.s3.key.Key(self.bucket)\n k.key = self.key_for_name(name)\n k.set_contents_from_string(string)", "def add_key(self, key):\n if key > self._header.eieio_type.max_value:\n raise SpinnmanInvalidParameterException(\n \"key\", key,\n \"Larger than the maximum allowed of {}\".format(\n self._header.eieio_type.max_value))\n self.add_element(KeyDataElement(key))", "def AddKey(self, key, data=[], index=-1):\n\n # Default index simply appends\n if index == -1:\n index = len(self.header)\n\n self.header.insert(index, key)\n\n # Loop over data\n for i, item in enumerate(self.data):\n\n # Check value types\n if not data or type(data) != list:\n element = data\n else:\n element = data[i]\n\n # Add element at corresponding key\n self.data[i][key] = element", "def AddKey(self, *args):\n return _snap.TIntSet_AddKey(self, *args)", "def add_char( self, value ):\n self.buffer_value.append( bytearray( value ) )", "def safeappend(self, key, item):\n ...", "def add_bytes(self, data: bytes) -> Variable:\n index = len(self.data)\n key = f\"raw-data-{index}\"\n val = Variable(key, types.string_lit)\n val.global_offset = DataReference(key)\n self.data_identifiers[key] = index\n self.data.append(data)\n return val", "def add_blob(self, key: str, content: bytes, allow_overwrite: bool = True) -> None:\n if isinstance(content, str):\n warnings.warn(\"received a string, but expect bytes\", DeprecationWarning)\n content = content.encode(\"utf-8\")\n if key in self._blobs and not allow_overwrite:\n raise Exception(\"Key %s already stored in blobs\" % key)\n self._blobs[key] = content", "def append(self, string: str) -> None:\n self._data.append(string)", "def as_bin_str(self):\n return \"\".join(format(b, \"0>8b\") for b in six.iterbytes(self.key))" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a routing table, return the rank of the GPUdb server that this record key should be routed to. routing_table A list of integers... the rank of the GPUdb server that this record key should be routed to.
def route( self, routing_table ): routing_index = ((self.routing % len(routing_table) ) - 1) return routing_table[ routing_index ]
[ "def convert_routing_table_entry_to_spinnaker_route(routing_table_entry):\n route_entry = 0\n for processor_id in routing_table_entry.processor_ids:\n if processor_id >= Router.MAX_CORES_PER_ROUTER or processor_id < 0:\n raise SpinnMachineInvalidParameterException(\n \"route.processor_ids\",\n str(routing_table_entry.processor_ids),\n \"Processor IDs must be between 0 and \" +\n str(Router.MAX_CORES_PER_ROUTER - 1))\n route_entry |= (1 << (Router.MAX_LINKS_PER_ROUTER + processor_id))\n for link_id in routing_table_entry.link_ids:\n if link_id >= Router.MAX_LINKS_PER_ROUTER or link_id < 0:\n raise SpinnMachineInvalidParameterException(\n \"route.link_ids\", str(routing_table_entry.link_ids),\n \"Link IDs must be between 0 and \" +\n str(Router.MAX_LINKS_PER_ROUTER - 1))\n route_entry |= (1 << link_id)\n return route_entry", "def transit_gateway_route_table_id(self) -> pulumi.Input[str]:\n return pulumi.get(self, \"transit_gateway_route_table_id\")", "def transit_gateway_route_table_id(self) -> pulumi.Output[str]:\n return pulumi.get(self, \"transit_gateway_route_table_id\")", "def _route_match(self, vlan, ip_dst):\n return self.fib_table.match(vlan=vlan, eth_type=self.ETH_TYPE, nw_dst=ip_dst)", "def get_route_table(_ctx=ctx):\n return _ctx.node.properties.get('route_table_name') or \\\n get_ancestor_name(\n _ctx.instance, constants.REL_CONTAINED_IN_RT)", "def RoutingTable(self, instance):\n parsedRoutes = []\n instanceName = \"master\"\n if instance : \n instanceName = instance.Name\n # get route table size\n routeTableSize = self.RouteTableSize(instance)\n if routeTableSize > self._maxRouteTableEntries :\n # query only default route \n cmd = \"show route 0.0.0.0 inet.0\"\n if instanceName.lower() != \"master\" : cmd = \"show route 0.0.0.0 table {0}.inet.0\".format(instance.Name)\n else:\n # query inet.0 route table for the requested instance\n cmd = \"show route table inet.0\"\n if instanceName.lower() != \"master\" : cmd = \"show route table {0}.inet.0\".format(instance.Name)\n \n routes = Session.ExecCommand(cmd)\n # define regex expressions for logical text blocks\n networkBlockFilter = re.compile(r\"\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b\\/\\d{1,2}\")\n protocolBlockFilter = re.compile(r\"[*[](.*?)\\]\")\n # network blocks are the top level blocks of the text output, get the iterator for them\n networkBlockIterator = tuple(networkBlockFilter.finditer(routes))\n networkMatchcount = len(networkBlockIterator)\n networkMatchIndex = 0\n # iterate through the network blocks\n for thisNetworkMatch in networkBlockIterator:\n try:\n # thisNetworkMatch is now a MatchObject\n thisNetwork = thisNetworkMatch.group(0)\n # a route block is the text of routes between the position of this match start and the next match start\n routeBlockStart = thisNetworkMatch.start()\n routeBlockEnd = -1\n if (networkMatchIndex == networkMatchcount - 1):\n routeBlockEnd = len(routes)\n else:\n routeBlockEnd = networkBlockIterator[networkMatchIndex + 1].start()\n \n thisRouteBlock = routes[routeBlockStart : routeBlockEnd] \n # protocol blocks appear inside a network block, get the iterator for them\n protocolBlockIterator = tuple(protocolBlockFilter.finditer(thisRouteBlock))\n # process networks\n protocolMatchcount = len(protocolBlockIterator)\n protocolMatchIndex = 0\n # iterte through the protocol blocks\n for thisProtocolMatch in protocolBlockIterator:\n try:\n # thisProtocolMatch is now a MatchObject\n protocolBlockHeader = thisProtocolMatch.group(0)\n isBestRoute = \"*[\" in protocolBlockHeader\n protocolBlockStart = thisProtocolMatch.start()\n # a protocol block is the text portion in actual routeBlock between the position of this match start and the next match start\n protocolBlockStart = thisProtocolMatch.start()\n protocolBlockEnd = -1\n if (protocolMatchIndex == protocolMatchcount - 1):\n protocolBlockEnd = len(thisRouteBlock)\n else:\n protocolBlockEnd = protocolBlockIterator[protocolMatchIndex + 1].start() \n \n thisProtocolBlock = thisRouteBlock[protocolBlockStart : protocolBlockEnd]\n thisProtocolNames = re.findall(r\"[a-zA-Z,-]+\", protocolBlockHeader)\n nextHopAddresses = re.findall(r\"(?<=to )[\\d\\.]{0,99}\", thisProtocolBlock, re.IGNORECASE)\n routeTags = re.findall(r\"(?<=tag )[\\d\\.]{0,99}\", thisProtocolBlock, re.IGNORECASE)\n asPath = re.findall(r\"(?<=AS path:).[^,]*\",thisProtocolBlock, re.IGNORECASE)\n outInterfaces = re.findall(r\"(?<=via ).*\", thisProtocolBlock, re.IGNORECASE)\n leartFrom = re.findall(r\"(?<=from )[\\d\\.]{0,99}\", thisProtocolBlock, re.IGNORECASE)\n routePreference = re.findall(r\"[0-9]+\", protocolBlockHeader)\n \n matchIndex = 0\n for thisOutInterface in outInterfaces:\n rte = L3Discovery.RouteTableEntry()\n # Protocol\n if len(thisProtocolNames) == 1 : rte.Protocol = thisProtocolNames[0]\n else : rte.Protocol = \"UNKNOWN\"\n # RouterID\n rte.RouterID = self._ridCalculator.GetRouterID(rte.Protocol, instance)\n # Prefix and Mask length\n prefixAndMask = thisNetwork.split(\"/\")\n rte.Prefix = prefixAndMask[0]\n rte.MaskLength = int(prefixAndMask[1])\n # OutInterface\n rte.OutInterface = thisOutInterface\n # NextHop address\n if len(nextHopAddresses) > matchIndex : rte.NextHop = nextHopAddresses[matchIndex]\n else : rte.NextHop = \"\"\n # LeartFrom\n if len(leartFrom) == 1 : rte.From = leartFrom[0]\n else : rte.From = \"\"\n # Prefix parameters\n rte.Best = isBestRoute\n if len(routeTags) == 1 : rte.Tag = routeTags[0]\n else : rte.Tag = \"\"\n if len(routePreference) == 1 : rte.AD = routePreference[0]\n else : rte.AD = \"\"\n if len(asPath) == 1 : rte.ASPath = asPath[0]\n else : rte.ASPath = \"\"\n rte.Community = \"\"\n rte.Metric = \"\"\n parsedRoutes.Add(rte)\n matchIndex += 1\n \n protocolMatchIndex += 1\n except Exception as Ex:\n message = \"JunOS Router Module Error : could not parse a route table Protocol block because : \" + str(Ex)\n DebugEx.WriteLine(message) \n \n networkMatchIndex += 1\n except Exception as Ex:\n message = \"JunOS Router Module Error : could not parse a route table Network block because : \" + str(Ex)\n DebugEx.WriteLine(message)\n \n return parsedRoutes", "def routing_table(ip, community, ci):\n ipRouteType = \"1.3.6.1.2.1.4.21.1.8\"\n ret = get_bulk(ip, ipRouteType, community)\n if ret != None:\n for r in ret:\n for name, val in r:\n ip = name.prettyPrint()[len(\"SNMPv2-SMI::mib-2.4.21.1.8.\"):]\n route_type = int(val.prettyPrint())\n\n # indirect(4)\n if route_type == 4:\n discovery_info.add_ip(ip)\n\n new_ci = ConfigurationItem.ConfigurationItem()\n new_ci.add_ipv4_address(ip)\n mac = discovery_info.get_mac_from_ip(ip)\n if mac != None:\n ci.set_mac_address(mac)\n\n rel_type = methods.add_rel_type(\n RelationshipType.RelationshipType(\"route to\"))\n rel_obj_1 = methods.create_relation(ci, new_ci, rel_type)\n rel_obj_1.set_title(str(ci.get_title()) +\n \" route to \" + str(new_ci.get_title()))\n\n rel_obj_2 = methods.create_relation(new_ci, ci, rel_type)\n rel_obj_2.set_title(str(new_ci.get_title()) + \" route to \" +\n str(ci.get_title()))\n\n methods.add_ci(new_ci)\n methods.add_rel(rel_obj_1)\n methods.add_rel(rel_obj_2)\n\n # direct(3)\n elif route_type == 3:\n ci.add_ipv4_address(ip)\n # discovery_info.add_ip(ip)", "def associate_route_table(DryRun=None, SubnetId=None, RouteTableId=None):\n pass", "def routing_tables(self):\n return self._routing_tables_by_chip.values()", "def _get_host_device_rank_relation(self):\n rank_table_file_path = self._get_rank_table_file_path()\n if not os.path.exists(rank_table_file_path):\n log.error('Did not find rank table file under %s', self._cluster_profiler_dir)\n raise ProfilerFileNotFoundException(msg='Did not find rank table file')\n with open(rank_table_file_path, 'r', encoding='utf-8') as file:\n try:\n relation_info = json.load(file)\n except json.JSONDecodeError as err:\n log.exception(err)\n host_device_rank_relation = list()\n servers_info = relation_info.get(\"server_list\")\n for server_info in servers_info:\n server_id = server_info.get(\"server_id\")\n devices_info = server_info.get(\"device\")\n for device_info in devices_info:\n device_id = device_info.get(\"device_id\")\n rank_id = device_info.get(\"rank_id\")\n host_device_rank_relation.append([server_id, device_id, rank_id])\n\n host_ips_mapping_info = self._get_host_ips_mapping_info()\n for item in host_device_rank_relation:\n # host_ip_index:0,host_mapping_id_index:1\n target_info = [i for i in host_ips_mapping_info if item[0] == i[0]]\n # target_info is like:[[host_ip, host_mapping_ip]]\n item[0] = target_info[0][1]\n\n return host_device_rank_relation", "def list_tgw_routetable():\n client = boto3.client(\"ec2\")\n tgw_table = list()\n\n try:\n tables = client.describe_transit_gateway_route_tables()\n\n for table in tables[\"TransitGatewayRouteTables\"]:\n #tgw_table_name = (table[\"Tags\"][2].get(\"Value\"))\n tgw_table.append(table[\"TransitGatewayRouteTableId\"])\n\n except botocore.exceptionsClientError as error:\n print(error)\n\n return tgw_table", "def routing_id(self) -> RoutingID:\n return self._routing_id", "def RouteTableSize(self, instance):\n instanceName = \"master\"\n if instance : \n instanceName = instance.Name\n routeTableSize = -1\n cmd = \"show route summary table inet.0\"\n if instanceName.lower() != \"master\" : \n cmd = \"show route summary table {0}.inet.0\".format(instance.Name)\n routeSummary = Session.ExecCommand(cmd)\n re_destinationCount = re.findall(r\"\\d+(?= destinations)\", routeSummary)\n if len(re_destinationCount) > 0:\n routeTableSize = int(re_destinationCount[0].strip())\n return routeTableSize", "def extract_ir_grid_points(grid_mapping_table):\n dtype = grid_mapping_table.dtype\n ir_grid_points = np.array(np.unique(grid_mapping_table), dtype=dtype)\n weights = np.zeros_like(grid_mapping_table)\n for i, gp in enumerate(grid_mapping_table):\n weights[gp] += 1\n ir_weights = np.array(weights[ir_grid_points], dtype=dtype)\n\n return ir_grid_points, ir_weights", "def print_routing_table(self):\n print(f\"Router ID: {self.r_id}\")\n print(self.table.pprint_table())", "def add_routing_table(self, routing_table):\n if (routing_table.x, routing_table.y) in self._routing_tables_by_chip:\n raise PacmanAlreadyExistsException(\n \"The Routing table for chip \"\n f\"{routing_table.x}:{routing_table.y} already exists in this \"\n \"collection and therefore is deemed an error to re-add it\",\n str(routing_table))\n self._routing_tables_by_chip[(routing_table.x, routing_table.y)] = \\\n routing_table\n self._max_number_of_entries = max(\n self._max_number_of_entries, routing_table.number_of_entries)", "def get_routing_table_for_chip(self, x, y):\n return self._routing_tables_by_chip.get((x, y), None)", "def route(src_ip, provider):\n cur.execute(\"\"\"SELECT id FROM provider WHERE name = ?\"\"\", (provider,))\n provider_id = cur.fetchone()[0]\n if not provider_id:\n return 9\n ret = os.system(\"\"\"\n sudo /sbin/iptables -t mangle -A PREROUTING -s %s -j MARK --set-mark %i\n \"\"\" % (src_ip, int(provider_id)))\n if ret == 0:\n ret = ret | back(src_ip)\n cur.execute(\"\"\"INSERT INTO active_routes \n (src_ip, provider_id) VALUES (?, ?)\"\"\", (src_ip, int(provider_id)))\n con.commit()\n return ret", "def lookup_mn_route(route_file,pair):\n\n call = []\n call.append('/bin/grep')\n call.append('int_vndst=\\\"%d\\\" int_vnsrc=\\\"%d\\\"'% (pair[1][0],pair[0][0]))\n call.append(route_file)\n\n\n try:\n result = subprocess.check_output(call)\n except subprocess.CalledProcessError as e:\n sys.stderr.write(\"Error: %s. Output: %s\\n\" % ( e.returncode, e.output))\n\n m = HOPREGEX.match(result)\n\n if not m:\n return None\n\n return map(int,m.groups()[0].split())" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Builds a RecordKey object based on the input data and returns it. record An object of the given type to make the record key out of.
def build( self, record ): # Nothing to do if the key size is zero! if (self.key_buffer_size == 0): return None # Check that the given record is a dict of the given table # type if not isinstance( record, dict ): raise ValueError( "Given record must be a dict; given %s" % type( record ) ) # Check all the keys of the given record record_keys = record.keys() if (record_keys != self.table_column_names): raise ValueError( "Given record must be of the type for GPUdb table '%s'" " (with columns '%s'); given record has columns '%s' " % (self.table_name, self.table_column_names, record_keys) ) # Create and populate a RecordKey object record_key = RecordKey( self.key_buffer_size ) for i in range(0, len(self.key_columns_names)): # get the key, value pair key = self.key_columns_names[ i ] value = record[ key ] key_type = self.key_types[ i ] # Add to the record key if key_type in ["char1", "char2", "char4", "char8", "char16"]: record_key.add_char( value ) elif key_type in ["double", "float", "int", "int8", "int16", "long"]: record_key.add_number( value ) elif key_type in ["string"]: record_key.add_string( value ) else: raise ValueError( "Unknown key type given: '%s'" % key_type ) # end loop # Compute the key hash and return the key record_key.compute_hashes() return record_key
[ "def get_key_from_record(type_: type) -> type:\n if not typing_inspect.is_generic_type(type_):\n raise Exception(f'Cannot get associated key from not generic type {type_.__name__}')\n\n from datacentric.types.record import TypedKey, TypedRecord, RootRecord\n from typing import ForwardRef\n\n generic_base = typing_inspect.get_generic_bases(type_)[0]\n\n generic_origin = typing_inspect.get_origin(generic_base)\n if generic_origin is not RootRecord and generic_origin is not TypedRecord:\n raise Exception(f'Wrong generic origin: {generic_origin.__name__}. Expected TypedRecord || RootRecord')\n\n generic_arg = typing_inspect.get_args(generic_base)[0] # Arg\n\n # Generic parameter is forward ref\n if type(generic_arg) is ForwardRef:\n return ClassInfo.get_type(generic_arg.__forward_arg__)\n # Generic parameter is type\n elif issubclass(generic_arg, TypedKey):\n return generic_arg\n else:\n raise Exception(f'Cannot deduce key from type {type_.__name__}')", "def createFieldKey(record):\n key = tuple ( [ record[field] for field in KEY_FIELDS if field in record ] )\n return key", "def get_record_from_key(type_: type) -> type:\n if not typing_inspect.is_generic_type(type_):\n raise Exception(f'Cannot get associated key from not generic type {type_.__name__}')\n\n from datacentric.types.record import TypedKey, TypedRecord, RootRecord\n from typing import ForwardRef\n\n generic_base = typing_inspect.get_generic_bases(type_)[0]\n\n generic_origin = typing_inspect.get_origin(generic_base)\n if generic_origin is not TypedKey:\n raise Exception(f'Wrong generic origin: {generic_origin.__name__}. Expected TypedKey')\n\n generic_arg = typing_inspect.get_args(generic_base)[0] # Arg\n\n # Generic parameter is forward ref\n if type(generic_arg) is ForwardRef:\n return ClassInfo.get_type(generic_arg.__forward_arg__)\n # Generic parameter is type\n elif issubclass(generic_arg, TypedRecord) or issubclass(generic_arg, RootRecord):\n return generic_arg\n else:\n raise Exception(f'Cannot deduce key from type {type_.__name__}')", "def createFieldKey(record, key_fileds):\n key = tuple ( [ record[field] for field in key_fields ] )\n return key", "def CreateRecordTypes():\r\n return {r[1]: RecordType(*r) for r in", "def gen_record_item(record: RecordType):\n raise NotImplementedError", "def mkRecord(keys, fields):\n d = {}\n for k, v in zip(keys, fields):\n\tif v: d[k] = v\n return d", "def build_key(cls, user_id):\n key = ndb.Key(cls, user_id)\n return key", "def of(python_type: Any) -> str:\n if python_type is str or isinstance(python_type, str):\n return KeyType.String\n elif python_type is dict or isinstance(python_type, dict):\n return KeyType.Hash\n elif python_type is list or isinstance(python_type, list):\n return KeyType.List\n elif python_type is set or isinstance(python_type, set):\n return KeyType.Set\n else:\n raise ValueError(\n f\"No corresponding Redis Key-Type for python type {python_type}\"\n )", "def make_key(self, column):\r\n assert isinstance(column, Column)\r\n return self.record_key.clone(key=column.value)", "def constructor(key_type: str):\n return KeyType._constructors[key_type]", "def __create_dns_record_object(self, domain, record_type, nameserver=None):\n record = self.__get_dns_record(domain, record_type, nameserver)\n if not record:\n return None\n\n dns_record = DNSRecord()\n dns_record.domain_name = self.__create_domain_name_object(record.get('Domain_Name'))\n dns_record.ip_address = self.__create_ip_address_object(record.get('IP_Address'))\n dns_record.entry_type = String(record.get('Entry_Type'))\n dns_record.flags = HexBinary(record.get('Flags'))\n dns_record.record_data = record.get('Record_Data')\n\n return dns_record", "def record_builder(record, error_counter, metadata):\n\n #create the object based on the input record\n try:\n person = entities.Person.parts_unknown(record['name'])\n except KeyError:\n # If we don't have name in the record\n person = entities.Entity('UNKNOWN')\n error_counter.add('No name on person')\n\n return person", "def _build_key_attr_dicts(self, record, entity_location):\n key_attrs = {}\n ent_loc_conf = self._rec_attr_map[record.record_type][entity_location]\n for key in ent_loc_conf['keys']:\n key_attrs[key] = {\n 'entity_location': entity_location,\n 'attribute_name': ent_loc_conf.get('attr_map', {}).get(key, key),\n 'key_type': ent_loc_conf['keys'].get(key, 'not_a_key'),\n 'attribute_value': record[key]\n }\n if '*' in ent_loc_conf['entity_map']:\n key_attrs[key].update({'entity_name': ent_loc_conf['entity_map']['*']})\n else:\n key_attrs[key].update({'entity_name': ent_loc_conf['entity_map'][key]})\n return key_attrs", "def cache_token_key_for_record(record):\n klass = record.__class__\n return \":\".join(map(str, [klass.__module__, klass.__name__, record.pk]))", "def _build_key(tenant_it, obj):\n\n str_list = []\n\n if tenant_it:\n str_list.append(str(tenant_it))\n\n if obj:\n if 'application_type' in obj and obj['application_type']:\n str_list += obj['application_type']\n\n if 'dimensions' in obj and obj['dimensions']:\n dims = obj['dimensions']\n sorted_dims = sorted(dims)\n for name in sorted_dims:\n str_list += name\n str_list += str(dims[name])\n\n return ''.join(str_list)", "def record_from_dict(data: dict[str, Any], cast: list[type]) -> Record:\n try:\n data_class = records.__getattribute__(data[\"record_type\"])\n except AttributeError:\n data_class = Record\n return dacite.from_dict(\n data=data,\n data_class=data_class,\n config=dacite.Config(cast=cast),\n )", "def grant_key(self,o,keytype):\n type_table = {\n 'manager': managerkey,\n 'auditor': managerkey,\n 'staff': managerkey,\n 'customer': customerkey,\n 'guest': guestkey,\n }\n# test for legal keytype\n try:\n k = type_table[keytype]\n except Exception:\n return None\n return k\n\n # call creator method for keytype\n def guestkey(self,o):\n k = AuthKey()\n k.operator = o\n k.type='guest'\n k.expiration = -1\n k.timestamp = 1 # get a real timestamp here\n return k\n\n def customerkey(self,o):\n k = self.guestkey(o)\n k.customerid = '' # get it from a legal place\n k.type = 'customer'\n return k\n\n def managerkey(self,o):\n k = self.guestkey(o)\n k.managerid = '' # get this from a legal source\n k.type = 'manager'\n return k", "def create_price_data(record, primary_key, price_type):\r\n price_key = f'{price_type}_price'\r\n if pd.notna(record[price_key]):\r\n return {\r\n 'gas_type': price_type,\r\n 'price': record[price_key],\r\n 'date': datetime.now(),\r\n 'station_id': primary_key\r\n }\r\n else:\r\n return None" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks whether this record has any key associated with it.
def has_key( self ): return (len( self.key_columns_names ) > 0)
[ "def has_key(self, key: str) -> bool:\n return key in self._collection", "def __contains__(self, key):\n return key in self._keys", "def is_key_registered(self, key):\n return key in self._objects", "def exists(cls, key):\n # Check the store first.\n if cls._store and cls._store.has(key):\n return True\n # Then check unsaved instances.\n if cls.get_key_name() == \"uid\":\n if key in cls._instances:\n return True\n else:\n # This entity isn't saved by UID, so we have to check\n # each one for a matching store key.\n for entity in cls._instances.values():\n if entity.key == key:\n return True\n return False", "def hasKey(self, table, key):\n raise NotImplementedException()", "def has_record(self) -> bool:\n # since accessing the 'record' property may be expensive, we try\n # to minimize the cost of this function by checking the\n # 'record_pid_id' first, which does not require joins\n if self.record_pid_id is None or self.record_pid is None:\n return False\n elif self.record is None:\n return False\n else:\n return True", "def has_key(key):\n from bempp.api.utils import pool\n\n return key in pool._DATA", "def is_key_for(self, obj):\n self.has_prop(\"key-for-%s\" % obj.id)", "def exists(self, key):\r\n return self.execute_command(\"EXISTS\", key)", "def isKey(self,arg):\n if arg in list(self.keyInfo.keys()):\n return True\n else:\n return False", "def has_data(self, obj):\n return self.key in obj.data", "def key_exists(self, namespace, key):\n\n return namespace in self.__data and key in self.__data[namespace]", "def check_key(self, key):\n\t\treturn len(key) == KEY_LEN", "def has_apikeys(self):\n return self.api_keys.count() > 0", "def _check_key(mcs, key):\n\n if key in mcs._keys:\n return True\n\n bases = mcs._get_base_metas()\n return any(key in base._keys for base in bases)", "def __contains__(self, key):\n location = self.hash(key)\n\n if self.table[location] is not None: # there is a node at location\n return True\n else: # item at location is None\n return False", "def __contains__(self, key):\n query = select([exists().where(self.store.c.key == key)])\n result = self.conn.execute(query)\n return result.fetchone()[0]", "def IsKey(self, *args):\n return _snap.TUnionFind_IsKey(self, *args)", "def has(self, key):\n\n return key in self._parameters;" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if the given record key builder is equivalent to this one.
def has_same_key( self, other_record_key_builder ): return (self.key_schema_str == other_record_key_builder.key_schema_str)
[ "def __eq__(self, other: Any) -> bool:\n if not isinstance(other, OrdinalEncoder):\n return False\n if (\n self.columns == other.columns\n and self.derived_columns == other.derived_columns\n ):\n return True\n\n return False", "def __eq__(self, other):\n return type(self) == type(other) and self.parent() == other.parent() and self.key() == other.key()", "def IsKey(self, *args):\n return _snap.TUnionFind_IsKey(self, *args)", "def check_key(self, key):\n\t\treturn len(key) == KEY_LEN", "def __eq__(self, edit_info):\n return self.to_storable() == edit_info.to_storable()", "def __eq__(self, other):\n if (other == None):\n return False\n if (type(other) == int):\n if (self.key == other):\n return True\n return False\n else:\n if (self.key == other.key):\n return True\n return False", "def __eq__(self, value):\r\n return self._key == value._key", "def isKey(self,arg):\n if arg in list(self.keyInfo.keys()):\n return True\n else:\n return False", "def __eq__(self, other):\n try:\n otherlbl = other.label\n except AttributeError:\n raise TypeError(\n 'Expecting a TodoKey with a label, got: {}'.format(\n other.__class__.__name__\n ))\n if otherlbl != self.label:\n return False\n try:\n otherdata = other.data\n except AttributeError:\n raise TypeError(\n 'Expecting a TodoKey with a data attribute, got: {}'.format(\n other.__class__.__name__\n )\n )\n # Same label, same data.\n return otherdata == self.data", "def hasProperKey(self, keyseq=DEFAULT_KEYSEQ):\n\n keylen = len(keyseq)\n keyseq_from_flow = self.toSeq(truncate=False,\n Bases=False)[:keylen]\n return (keyseq_from_flow == keyseq)", "def _check_key_setting_consistency(self, params_kkrimp, key, val):\n param_ok = True\n\n #TODO implement checks\n\n if not param_ok:\n raise ValueError('Trying to set key \"{}\" with value \"{}\" which is in conflict to previous settings!'.format(key, val))", "def _check_key(self, key):\n\n locked_ckt = circuit.Circuit.specify_inputs(key, self.nodes, self.output_names)\n miter = circuit.Circuit.miter(locked_ckt, self.oracle_ckt)\n\n s = z3.Solver()\n s.add(miter.outputs()[\"diff\"] == True)\n\n return s.check() == z3.unsat", "def has_key( self ):\n return (len( self.key_columns_names ) > 0)", "def is_key_field(self, k : str) -> bool:\n if k == KEY_FIELD: return True\n kf = self.key_fields()\n if kf and len(kf) == 1 and kf[0] == k: return True\n return False", "def __eq__(self, other):\n return (\n isinstance(other, self.__class__)\n and self._ordinal == other._ordinal\n and self._key == other._key)", "def check_private_view_key(self, key):\n return ed25519.public_from_secret_hex(key) == self.view_key()", "def __eq__(self, other):\n if other is self:\n return True\n elif not self.__class__ == other.__class__:\n return False\n\n if id(self) in _recursion_stack:\n return True\n _recursion_stack.add(id(self))\n\n try:\n # pick the entity that's not SA persisted as the source\n try:\n self_key = sa.orm.attributes.instance_state(self).key\n except sa.orm.exc.NO_STATE:\n self_key = None\n\n if other is None:\n a = self\n b = other\n elif self_key is not None:\n a = other\n b = self\n else:\n a = self\n b = other\n\n for attr in list(a.__dict__):\n if attr.startswith(\"_\"):\n continue\n\n value = getattr(a, attr)\n\n if isinstance(value, WriteOnlyCollection):\n continue\n\n try:\n # handle lazy loader errors\n battr = getattr(b, attr)\n except (AttributeError, sa_exc.UnboundExecutionError):\n return False\n\n if hasattr(value, \"__iter__\") and not isinstance(value, str):\n if hasattr(value, \"__getitem__\") and not hasattr(\n value, \"keys\"\n ):\n if list(value) != list(battr):\n return False\n else:\n if set(value) != set(battr):\n return False\n else:\n if value is not None and value != battr:\n return False\n return True\n finally:\n _recursion_stack.remove(id(self))", "def test_key_id(self):\n self.__assert_empty_builder()\n self.__builder.key_id('id')\n self.assertEqual('path - -keyid id', str(self.__builder))", "def __eq__(self, other: Any) -> bool:\n if not isinstance(other, ReplaceSubstrings):\n return False\n if (\n self.columns == other.columns\n and self.derived_columns == other.derived_columns\n and self.replacement_map == other.replacement_map\n ):\n return True\n\n return False" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the current (old) record queue and create a new empty one.
def flush( self ): old_queue = self.record_queue # Create a fresh new queue self.record_queue = [] # if a key->record_queue_index map exists, clear it if self.primary_key_to_queue_index_map: self.primary_key_to_queue_index_map = {} return old_queue
[ "def new_empty_q():\n from queue_ds import Queue\n this_empty_q = Queue()\n return this_empty_q", "def queue_fixture():\n new_queue = our_queue()\n return new_queue", "def create_queue(self, queue):", "def refresh_queue(self):\n #print(\"REF Q\")\n now_s = time.time()\n state = self.get_state()\n queue = self.queue = self.get_queue()\n for probe in self.get_probes():\n name = probe['name']\n if not name in queue:\n logger.debug(\"Adding entry for %s\", name)\n sched = self.cfg['schedules'][probe['schedule']]\n sched_st = self.mk_sched_entry(\n probe['name'],\n t_next=now_s,\n schedule=sched,\n )\n queue.add(sched_st)\n #print(\"Q: \", self.queue)\n s_queue = OrderedDict()\n for key, val in sorted(queue.items(), \n key=lambda key_val: (key_val[1]['t_next'], key_val[1]['interval'])):\n s_queue[key] = val\n self.queue = s_queue\n #print(\"SQ: \", s_queue)", "def get_queue(self):\n if self.queue is not None:\n return self.queue\n from timon.state import TMonQueue\n state = self.get_state()\n self.queue = queue = state.get_queue()\n #print(\"IQ\", queue)\n return self.queue", "def handle_create(self):\r\n queue_name = self.physical_resource_name()\r\n queue = self.marconi().queue(queue_name, auto_create=False)\r\n # Marconi client doesn't report an error if an queue with the same\r\n # id/name already exists, which can cause issue with stack update.\r\n if queue.exists():\r\n raise exception.Error(_('Message queue %s already exists.')\r\n % queue_name)\r\n queue.ensure_exists()\r\n self.resource_id_set(queue_name)\r\n return queue", "def add_queue_info(record):\n record.queue_id = background_helper.lookup_queue_for_action(record.action)\n return record", "def queue(self):\n from .queue import Queue\n return Queue.load(self.queue_id)", "def __dequeue(self):\n return self.__queue.pop()", "def test_dequeue_reassign_head(new_q):\n old_head = new_q._container.head\n new_q.dequeue()\n assert old_head.nxt.value == new_q._container.head.value", "def test_dequeue_reassign_nxt_prev(new_q):\n new_q.dequeue()\n assert new_q._container.head.prev is None\n assert new_q._container.head.nxt.prev is new_q._container.head", "def push_back (self):\n new_item = int(input(\"New item to the end: \"))\n self.deque = np.append(self.deque, new_item)\n self.check()\n return self.deque", "def dequeue(self):\n if self.isEmpty():\n return None\n else:\n obj = self._queue[0]\n del self._queue[0]\n return obj", "def fill_queue(orders_of_the_day, queue_of_the_day):\n for order in orders_of_the_day:\n queue_of_the_day.enqueue(order)\n return queue_of_the_day", "def test_dequeue_decrease_size(new_q):\n old_size = new_q._container._size\n new_q.dequeue()\n assert new_q._container._size == old_size - 1", "def get_date_queue(end):\n dg = gen_date_from_now_to(end)\n dq = Queue.Queue()\n while True:\n date = dg.next()\n if date is not None:\n dq.put(date)\n else:\n return dq", "def pop_queue(self, container, obj, q_ts, q_record):\n q_path = '/%s/%s/%s' % (MISPLACED_OBJECTS_ACCOUNT, container, obj)\n x_timestamp = slightly_later_timestamp(max(q_record, q_ts))\n self.stats_log('pop_queue', 'remove %r (%f) from the queue (%s)',\n q_path, q_ts, x_timestamp)\n headers = {'X-Timestamp': x_timestamp}\n direct_delete_container_entry(\n self.swift.container_ring, MISPLACED_OBJECTS_ACCOUNT,\n container, obj, headers=headers)", "def wipeQueue():\n\tq.clear()", "def get_queue(queue1: queue.Queue):\n file = open(constant.file_name, constant.mode)\n flag = True\n while flag:\n message = queue1.get()\n file.write(message)\n if not message:\n flag = False\n file.close()" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initializes the GPUdbIngestor instance. gpudb table_name batch_size options workers
def __init__( self, gpudb, table_name, batch_size, options = None, workers = None ): # Validate input parameter 'gpudb' assert isinstance(gpudb, GPUdb), ("Parameter 'gpudb' must be of " "type GPUdb; given %s" % type(gpudb) ) # Validate input parameter 'table_name' assert isinstance(table_name, str), ("Parameter 'table_name' must be a" "string; given %s" % type(table_name) ) # Validate input parameter 'batch_size' assert (isinstance(batch_size, int) and (batch_size >= 1)), ("Parameter 'batch_size' must be greater" " than zero; given %d" % batch_size ) # Validate input parameter 'options' assert isinstance(options, (dict, None)), ("Parameter 'options' must be a" "dicitonary, if given; given %s" % type(options) ) # Validate input parameter 'workers' assert ((not workers) or isinstance(workers, self.WorkerList)), \ ("Parameter 'workers' must be of type WorkerList; given %s" % type(workers) ) # Save the parameter values self.gpudb = gpudb self.table_name = table_name self.batch_size = batch_size self.options = options self.count_inserted = 0 self.count_updated = 0 # Get the schema for the records for this table from GPUdb show_table_rsp = self.gpudb.show_table( table_name ) assert (show_table_rsp[ C._info ][ C._status ] == C._ok), \ show_table_rsp[ C._info ][ C._msg ] assert (show_table_rsp[ C._table_names ][ 0 ] == table_name), \ ("Table name doesn't match; given: '%s', received '%s'" "" % (table_name, show_table_rsp[ C._table_names ][ 0 ])) assert (not show_table_rsp[ C._is_collection ][ 0 ]), \ ("Cannot instantiate a RecordKeyBuilder for a 'collection' type" " table; table name: '%s'" % table_name) record_schema_str = show_table_rsp[ C._type_schemas ][ 0 ] self.record_schema = schema.parse( record_schema_str ) # Create the primary and shard key builders shard_key_builder = self.RecordKeyBuilder( self.gpudb, self.table_name ) primary_key_builder = self.RecordKeyBuilder( self.gpudb, self.table_name, has_primary_key = True ) self.primary_key_builder = None self.shard_key_builder = None # Save the appropriate key builders if primary_key_builder.has_key(): self.primary_key_builder = primary_key_builder # If both pk and shard keys exist; check that they're not the same if (shard_key_builder.has_key() and (not shard_key_builder.has_same_key( primary_key_builder ))): self.shard_key_builder = shard_key_builder elif shard_key_builder.has_key(): self.shard_key_builder = shard_key_builder # end saving the key builders # Boolean flag for primary key related info update_on_existing_pk = False if ( self.options and ("update_on_existing_pk" in self.options) ): update_on_existing_pk = (self.options[ "update_on_existing_pk" ] == "true") # end if self.worker_queues = [] # Create a list of worker queues and a map of url to GPUdb worker ranks if not workers: # but no worker provided worker_url = self.gpudb.get_url() try: has_primary_key = (self.primary_key_builder != None) wq = self.WorkerQueue( worker_url, self.gpudb, self.batch_size, has_primary_key, update_on_existing_pk ) self.worker_queues.append( wq ) except ValueError as e: raise else: # workers provided for worker in workers.get_worker_urls(): try: worker_url = worker wq = self.WorkerQueue( worker_url, self.gpudb, self.batch_size, update_on_existing_pk ) self.worker_queues.append( wq ) # Create a gpudb per worker worker_host, sep, worker_port = worker.rpartition( ":" ) # worker_host, worker_port = worker.split( ":" ) except ValueError as e: raise # end loop over workers # end if-else # Get the number of workers if not workers: self.num_ranks = 1 else: self.num_ranks = len( workers.get_worker_urls() ) self.routing_table = None if ( (self.num_ranks > 1) and (self.primary_key_builder or self.shard_key_builder) ): # Get the sharding assignment ranks shard_info = self.gpudb.adming_get_shard_assignments() self.routing_table = shard_info[ C._shard_ranks ] # end if
[ "def init():\n\n # Check if metric already present in the metric_map\n if gpu_count not in metric_map: \n\n # Create metric and add it to metric_map\n metric_map[gpu_count] = Gauge(gpu_count, \"Number of GPUs\")\n\n if not created:\n metric_map[gpu_healthrollup] = Gauge(gpu_healthrollup, \"GPU HealthRollup\")\n\n print(\"Initialized GPU Exporter...\")", "def heavy_init(cls):\n cfg.CONF.set_default('connection', 'sqlite://', group='database')\n cfg.CONF.set_default('max_overflow', -1, group='database')\n cfg.CONF.set_default('max_pool_size', 1000, group='database')\n\n qinling_opts = [\n (config.API_GROUP, config.api_opts),\n (config.PECAN_GROUP, config.pecan_opts),\n (config.ENGINE_GROUP, config.engine_opts),\n (config.STORAGE_GROUP, config.storage_opts),\n (config.KUBERNETES_GROUP, config.kubernetes_opts),\n (None, [config.launch_opt])\n ]\n for group, options in qinling_opts:\n cfg.CONF.register_opts(list(options), group)\n\n db_api.setup_db()", "def init_statistics_tables(self):\r\n self.initDB('job_stats.db3')", "def init_replica(self):\n\t\tself.pg_eng.set_source_id('initialising')\n\t\tself.pg_eng.clean_batch_data()\n\t\tself.create_schema()\n\t\tself.copy_table_data()\n\t\tself.create_indices()\n\t\tself.pg_eng.set_source_id('initialised')", "def __init__( self, gpudb, ip_regex = \"\" ):\n # Check the input parameter type\n assert isinstance(gpudb, GPUdb), (\"Parameter 'gpudb' must be of \"\n \"type GPUdb; given %s\"\n % type(gpudb) )\n\n self.worker_urls = []\n\n # Get system properties\n system_prop_rsp = gpudb.show_system_properties()\n if system_prop_rsp[ C._info ][ C._status ] == C._error:\n raise ValueError( \"Unable to retrieve system properties; error:\"\n \" %s\" % system_prop_rsp[ C._info ][ C._msg ] )\n\n system_properties = system_prop_rsp[ C._sys_properties ]\n\n # Is multi-head ingest enabled on the server?\n if C._multihead_enabled not in system_properties:\n raise ValueError( \"Missing value for %s\" % C._multihead_enabled)\n\n self.multihead_enabled = (system_properties[ C._multihead_enabled ] == C._TRUE)\n if not self.multihead_enabled:\n # Multihead ingest is not enabled. Just return the main/only ingestor\n self.worker_urls.append( gpudb.get_url() )\n return # nothing to do\n\n # Get the worker IP addresses (per rank)\n if C._worker_IPs not in system_properties:\n raise ValueError( \"Missing value for %s\" % C._worker_IPs)\n\n self.worker_IPs_per_rank = system_properties[ C._worker_IPs ].split( \";\" )\n\n # Get the worker ports\n if C._worker_ports not in system_properties:\n raise ValueError( \"Missing value for %s\" % C._worker_ports)\n\n self.worker_ports = system_properties[ C._worker_ports ].split( \";\" )\n\n # Check that the IP and port list lengths match\n if (len(self.worker_IPs_per_rank) != len(self.worker_ports)):\n raise ValueError(\"Inconsistent number of values for %s and %s.\"\n % (C._worker_IPs_per_rank, C._worker_ports) )\n\n # Process the IP addresses per rank\n for i in range(0, len(self.worker_IPs_per_rank)):\n ip_address = self.worker_IPs_per_rank[ i ]\n # ips_per_rank = self.worker_IPs_per_rank[ i ]\n found = False\n\n # Validate the IP address's syntax\n if not self.validate_ip_address( ip_address ):\n raise ValueError( \"Malformed IP address: %s\" % ip_address )\n\n # Generate the URL using the IP address and the port\n # url = (ip_address + \":\" + self.worker_ports[i])\n url = (\"http://\" + ip_address + \":\" + self.worker_ports[i])\n\n if (ip_regex == \"\"): # no regex given\n # so, include all IP addresses\n self.worker_urls.append( url )\n found = True\n else: # check for matching regex\n match = re.match(ip_regex, ip_address)\n if match: # match found\n self.worker_urls.append( url )\n found = True\n # skip the rest of IP addresses for this rank\n continue\n # end found match\n # end if-else\n\n # if no worker found for this rank, throw exception\n if not found:\n raise ValueError(\"No matching IP address found for worker\"\n \"%d.\" % i)\n # end outer loop of processing worker IPs\n\n # if no worker found, throw error\n if not self.worker_urls:\n raise ValueError( \"No worker HTTP servers found.\" )", "def init_with_database(self):\n\n with self._lock:\n self._metrics.init_with_database()", "def __init__(self, config):\n\n conn = mysql.connector.connect(\n host=config.get('database', 'host'),\n database=config.get('database', 'database'),\n user=config.get('database', 'user'),\n password=config.get('database', 'password'))\n\n self.db = JSAProcMySQLLock(conn)\n\n JSAProcDB.__init__(self)", "def __init__(self, gmpe_table=None):\n if not self.GMPE_TABLE:\n if gmpe_table:\n if os.path.isabs(gmpe_table):\n self.GMPE_TABLE = gmpe_table\n else:\n # NB: (hackish) GMPE_DIR must be set externally\n self.GMPE_TABLE = os.path.abspath(\n os.path.join(self.GMPE_DIR, gmpe_table))\n else:\n raise IOError(\"GMPE Table Not Defined!\")\n super().__init__()\n self.imls = None\n self.stddevs = {}\n self.m_w = None\n self.distances = None\n self.distance_type = None\n self.amplification = None\n # NB: it must be possible to instantiate a GMPETable even if the\n # the .hdf5 file (GMPE_TABLE) does not exist; the reason is that\n # we want to run a calculation on machine 1, copy the datastore\n # on machine 2 (that misses the .hdf5 files) and still be able to\n # export the results, i.e. to instantiate the GsimLogicTree object\n # which is required by the engine to determine the realizations\n if os.path.exists(self.GMPE_TABLE):\n with h5py.File(self.GMPE_TABLE, \"r\") as f:\n self.init(f)", "def init(self):\n # Support both distributed and non-distributed training\n local_rank = os.environ.get(\"LOCAL_RANK\")\n if local_rank is not None:\n dist.init_process_group(\n \"nccl\", timeout=timedelta(seconds=self.nccl_timeout)\n )\n assert (\n th.cuda.is_available()\n ), \"CUDA must be available for distributed training\"\n th.cuda.set_device(self.local_rank)", "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 _init_device_worker(identifier, precision):\n import bempp.api\n from bempp.api.utils.pool import get_id\n from bempp.core.cl_helpers import get_context_by_name\n\n ctx, platform_index = get_context_by_name(identifier)\n bempp.api.set_default_device(platform_index, get_id())\n if precision is not None:\n bempp.api.DEVICE_PRECISION_CPU = precision\n bempp.api.DEVICE_PRECISION_GPU = precision", "def initialize_database(self):\n self.database = self.loader.request_library(\"common_libs\", \"database\")\n self.database.create_connection(\"production\")\n self.database.load_mappings()\n\n self.migrator = self.loader.request_library(\"database_tools\", \"migrator\")\n self.migrator.migrate()", "def _initialize_db():\n # TODO(metzman): Most of the strings in this function should probably be\n # configurable.\n\n db_utils.initialize()\n # One time set up for any db used by FuzzBench.\n models.Base.metadata.create_all(db_utils.engine)\n\n # Now set up the experiment.\n with db_utils.session_scope() as session:\n experiment_name = 'oss-fuzz-on-demand'\n experiment_exists = session.query(models.Experiment).filter(\n models.Experiment.name == experiment_name).first()\n if experiment_exists:\n raise Exception('Experiment already exists in database.')\n\n db_utils.add_all([\n db_utils.get_or_create(models.Experiment,\n name=experiment_name,\n git_hash='none',\n private=True,\n experiment_filestore='/out/filestore',\n description='none'),\n ])\n\n # Set up the trial.\n trial = models.Trial(fuzzer=os.environ['FUZZER'],\n experiment='oss-fuzz-on-demand',\n benchmark=os.environ['BENCHMARK'],\n preemptible=False,\n time_started=scheduler.datetime_now(),\n time_ended=scheduler.datetime_now())\n db_utils.add_all([trial])", "def __init__(self) -> None:\r\n self.db = Db()\r\n self.init_db()", "def __init__(self, feature_generators=[], instances=[], num_processes = 1):\n self.feature_generators = feature_generators\n self.instances = instances\n self.num_processes = num_processes", "def initialize_global_dbs_mngr(update_required=False):\n from DAS.core.das_mapping_db import DASMapping\n\n dasconfig = das_readconfig()\n dasmapping = DASMapping(dasconfig)\n\n dburi = dasconfig['mongodb']['dburi']\n dbsexpire = dasconfig.get('dbs_daemon_expire', 3600)\n main_dbs_url = dasmapping.dbs_url()\n dbsmgr = DBSDaemon(main_dbs_url, dburi, {'expire': dbsexpire,\n 'preserve_on_restart': True})\n\n # if we have no datasets (fresh DB, fetch them)\n if update_required or not next(dbsmgr.find('*Zmm*'), False):\n print('fetching datasets from global DBS...')\n dbsmgr.update()\n return dbsmgr", "def __init__(self):\n project_id = os.environ.get(\"GOOGLE_PROJECT_ID\", \"\")\n client = spanner.Client(project=project_id)\n instance_id = os.environ.get(\"GLUU_GOOGLE_SPANNER_INSTANCE_ID\", \"\")\n self.instance = client.instance(instance_id)\n\n database_id = os.environ.get(\"GLUU_GOOGLE_SPANNER_DATABASE_ID\", \"\")\n self.database = self.instance.database(database_id)", "def _initialize():\n\n\t\t# Read the configuration from file:\n\t\tdbType = Config.get(\"localdb\", \"type\")\n\t\tdbName = Config.get(\"localdb\", \"name\")\n\t\tdbHost = Config.get(\"localdb\", \"hostname\")\n\t\tdbUser = Config.get(\"localdb\", \"username\")\n\t\tdbPass = Config.get(\"localdb\", \"password\")\n\t\t\n\t\t# Construct the dbPath string, or rais an exception if the dbtype is unknown.\n\t\tif(dbType == \"sqlite\"):\n\t\t\tdbpath = 'sqlite:///' + dbName\n\t\telif(dbType == \"mysql\"):\n\t\t\tdbpath = dbType + \"://\" + dbUser + \":\" + dbPass + \"@\" + dbHost + \"/\" + dbName\n\t\telse:\n\t\t\traise Exception(\"DatabaseConfiguration is not correct\")\n\t\t\n\t\t# Create a dbengine, and depending on the configfile maybe turn on the debug.\n\t\tif(Config.get(\"localdb\", \"debug\") == \"0\"):\n\t\t\tSession.engine = create_engine(dbpath)\n\t\telse:\n\t\t\tSession.engine = create_engine(dbpath, echo=True)\n\t\t\n\t\t# Create a session, and bind it to the engine.\n\t\tSession.session = sessionmaker(bind=Session.engine)\n\t\t\n\t\t# Making sure that the dbSchema is created.\n\t\tBase.metadata.create_all(Session.engine)", "def __init__(self):\n self.database_uri = None\n self.config = dict()\n # default configuration for MongoDB server connection\n self.max_pool = 100\n self.min_pool = 0\n self.max_idle_time = None\n self.connection_timeout = 10000\n self.heartbeat_frequency = 10000\n self.server_timeout = 100" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the number of records inserted thus far.
def get_count_inserted( self ): return self.count_inserted
[ "def rowcount(self):\n self._check_that_read_query_was_issued()\n return self._delegate.rowcount", "def getAffectedRowsCount(self): \n return self.affectedRows", "def get_records_count(conn):\n\n if not conn:\n return 0\n\n raw_iterator = conn.raw_iterator() # invalid,must move to the first\n if raw_iterator:\n raw_iterator.seek_to_first()\n else:\n return 0\n\n count = 0\n\n while raw_iterator.valid() and raw_iterator.item():\n count = count + 1\n item = raw_iterator.item()\n # Only move ,no returnVal\n raw_iterator.next()\n\n return count", "def get_num_rows(self):\r\n return len(self.rows)", "def row_count(self):\n return len(self._table)", "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 document_count(self):\n #return len(self.fake_index_storage.keys())\n raise NotImplementedError()", "def get_record_count():\n record_counts_list = RecordCount.query().fetch(1)\n return record_counts_list[0].count", "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 record(self, entries):\n count = None\n for ent in entries:\n count = db.insert_one({\n 'txhash': ent[0],\n 'start': ent[1],\n 'end': ent[2],\n })\n return count", "def count_keys(self):\n return self.connection.dbsize()", "def num_entities(self) -> int:\n conn = self._get_connection()\n status = conn.get_collection_stats(db_name=\"\", collection_name=self._name)\n return status[\"row_count\"]", "def getRecordCount(self):\n self.numberOfRecordsReturned = 0\n if self.stopped:\n return\n try:\n data = json.loads(self.data, strict=False)\n if data['success'] == 'true' or data['success'] == True:\n self.numberOfRecordsReturned = int(len(data['result']['results']))\n self.totalCount = int(data['result']['count'])\n self.pageCount += 1\n self.logger.logMessage(\"CKANQUERY (numberOfRecordsReturned) %d of %d\" % ((self.numberOfRecordsReturned * self.pageCount), self.totalCount), \"DEBUG\")\n # sanity check\n self.recordCount += self.numberOfRecordsReturned\n if self.recordCount >= self.totalCount:\n self.logger.logMessage(\"CKANQUERY (Harvest Completed)\", \"DEBUG\")\n self.completed = True\n except Exception:\n self.numberOfRecordsReturned = 0\n self.errored = True\n pass", "def debug_record_count(self) -> int:\n _returned = self.auth_object.debug_record_count\n if isinstance(self._debug_record_count, int):\n _returned = self._debug_record_count\n\n return _returned", "def table_est_row_count():\n query_est_row_count(current_app.extensions['sqlalchemy'].db)", "def __len__(self):\n with self._index.reader() as reader:\n return reader.doc_count()", "def get_number_of_entries(self):\n return self.mongo_db_service.entries", "def total_rows_count(self) -> int:\n return pulumi.get(self, \"total_rows_count\")", "def nrecords(self):\n self.ready() # check if we're ready\n return sum(\n 1 for line in self._file\n if line.strip() and not line.endswith(\"|\") and not line.startswith(\"#\")\n )", "def count(self):\n info = self.describe()\n return info['Table'].get('ItemCount', 0)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Internal method to flushactually insertthe records to GPUdb. queue List of records to insert url The URL to which to send the records.
def __flush( self, queue, worker_gpudb ): if not queue: return # nothing to do try: print "Flushing to %s with %d objects" % (worker_gpudb.get_url(), len(queue)) # debug~~~~~~~~~ # Insert the records insert_rsp = worker_gpudb.insert_records( table_name = self.table_name, data = queue, options = self.options ) self.count_inserted += insert_rsp[ C._count_inserted ] self.count_updated += insert_rsp[ C._count_updated ] print "insert status:", insert_rsp[ C._info ][ C._status ], "self.count_inserted:", self.count_inserted, "self.count_updated:", self.count_updated # debug~~~~~~~~~~ except Exception as e: raise self.InsertionException( str(e), queue )
[ "def insert_record(self,list_holding_record):", "def _insert_helper(list_of_docs: List[Dict], api: MongoAPI) -> None:\n api.batch_insert(list_of_docs)\n list_of_docs.clear()", "def bulk_insert_to_es(self, bulk_list_fp, debug = True): \n bulkstr_list = bulk_list_fp.readlines()\n bulkstr = \"\".join(bulkstr_list)\n resp = self.e.bulk(bulkstr)\n if debug: print(resp)", "def process_batch(self, urls, extra_headers=None):\n\n # cull out ones we've got\n n_before = len(urls)\n urls = [url for url in urls if not self.store.already_got(url)]\n logging.info(\"processing %d urls (%d are new)\", n_before, len(urls))\n\n err_cnt = 0\n try:\n\n for url in urls:\n try:\n logging.debug(\"fetch %s\",url)\n headers = {}\n headers.update(self.headers)\n if extra_headers:\n headers.update(extra_headers)\n response = requests.get(url, headers=headers)\n\n # TODO: maybe just skip ones which redirect to other domains?\n if response.url != url:\n if self.disallow_redirects == True:\n logging.warning(\"Skipping %s because it redirected to %s\", url, response.url)\n continue\n elif self.require_same_domain == True:\n orig_location = urlparse.urlparse(url)\n new_location = urlparse.urlparse(response.url)\n if orig_location.netloc != new_location.netloc:\n logging.warning(\"Skipping %s because it redirected to another domain: %s\", url, response.url)\n continue\n\n press_release = self.extract(response.text, url)\n\n # encode text fields\n # TODO: use isinstance(...,unicode) instead\n for f in ('url','title','source','text','location','language','topics'):\n if f in press_release:\n press_release[f] = press_release[f].encode('utf-8')\n self.store.add(press_release)\n \n except Exception as e:\n logging.error(\"failed on %s: %s %s\",url,e.__class__,e)\n print traceback.print_exc()\n err_cnt += 1\n finally:\n self.store.save()", "def pushUrl(self, pUrl, max_redirect):\r\n if pUrl.vaildUrl():\r\n # 去重操作\r\n try:\r\n if self.__Queue.sismember(self.unique_set, pUrl.getUrl):\r\n pass\r\n else:\r\n self.__Queue.sadd(self.unique_set, pUrl.getUrl)\r\n if self.qtype == 'p':\r\n self.__Queue.push(pUrl.getUrl, pUrl.getPriority)\r\n elif self.qtype == 'q':\r\n self.__Queue.push(pUrl.getUrl)\r\n except Exception as error:\r\n log.info('redisScheduler.RedisScheduler.pushUrl ERROR(reason: %s)', error)", "def _add_to_batch(self, spider, request):\n url = request.url\n if not url in self._seen:\n self._seen.add(url)\n self._urls.append(url)\n if len(self._urls) >= self._batch_size:\n self._flush_urls(spider)", "def executeRequests(self):\r\n for i in self.processQueue.queue:\r\n self.allocateMemory(i.pID, i.size//4)\r\n self.processQueue.queue = []", "def _upload_telemetry(self):\n\n # Are there any entries at all?\n queue_entries = self._data_queue.num_entries()\n if queue_entries >= 1:\n # On every upload report current queue size\n data = {'tb-qsize': queue_entries}\n self._data_queue.add(data)\n\n # Build HTTP query string with queue data\n entries = self._data_queue.first_entries(Things.TELEMETRY_MAX_ITEMS_TO_UPLOAD)\n num_entries = len(entries)\n assert len(entries) >= 0\n\n post_data = list()\n for entry in entries:\n data = {'ts': entry['time'], 'values': entry['data']}\n post_data.append(data)\n\n # Upload the collected data\n res = self._post_data('telemetry', post_data)\n if res:\n # Transmission was ok, remove data from queue\n self._data_queue.remove_first(num_entries)\n logger.debug(f'removing {num_entries} entries from queue')\n else:\n logger.warning('could not upload telemetry data, keeping in queue')\n logger.warning(f'{queue_entries} entries in queue')", "def __insert_into_database(request_data: list, predictions: list) -> None:\n try:\n db_connection = __connect()\n cur = db_connection.cursor()\n try:\n date = datetime.now()\n data_joined = []\n\n # Joining data as tuples\n for input, predict in zip(request_data, predictions):\n row_data = (date, f\"{input}\", predict)\n data_joined.append(row_data)\n\n # Inserting data as a batch into database\n insert_query = \"insert into history (date,features,prediction) values %s\"\n psycopg2.extras.execute_values(\n cur, insert_query, data_joined, template=None, page_size=100\n )\n except:\n print(\"Couldn't insert values\")\n db_connection.close()\n except:\n print(\"Couldn't connect to database\")", "def send_data_forward(self):\n front_ip = self.neighbors.front_ip\n front_port = self.neighbors.front_port\n self.data_lock.acquire()\n for key, value in self.data.iteritems():\n #Process(target= lambda : self.neighbors.send_front('insert_after_depart:{}:{}'.format(value[0],value[1]))).start()\n req = 'insert_after_depart:{}:{}'.format(value[0],value[1])\n threading.Thread(target=send_request , args = (front_ip, front_port, req)).start()\n #threading.Thread(target=send_request , args = (front_ip, front_port, req)).start()\n self.data_lock.release()", "def insert_posts_list(self, posts_list, db_ses, FuukaPosts):\n logging.debug('Attempting to insert all posts from thread {0!r} into the DB'.format(self.thread_num))\n for post in posts_list:\n logging.debug('Attempting to insert post {0!r}'.format(post.num))\n post.db_insert(db_ses, FuukaPosts)\n logging.debug('Inserted all posts from thread {0!r} into the DB'.format(self.thread_num))\n return", "def upload_records(self, records, initial=False):\n raise NotImplementedError # pragma: no cover", "def download_and_insert_data(url: str, cursor: psycopg2.extensions.cursor, \n log: logger.Log) -> None:\n page = 0\n empty_response = False\n\n time1 = datetime.datetime.now()\n\n while not empty_response:\n player_response = utils.make_get_request(f\"{url}?page={page}\")\n\n if player_response.content == b'[]':\n empty_response = True\n else:\n content_blob = player_response.json()\n content_blob = json.dumps(content_blob).replace(\"'\", \"''\") \n insert_player_blob(cursor, content_blob)\n\n page += 1\n\n time2 = datetime.datetime.now()\n log.write_metric('player_download_seconds', (time2 - time1).total_seconds())", "def flush(self) -> None:\n for website in self._website_list:\n url = website.get(\"url\")\n time_, error_code, page_content = _StatsExtractor.from_url(url)\n message = {\n \"id\": website.get(\"id\"),\n \"url\": url,\n \"time\": time_,\n \"error_code\": error_code,\n \"page_content\": page_content,\n }\n self._publish_message(self._producer, TOPIC, value=json.dumps(message))", "def insert(self, sql):", "def run_to_queue(self, queue, conn, options=None):\n multiquery = self._maybe_multi_query()\n if multiquery is not None:\n multiquery.run_to_queue(queue, conn, options=options) # No return value.\n return\n dsqry, post_filters = self._get_query(conn)\n orig_options = options\n if (post_filters and options is not None and\n (options.offset or options.limit is not None)):\n options = datastore_query.QueryOptions(offset=None, limit=None,\n config=orig_options)\n assert options.limit is None and options.limit is None\n rpc = dsqry.run_async(conn, options)\n skipped = 0\n count = 0\n while rpc is not None:\n batch = yield rpc\n rpc = batch.next_batch_async(options)\n for ent in batch.results:\n if post_filters:\n if not post_filters.apply(ent):\n continue\n if orig_options is not options:\n if orig_options.offset and skipped < orig_options.offset:\n skipped += 1\n continue\n if orig_options.limit is not None and count >= orig_options.limit:\n rpc = None # Quietly throw away the next batch.\n break\n count += 1\n queue.putq(ent)\n queue.complete()", "def uploadtoDB(date, item, place, cost):", "def bulk_insert(self, records):\r\n # TODO Maybe use COPY instead?\r\n insert_many(SourceEntity, records)", "def BatchInsert(self, table, rowlist):\n columns = rowlist[0].keys()\n sql = \"INSERT INTO {table} ({columns}) VALUES\\n\".format(table=table, columns=', '.join(columns))\n rindex = 0\n sqlvals = dict()\n values = ''\n for row in rowlist:\n rowvalues = list()\n for column in columns:\n rowvalues.append(row[column])\n rowvalues = tuple(rowvalues)\n # update the row index\n rowref = \"r{}\".format(rindex)\n rindex += 1\n # update the sql string; on first time don't add a comma\n if values:\n values += \",\\n\"\n values += \"%({thisrow})s\".format(thisrow=rowref)\n #----- \n sqlvals[rowref] = rowvalues\n #execute\n self.query(sql + values, sqlvals)\n self.connection.commit()" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a new Image object from source file.
def open_file_as_pil_image(source_file): return Image.open(source_file)
[ "def load_image(file):\n return Image.open(os.path.abspath(file))", "def load(image_path, access='random'):\n\n return pyvips.Image.new_from_file(image_path, access=access)", "def from_file(klass, filename):\n surface = pygame.image.load(filename).convert_alpha()\n return Texture(surface)", "def _create_image(self, file, title=None):\n return Image(file=file, title=title)", "def from_file_map(klass, file_map):\n bvf = file_map['image'].get_prepare_fileobj('rb')\n header = klass.header_class.from_fileobj(bvf)\n affine = header.get_affine()\n hdr_copy = header.copy()\n # use row-major memory presentation!\n data = klass.ImageArrayProxy(bvf, hdr_copy)\n img = klass(data, affine, header, file_map=file_map)\n img._load_cache = {'header': hdr_copy,\n 'affine': None,\n 'file_map': copy_file_map(file_map)}\n return img", "def get_img_obj(file_path):\n try:\n img = Image.open(file_path)\n except IOError as ioe:\n print ioe, \", skipping:\", file_path\n return False\n if img.format:\n return img\n return False", "def image(self):\n if self.has_metadata:\n self.extract_metadata()\n tempdir_path = self.make_tempdir()\n tempfile_path = os.path.join(tempdir_path, self.filename)\n warnings.simplefilter('error', Image.DecompressionBombWarning)\n try: # Do image conversions\n with Image.open(self.src_path) as img_in:\n with Image.frombytes(img_in.mode, img_in.size, img_in.tobytes()) as img_out:\n img_out.save(tempfile_path)\n self.src_path = tempfile_path\n except Exception as e: # Catch decompression bombs\n # TODO: change this from all Exceptions to specific DecompressionBombWarning\n self.add_error(e, \"Caught exception (possible decompression bomb?) while translating file {}.\".format(self.src_path))\n self.make_dangerous('Image file containing decompression bomb')\n if not self.is_dangerous:\n self.add_description('Image file')", "def fromFile(cls, file_name):\n try:\n ds = gdal.Open(file_name)\n return Raster(ds)\n except (RuntimeError, TypeError, NameError) as e:\n raise e", "def get_image(source, exif_orientation=True, **options):\n # Use a StringIO wrapper because if the source is an incomplete file like\n # object, PIL may have problems with it. For example, some image types\n # require tell and seek methods that are not present on all storage\n # File objects.\n\n source = StringIO(source.read())\n\n image = Image.open(source)\n # Fully load the image now to catch any problems with the image\n # contents.\n image.load()\n\n if exif_orientation:\n image = _exif_orientation(image)\n return image", "def open_image(filename):\n return Image.open(filename)", "def open_image():\n rawData = open(\"rose.raw\", 'rb').read()\n imgSize = (256, 256) \n img = Image.frombytes('L', imgSize, rawData)\n original_image = np.asarray(img)\n\n return original_image", "def read_image(self, path: str) -> Image:\n raise NotImplementedError", "def from_file(cls, view_position, imgfile):\n img = plt.imread(imgfile)\n return cls(view_position, img, img)", "def _get_image(self):\n attr_name = '_image_cache'\n if not getattr(self, attr_name, None):\n self.seek(0)\n setattr(self, attr_name, Image.open(self.file))\n return getattr(self, attr_name)", "def load() -> Image:\r\n image = load_image(choose_file())\r\n show(image)\r\n return image", "def sample_loader(sample_path: str) -> Image:\n image = Image.open(sample_path).convert(\"RGB\")\n return image", "def from_image_UI(cls):\n obj = cls()\n obj.load_image_UI()\n return obj", "def get_image(self, name, pil=False):\n image = Image.open(BytesIO(self.get_file(name).read()))\n if pil:\n return image\n return to_tensor(image)", "def load_image(self, idx):\n\n path = self.__image_folder / self.imgs[idx][\"file_name\"]\n return Image.open(path)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create an empty PIL Image.
def create_empty_pil_image(pil_image): return Image.new('RGB', (pil_image.size[0], pil_image.size[1]))
[ "def createImage(size, blank=True):\n if blank:\n img = np.zeros(size)\n else:\n img = np.ones(size) * 255\n img = Image.fromarray(img, mode='L')\n return img", "def empty_image(request):\n channels = request.param\n data_shape = (4, 8, 12, channels)\n return np.zeros(data_shape).astype(ART_NUMPY_DTYPE)", "def init_image(self):\n \n self.img = Image.new('L', \n (self.bitmap_width, self.bitmap_height), 'black')\n self.draw = ImageDraw.Draw(self.img)\n self.draw.fontmode = '1' # No antialiasing", "def get_pil_image(self):\n image = PILImage.new(\"RGBA\", (self.width, self.height),\n (255, 255, 255, 0))\n draw = ImageDraw.Draw(image)\n for x in range(self.width):\n for y in range(self.height):\n if self.pixel_matrix[x][y] == BinaryPixelEnum.BLACK:\n draw.point((x, y), fill=\"black\")\n del draw\n return image", "def blank(klass, width, height, internal_format=GL.GL_RGBA):\n return Texture((width, height), internal_format)", "def getEmpty(self, channels = 3):\n\n\n bitmap = cv.CreateImage(self.size(), cv.IPL_DEPTH_8U, channels)\n cv.SetZero(bitmap)\n return bitmap", "def generate_image(self) -> None:", "def create(width,height,depth):\r\n\r\n # Creating the image.\r\n im = mambaCore.MB_Image()\r\n err = mambaCore.MB_Create(im,width,height,depth)\r\n raiseExceptionOnError(err)\r\n \r\n return im", "def _create_image(self, file, title=None):\n return Image(file=file, title=title)", "def create(IMGSIZE=...) -> retval:\n ...", "def clear(self):\n \n img = Image.new('RGBA', (self.bitmap_width, self.bitmap_height),\n 'black')\n self.bitmap(img)", "def _png_no_image(path_to_image, width):\n\n font = None\n font_path = _supply_font()\n\n if font is not None:\n font_path = ImageFont.truetype(font_path, size=(int(width / 8)))\n else:\n font = ImageFont.load_default()\n\n white = (255, 255, 255)\n black = (0, 0, 0)\n img = Image.new(\"RGBA\", (width, width), white)\n draw = ImageDraw.Draw(img)\n draw.multiline_text(\n (width / 4, width / 3),\n \"No image\\n available\",\n font=font,\n align=\"center\",\n fill=black,\n )\n draw = ImageDraw.Draw(img)\n img.save(path_to_image)", "def create_new_image(self):\n logging.info('Starting image \\'' + self.name + '\\' creation')", "def new(self,matrix):\n\n\t\twidth = len(matrix[0])\n\t\theight = len(matrix)\n\t\tim = PIL.Image.new('RGB', (width, height))\n\t\tim.putdata(_flatten_matrix(matrix))\n\t\treturn im", "def create_pil_image(filepath):\n\n try:\n image = Image.open(filepath)\n except FileNotFoundError as e:\n print(e, f\"{filepath} is not a valid path to an image\")\n\n return image", "def create_random_image(self):\n self.image = np.zeros((self.height, self.width, 3), np.uint8)\n\n for _ in range(self.shapes_size):\n self.shape_functions_dict[self.shape]()", "def __init__(self,\n source_image_path: str,\n source_image_size: Tuple[int, int],\n output_image_path: str,\n output_image_size: Tuple[int, int]) -> None:\n assert source_image_size >= (1, 1), \"Source image size cannot be zero or negative.\"\n assert output_image_size >= (1, 1), \"Output image size cannot be zero or negative.\"\n self.__source_image = Image(source_image_path)\n self.__source_image_size = source_image_size\n self.__output_image = Image(output_image_path)\n self.__output_image_size = output_image_size", "def New(*args, **kargs):\n obj = itkImageULL4.__New_orig__()\n from itk.support import template_class\n template_class.New(obj, *args, **kargs)\n return obj", "def New(*args, **kargs):\n obj = itkImageBase4.__New_orig__()\n from itk.support import template_class\n template_class.New(obj, *args, **kargs)\n return obj" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Resize PIL image object, fixing largest dimension to 1080px.
def resize_pil_image(image): width = image.size[0] height = image.size[1] ratio = width / height if ratio >= 1: width = 810 height = int(width / ratio) else: height = 810 width = int(height * ratio) return image.resize((width, height))
[ "def resize_image(image, size):\n image.thumbnail(size)\n return image", "def setImagesize(self, W, H) -> None:\n ...", "def resizeImage(path):\n temp_pic = Image.open(path,mode='r')\n temp_pic = temp_pic.resize((200,200))\n temp_pic.save(path)", "def resize_image(img, new_width, new_height):\n img_new = img.resize((new_width, new_height))\n return img_new", "def resize_image(img, size):\n # Resize\n n_x, n_y = img.size\n if n_y > n_x:\n n_y_new = size\n n_x_new = int(size * n_x / n_y + 0.5)\n else:\n n_x_new = size\n n_y_new = int(size * n_y / n_x + 0.5)\n img_res = img.resize((n_x_new, n_y_new), resample=PIL.Image.BICUBIC)\n\n # Pad the borders to create a square image\n img_pad = Image.new('RGB', (size, size), (128, 128, 128))\n ulc = ((size - n_x_new) // 2, (size - n_y_new) // 2)\n img_pad.paste(img_res, ulc)\n return img_pad", "def scale_image(self, image, new_width=100):\n (original_width, original_height) = image.size\n aspect_ratio = original_height/float(original_width)\n new_height = int(aspect_ratio * new_width)\n\n new_image = image.resize((new_width, new_height))\n return new_image", "def resize(self, newSize):\n\n\t\tif self.kwargs[\"borderSize\"]:\n\t\t\tself.image = stretch_image(self.image, newSize, \\\n\t\t\tself.kwargs[\"borderSize\"])\n\t\telse:\n\t\t\tself.image = resize_image(self.image, newSize, \\\n\t\t\t\tself.kwargs[\"antialiasing\"])\n\t\tself.kwargs[\"size\"] = tuple(newSize)", "def resize_picture(picture, size):\n\tif picture.size[0] < picture.size[1]:\n\t\twidth = size[0]\n\t\t#import pdb; pdb.set_trace()\n\t\theight = int((float(picture.size[1])/picture.size[0]) * size[0])\n\telif picture.size[1] < picture.size[0]:\n\t\theight = size[1]\n\t\twidth = int((float(picture.size[0])/picture.size[1]) * size[1])\n\telse:\n\t\twidth = size[0]\n\t\theight = size[1]\n\n\tpicture = picture.resize((width, height))\n\treturn picture", "def _resize_pillars(self):\n self.image = pygame.transform.smoothscale(self.image, (100, 650))", "def resize_img(img, w=224, h=224):\n return img.resize((w, h), Image.ANTIALIAS)", "def main_shrink_resolution():\n img = cv2.imread(IMAGE_GRAY)\n images = [(n, shrink_resolution(img, n)) for n in (3,5,7,20,100)]\n show_images(images)", "def resize_image(*args, **kwargs): # real signature unknown; restored from __doc__\n pass", "def Expand(image):\r\n\treturn resize_image(image, 2)", "def _resize(self):\n avg_frames = 87 #this is the average image frame length in the entire dataset\n for i in range(len(self.data)):\n image = self.data[i]\n self.data[i] = resize(image, width=avg_frames, height=len(image))", "def resize_image(image, size):\n return skimage.transform.resize(image, size, preserve_range=True)", "def resize_pic(inp_pic, x=64, y=64):\n out_pic = cv.resize(inp_pic, (y, x), interpolation=cv.INTER_AREA)\n return out_pic", "def resize(frame, height, width):\n\n if height and width >= 1000:\n return cv2.resize(frame,(r(height*0.5), r(width*0.5)))\n\n elif height and width >= 2500:\n return cv2.resize(frame, (r(height*0.7), r(width*0.7)))\n else:\n return cv2.resize(frame, (height, width))", "def set_output_image_size(self, width=512, height=512):\r\n self._renderWindow.SetSize(width, height)", "def maintain_aspect_ratio_resize(image, long_edge_size):\r\n width, height = image.size\r\n if width > height:\r\n height = int(height * long_edge_size / width)\r\n width = long_edge_size\r\n else:\r\n width = int(width * long_edge_size / height)\r\n height = long_edge_size\r\n #image = image.resize((width, height), Image.ANTIALIAS)\r\n image = image.resize((width, height), Image.BILINEAR)\r\n return image" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Covert RGB threetuple and sort newly converted HLS data.
def refactor_and_sort_data(color_data): return sorted(color_data)
[ "def actual_pixel_sort(color_data):\n color_data = [tuple(rgb_shift(i) for i in toop) for toop in color_data]\n return color_data", "def rgb_sort(colours, reverse=False):\n sorted_col = sorted(colours, reverse=reverse)\n return sorted_col", "def BGRtoRGBHLS(colours):\n # put them in RGB order\n colours.reverse()\n hls = colorsys.rgb_to_hls(*(col/255 for col in colours))\n return tuple(colours) + tuple(int(col*255) for col in hls)", "def get_sorted_colors():\n\n colors = mcolors.CSS4_COLORS\n\n list_colors = sorted((tuple(mcolors.rgb_to_hsv(mcolors.to_rgb(color))), name) for name, color in colors.items())\n sorted_colors = [x[1] for x in list_colors]\n\n return sorted_colors", "def toHLS(self):\n retVal = self.getEmpty()\n if( self._colorSpace == ColorSpace.BGR or\n self._colorSpace == ColorSpace.UNKNOWN ):\n cv.CvtColor(self.getBitmap(), retVal, cv.CV_BGR2HLS)\n elif( self._colorSpace == ColorSpace.RGB):\n cv.CvtColor(self.getBitmap(), retVal, cv.CV_RGB2HLS)\n elif( self._colorSpace == ColorSpace.HSV ):\n cv.CvtColor(self.getBitmap(), retVal, cv.CV_HSV2RGB)\n cv.CvtColor(retVal, retVal, cv.CV_RGB2HLS)\n elif( self._colorSpace == ColorSpace.XYZ ):\n cv.CvtColor(self.getBitmap(), retVal, cv.CV_XYZ2RGB)\n cv.CvtColor(retVal, retVal, cv.CV_RGB2HLS)\n elif( self._colorSpace == ColorSpace.HLS ):\n retVal = self.getBitmap() \n else:\n warnings.warn(\"Image.toHSL: There is no supported conversion to HSL colorspace\")\n return None\n return Image(retVal, colorSpace = ColorSpace.HLS )", "def _sortTraces(\n self,\n rdt,\n cdt\n ):\n\n tmp_rdt = []\n tmp_cdt = []\n\n if(len(rdt) > 0):\n # first, find background trace: (max 'x')\n rdt.sort(key=lambda t: -1*max(list(t['x'])))\n tmp_rdt.append(rdt[0])\n # then, sort top-to-bottom\n r = rdt[1:]\n r.sort(key=lambda t: -1*min(list(t['y'])))\n tmp_rdt += r\n if(len(cdt) > 0):\n # background trace has max 'y'\n cdt.sort(key=lambda t: -1*max(list(t['y'])))\n tmp_cdt.append(cdt[0])\n # sort left to right\n c = cdt[1:]\n c.sort(key=lambda t: min(list(t['x'])))\n tmp_cdt += c\n\n return(tmp_rdt, tmp_cdt)", "def _get_hls_image(rgb_image):\n\treturn cv2.cvtColor(rgb_image, cv2.COLOR_RGB2HLS)", "def sort_segments(case):\n blue = []\n red = []\n for segment in case:\n\n if segment[-1] == 'B':\n blue.append(int(segment[:-1]))\n else:\n red.append(int(segment[:-1]))\n\n # sort from big to small\n blue.sort(reverse=True)\n red.sort(reverse=True)\n\n return blue, red", "def sort(self):", "def sortRouteData(route_data):\n for i in range(1, len(route_data)):\n j = i\n while j > 0 and ratioComesBefore(route_data[j][\"happy_ratio\"], route_data[j - 1][\"happy_ratio\"]):\n route_data[j - 1], route_data[j] = route_data[j], route_data[j - 1]\n j = j - 1\n return route_data", "def Sort(self, *args):\n return _snap.TIntPrFltH_Sort(self, *args)", "def hsv_to_rgb(hsv):\n hsv = np.asarray(hsv)\n\n # check length of the last dimension, should be _some_ sort of rgb\n if hsv.shape[-1] != 3:\n raise ValueError(\"Last dimension of input array must be 3; \"\n \"shape {shp} was found.\".format(shp=hsv.shape))\n\n # if we got pased a 1D array, try to treat as\n # a single color and reshape as needed\n in_ndim = hsv.ndim\n if in_ndim == 1:\n hsv = np.array(hsv, ndmin=2)\n\n # make sure we don't have an int image\n if hsv.dtype.kind in ('iu'):\n hsv = hsv.astype(np.float32)\n\n h = hsv[..., 0]\n s = hsv[..., 1]\n v = hsv[..., 2]\n\n r = np.empty_like(h)\n g = np.empty_like(h)\n b = np.empty_like(h)\n\n i = (h * 6.0).astype(np.int)\n f = (h * 6.0) - i\n p = v * (1.0 - s)\n q = v * (1.0 - s * f)\n t = v * (1.0 - s * (1.0 - f))\n\n idx = i % 6 == 0\n r[idx] = v[idx]\n g[idx] = t[idx]\n b[idx] = p[idx]\n\n idx = i == 1\n r[idx] = q[idx]\n g[idx] = v[idx]\n b[idx] = p[idx]\n\n idx = i == 2\n r[idx] = p[idx]\n g[idx] = v[idx]\n b[idx] = t[idx]\n\n idx = i == 3\n r[idx] = p[idx]\n g[idx] = q[idx]\n b[idx] = v[idx]\n\n idx = i == 4\n r[idx] = t[idx]\n g[idx] = p[idx]\n b[idx] = v[idx]\n\n idx = i == 5\n r[idx] = v[idx]\n g[idx] = p[idx]\n b[idx] = q[idx]\n\n idx = s == 0\n r[idx] = v[idx]\n g[idx] = v[idx]\n b[idx] = v[idx]\n\n rgb = np.empty_like(hsv)\n rgb[..., 0] = r\n rgb[..., 1] = g\n rgb[..., 2] = b\n\n if in_ndim == 1:\n rgb.shape = (3, )\n\n return rgb", "def membership_sort(patterns, neural_data, sort_duplicates=True):\n high_weights = get_important_neurons(patterns)\n colors = distinct_colors(patterns.shape[0])\n\n do_not_sort, sorted_data, sorted_colors = [], [], []\n for color, pattern in zip(colors, high_weights):\n for neuron in pattern:\n if neuron not in do_not_sort:\n sorted_data.append(neural_data[neuron])\n sorted_colors.append(color)\n\n if not sort_duplicates:\n do_not_sort.append(neuron)\n\n return sorted_data, sorted_colors", "def __sortElements(elts):\n table = openbabel.OBElementTable()\n res = list()\n for e in elts:\n for l in [3,2,1]:\n num = table.GetAtomicNum(e[:l])\n if num > 0:\n res.append(\"%03d%s\" % (num,e))\n break\n res.sort()\n #print \"__sortElements\", res\n del elts[:]\n for e in res: elts.append(e[3:])\n #print \"__sortElements\", elts", "def loadList(h5group, convert=int):\n return sorted(map(lambda p: (convert(p[0]), p[1]), h5group.items()),\n key=lambda item: item[0])", "def legend_sort_val(t):\n val = re.compile(r\"^.*r=(\\S+) .*$\").search(t[0]).groups()[0]\n # Return the negative so high values are first in the vertical legend.\n return float(val) * -1.0", "def sort( self ):\n # define event sources\n sortlist=[]\n if self.infileNa is not None:\n ENa=EventSource(self.infileNa)\n hNa=Histogram(ENa, ADC1+ADC2+ADC3, 'ADC1', 512, label=\"22Na\")\n self.hNa = hNa\n SNa=Sorter(ENa, [hNa] )\n sortlist.append(SNa)\n if self.infileCo is not None:\n ECo=EventSource(self.infileCo)\n hCo=Histogram(ECo, ADC1+ADC2+ADC3, 'ADC1', 512, label=\"60Co\")\n self.hCo = hCo\n SCo=Sorter(ECo, [hCo] )\n sortlist.append(SCo)\n if self.infileCs is not None:\n ECs=EventSource(self.infileCs)\n hCs=Histogram(ECs, ADC1+ADC2+ADC3, 'ADC1', 512, label=\"137Cs\")\n self.hCs = hCs\n SCs=Sorter(ECs, [hCs] )\n sortlist.append(SCs)\n if self.infileAmBe is not None:\n EAmBe=EventSource(self.infileAmBe)\n hAmBe=Histogram(EAmBe, ADC1+ADC2+ADC3, 'ADC1', 512, label='AmBe')\n self.hAmBe = hAmBe\n SAmBe=Sorter(EAmBe, [hAmBe] )\n sortlist.append(SAmBe)\n \n ETAC=EventSource(self.infileTAC)\n hTAC=Histogram(ETAC, ADC1+ADC2+ADC3, 'ADC3', 1024, label='TAC')\n STAC=Sorter(ETAC, [hTAC] )\n self.hTAC = hTAC\n sortlist.append(STAC)\n\n # set calibration channels\n self.calibration.EADC='ADC1'\n self.calibration.TADC='ADC3' # could be just TDC ...\n\n # sort data. eventually must make multistream sorter!\n for s in sortlist:\n sortadc=s.sort()", "def sort_time(self):\n t, r, e = zip(*sorted(zip(self.time, self.rate, self.error)))\n return LightCurve(t=np.array(t), r=np.array(r), e=np.array(e))", "def hls_palette(\n n_colors: int = 6, h: float = 0.01, l: float = 0.6, s: float = 0.65\n) -> Sequence[TupleFloat3]:\n hues = np.linspace(0, 1, n_colors + 1)[:-1]\n hues += h\n hues %= 1\n hues -= hues.astype(int)\n palette = [colorsys.hls_to_rgb(h_i, l, s) for h_i in hues]\n return palette" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
some kind of actual pixel sorting to make art or at least try
def actual_pixel_sort(color_data): color_data = [tuple(rgb_shift(i) for i in toop) for toop in color_data] return color_data
[ "def paintSortBuf( self, nFigID, center ):\n #print(dir(cv2))\n #cv2.floodFill( self.sortbuf, nFigID, center, 255 ) # todo: find right command\n cv2.circle( self.sortbuf, (center[0],center[1]), 40, (nFigID), 100 ) # temp sprout\n print( self.sortbuf[0,0] )\n print( self.sortbuf[center[1],center[0]] )\n pass\n # TODO: do the same than in repaintAll", "def intake(self): \n\n # first turn each line into a 'tuple'\n # and create a list from the 'tuples'\n file_lines = [] \n\n with open(self.path, \"r\") as data_file:\n lines = data_file.readlines()\n for line in lines:\n line_tuple = line.rstrip().split(\",\")\n file_lines.append(line_tuple) \n\n # create the unordered bitmap \n unsorted_bitmap = self.createBitmap(file_lines)\n self.unsorted_bitmap = unsorted_bitmap\n\n # create the ordered bitmap\n sorted_bitmap = self.createBitmap(sorted(file_lines))\n self.sorted_bitmap = sorted_bitmap", "def decode(imprefix_color,imprefix,start,threshold_color,threshold):\n nbits = 10\n \n imgs = list()\n imgs_inv = list()\n print('loading',end='')\n for i in range(start,start+2*nbits,2):\n fname0 = '%s%2.2d.png' % (imprefix,i)\n fname1 = '%s%2.2d.png' % (imprefix,i+1)\n print('(',i,i+1,')',end='')\n img = plt.imread(fname0)\n img_inv = plt.imread(fname1)\n if (img.dtype == np.uint8):\n img = img.astype(float) / 256\n img_inv = img_inv.astype(float) / 256\n if (len(img.shape)>2):\n img = np.mean(img,axis=2)\n img_inv = np.mean(img_inv,axis=2)\n imgs.append(img)\n imgs_inv.append(img_inv)\n \n (h,w) = imgs[0].shape\n print('\\n')\n \n gcd = np.zeros((h,w,nbits))\n mask = np.ones((h,w))\n for i in range(nbits):\n gcd[:,:,i] = imgs[i]>imgs_inv[i]\n mask = mask * (np.abs(imgs[i]-imgs_inv[i])>threshold)\n \n bcd = np.zeros((h,w,nbits))\n bcd[:,:,0] = gcd[:,:,0]\n for i in range(1,nbits):\n bcd[:,:,i] = np.logical_xor(bcd[:,:,i-1],gcd[:,:,i])\n \n code = np.zeros((h,w))\n for i in range(nbits):\n code = code + np.power(2,(nbits-i-1))*bcd[:,:,i]\n \n #Note:!we need to make use of the color instead of convering to grayscale...\n #...since the object and the background could have the same gray level/brightness but be different colors!\n imc1 = plt.imread(imprefix_color +\"%02d\" % (0)+'.png')\n imc2= plt.imread(imprefix_color +\"%02d\" % (1)+'.png')\n color_mask = np.ones((h,w))\n color_mask = color_mask*((np.sum(np.square(imc1-imc2), axis=-1))>threshold_color)\n\n return code,mask,color_mask", "def fancyConvert(image):", "def test_g_et_pix(self):\n pass", "def im_split_z(data,dim,depth):\r\n\r\n\tn_tot = len(data[0][:,0]) #number of events\r\n\r\n\t#define lattice to insert energies into to creta images\r\n\tx_ref = np.linspace(x_min,x_max,dim)\r\n\ty_ref = np.linspace(y_min,y_max,dim)\r\n\tz_ref = np.linspace(z_min,z_max,depth)\r\n\r\n\th=0 #count events\r\n\tim_array = np.zeros(n_tot,dim,dim,depth)\r\n\r\n\twhile h<n_tot: #loop over events\r\n\r\n\t\tim_tab = np.zeros((dim,dim,depth)) #array to contain constructed image\r\n\r\n\t\t#remove empty hits\r\n\t\tind_nul = np.where(data[3][h,:]==0)[0]\r\n\t\tx_tab = data[0][h,:ind_nul]\r\n\t\ty_tab = data[1][h,:ind_nul]\r\n\t\tz_tab = data[2][h,:ind_nul]\r\n\t\te_tab = data[3][h,:ind_nul]\r\n\r\n\t\tfor i in range(len(e_tab)): #loop over hits within event\r\n\r\n\t\t\tx_coord = np.argmin(np.abs(x_ref-x_tab[i]))\r\n\t\t\ty_coord = np.argmin(np.abs(y_ref-y_tab[i]))\r\n\t\t\tz_coord = np.argmin(np.abs(z_ref-z_tab[i]))\r\n\r\n\t\t\tim_array[h,x_coord,y_coord,z_coord] += e_tab[i]\r\n\r\n\r\n\t\t#show a few plots of actual event vs events converted to picture\r\n\t\t\"\"\"\r\n\t\tif h<5:\r\n\t\t\tdata_actual = [x_tab,y_tab,z_tab,e_tab]\r\n\t\t\tdata_comp = im_array[h,:,:,:]\r\n\t\t\tplot_scatter(data_actual,data_comp,depth)\r\n\t\t\"\"\"\r\n\t\th+=1 #next event\r\n\r\n\t\tif h % 10000 == 0:\r\n\t\t\tprint('{}% completed'.format(h/n_tot*100))\r\n\r\n\treturn im_array", "def test_z_order_images(make_test_viewer):\n data = np.ones((10, 10))\n\n viewer = make_test_viewer(show=True)\n viewer.add_image(data, colormap='red')\n viewer.add_image(data, colormap='blue')\n screenshot = viewer.screenshot(canvas_only=True)\n center = tuple(np.round(np.divide(screenshot.shape[:2], 2)).astype(int))\n # Check that blue is visible\n np.testing.assert_almost_equal(screenshot[center], [0, 0, 255, 255])\n\n viewer.layers[0, 1] = viewer.layers[1, 0]\n screenshot = viewer.screenshot(canvas_only=True)\n center = tuple(np.round(np.divide(screenshot.shape[:2], 2)).astype(int))\n # Check that red is now visible\n np.testing.assert_almost_equal(screenshot[center], [255, 0, 0, 255])", "def gridrefactorobjs(self):\r\n objwidths, objheights, shortestx, shortesty = [], [], [], []\r\n furtheestleft, furthestup, shortestxt2, shortestyt2 = 100, 100, 100, 100\r\n for objno, obj1 in enumerate(self.predoutputsamecolobjs):\r\n if len(self.predoutputsamecolobjs[objno+1:]) != 0:\r\n for obj2 in self.predoutputsamecolobjs[objno+1:]:\r\n shortestxt1 = obj2.positionabsx - obj1.positionabsx\r\n shortestyt1 = obj2.positionabsy - obj1.positionabsy\r\n\r\n if (shortestxt1 > 0) & (shortestxt1 < shortestxt2) & (obj2.positionabsy == obj1.positionabsy):\r\n shortestxt2 = shortestxt1\r\n\r\n if (shortestyt1 > 0) & (shortestyt1 < shortestyt2) & (obj2.positionabsx == obj1.positionabsx):\r\n shortestyt2 = shortestyt1\r\n\r\n shortestx = shortestx + [shortestxt2]\r\n shortesty = shortesty + [shortestyt2]\r\n objwidths = objwidths + [obj1.elementarr.shape[1]]\r\n objheights = objheights + [obj1.elementarr.shape[0]]\r\n\r\n if obj1.positionabsx < furtheestleft:\r\n furtheestleft = obj1.positionabsx\r\n topleftx = obj1.positionabsx\r\n toplefty = obj1.positionabsy\r\n\r\n if obj1.positionabsy < furthestup:\r\n furthestup = obj1.positionabsy\r\n toplefty = obj1.positionabsy\r\n\r\n mostfreqwidth = max(set(objwidths), key=objwidths.count)\r\n mostfreqheight = max(set(objheights), key=objheights.count)\r\n mostfreqx = max(set(shortestx), key=shortestx.count)\r\n mostfreqy = max(set(shortesty), key=shortesty.count)\r\n\r\n # sense-check at this point\r\n if (mostfreqwidth >= mostfreqx) or (mostfreqheight >= mostfreqy):\r\n self.gridapplied = 0\r\n return\r\n\r\n # use these numbers to set your grid & rep obj size. If you can account for all pixels in each obj: good.\r\n # start at top left obj\r\n bwfullimg = (self.fullpredimg != self.backgroundcol) * 1\r\n pixelscounted = 0\r\n xpos = topleftx\r\n ypos = toplefty\r\n newobjrefactor = []\r\n rowsize = 0\r\n objlist = []\r\n counter = 0\r\n outputcanvas = np.zeros([bwfullimg.shape[0], bwfullimg.shape[1]])\r\n\r\n while (ypos + mostfreqheight) <= bwfullimg.shape[0]:\r\n while (xpos + mostfreqwidth) <= bwfullimg.shape[1]:\r\n bwarr1 = bwfullimg[ypos:ypos+mostfreqheight, xpos:xpos+mostfreqwidth] # bw array for counting obj pixels\r\n bwarr = deepcopy(outputcanvas)\r\n bwarr[ypos:ypos+mostfreqheight, xpos:xpos+mostfreqwidth] = bwarr1\r\n colarr = self.fullpredimg[ypos:ypos+mostfreqheight, xpos:xpos+mostfreqwidth] # colarr for making newobj\r\n pixelscounted = pixelscounted + bwarr.sum() # count the pixels\r\n\r\n if len(np.delete(np.unique(colarr), np.where(np.unique(colarr) == 0))) == 1: # rem backcol & chek 1 col left\r\n specificcolour = np.delete(np.unique(colarr), np.where(np.unique(colarr) == 0))[0]\r\n newobj = SameColourObject(bwarr, specificcolour)\r\n newobjrefactor = newobjrefactor + [newobj]\r\n objlist = objlist + [counter]\r\n else:\r\n objlist = objlist + [None]\r\n xpos = xpos + mostfreqx\r\n counter += 1\r\n rowsize += 1\r\n xpos = topleftx\r\n ypos = ypos + mostfreqy\r\n\r\n objgrid = np.array(objlist).reshape([rowsize, int(counter/rowsize)])\r\n\r\n if pixelscounted == bwfullimg.sum(): # if all objs are accounted for, re-factor objs into grid format\r\n self.predoutputsamecolobjs = newobjrefactor\r\n self.gridapplied = 1\r\n # self.objgrid = objgrid\r\n print('refactored by seperating by obj grid')\r\n else:\r\n self.gridapplied = 0", "def solve(images):\n width = images[0].width\n height = images[0].height\n result = SimpleImage.blank(width, height)\n ######## YOUR CODE STARTS HERE #########\n\n for x in range(width):\n for y in range(height):\n pixels = []\n for each in images:\n pixel = each.get_pixel(x, y)\n pixels.append(pixel)\n best = get_best_pixel(pixels)\n\n new = result.get_pixel(x, y)\n new.red = best.red\n new.green = best.green\n new.blue = best.blue\n\n # Write code to populate image and create the 'ghost' effect\n\n # Code to check milestone 1.\n\n # green_im = SimpleImage.blank(20, 20, 'green')\n # green_pixel = green_im.get_pixel(0, 0)\n # print(get_pixel_dist(green_pixel, 5, 255, 10))\n\n # Code to check milestone 2.\n\n # green_pixel =SimpleImage.blank(20, 20, 'green').get_pixel(0, 0)\n # red_pixel = SimpleImage.blank(20, 20, 'red').get_pixel(0, 0)\n # blue_pixel = SimpleImage.blank(20, 20, 'blue').get_pixel(0, 0)\n # print(get_average([green_pixel, green_pixel, green_pixel, blue_pixel]))\n\n # Code to check milestone 3.\n\n # green_pixel = SimpleImage.blank(20, 20, 'green').get_pixel(0, 0)\n # red_pixel = SimpleImage.blank(20, 20, 'red').get_pixel(0, 0)\n # blue_pixel = SimpleImage.blank(20, 20, 'blue').get_pixel(0, 0)\n # best1 = get_best_pixel([green_pixel, blue_pixel, blue_pixel])\n # print(best1.red, best1.green, best1.blue)\n\n\n ######## YOUR CODE ENDS HERE ###########\n print(\"Displaying image!\")\n result.show()", "def invert(self):\n if self._pixels is None:\n self._pixels = [[3]*TILESIZE for _ in range(TILESIZE)]\n else:\n self._pixels = [ [ (3-val) for val in row] for row in self._pixels ]", "def do_sort(pixels, sort_func, reverse=False):\n pos = [pixel[\"pos\"] for pixel in pixels]\n col = [pixel[\"col\"] for pixel in pixels]\n\n sorted_col = sort_func(col, reverse)\n\n #combine back to positions\n out = [{\"pos\":pos, \"col\":col} for (pos,col) in zip(pos,sorted_col)]\n return out", "def _renorm(self):\n #convert all to lowest level\n self._demote_all()\n #store this for later\n self.demoted=self.pixeldict\n #now promote as needed\n for d in xrange(self.maxdepth,2,-1):\n plist=self.pixeldict[d].copy()\n for p in plist:\n if p%4==0:\n nset=set((p,p+1,p+2,p+3))\n if p+1 in plist and p+2 in plist and p+3 in plist:\n # if nset.intersection(plist) != set():\n #remove the four pixels from this level\n self.pixeldict[d].difference_update(nset)\n #add a new pixel to the next level up\n self.pixeldict[d-1].add(p/4)\n return", "def __create_image(self, sortedShreds, start):\n newImage = Image.new('RGB', self.__imageSize)\n sortedShreds = self.__compare()\n col1 = start\n \n for col2 in xrange(0, self.__shredCount):\n col1x1 = col1 * self.__shredSize\n col1x2 = col1x1 + self.__shredSize\n shred = self.__image.crop((col1x1, 0, col1x2, self.__imageSize[1] -1))\n col2x1 = self.__shredSize * col2\n newImage.paste(shred, (col2x1, 0))\n col1 = sortedShreds[col1][0]\n \n newImage.save(self.__outputFilename, 'JPEG')", "def GetPixelAspect(self):\n ...", "def test():\n\tprint(\"Reading the pickle file...\")\n\tpickle_file = open(\"./camera_cal.pk\", \"rb\")\n\tdist_pickle = pickle.load(pickle_file)\n\tmtx = dist_pickle[\"mtx\"] \n\tdist = dist_pickle[\"dist\"]\n\tpickle_file.close()\n\n\tprint(\"Reading the sample image...\")\n\timg = mpimg.imread('./corners_found2.jpg')\n\timg_size = (img.shape[1],img.shape[0])\n\tdst = cv2.undistort(img, mtx, dist, None, mtx)\n\n\t# dst = cv2.cvtColor(dst, cv2.COLOR_BGR2GRAY)\n\t# Visualize undistortion\n\tprint(\"Visulize the result...\")\n\tf, (ax1,ax2) = plt.subplots(1,2, figsize=(20,10))\n\tax1.imshow(img), ax1.set_title('Original Image', fontsize=15)\n\tax2.imshow(dst), ax2.set_title('Undistored Image', fontsize=15)\n\tplt.show()", "def test_image_inverted(self):\n star = Starshot.from_demo_image()\n top_left_corner_val_before = star.image.array[0, 0]\n star.image.check_inversion_by_histogram(percentiles=[4, 50, 96])\n top_left_corner_val_after = star.image.array[0, 0]\n self.assertNotEqual(top_left_corner_val_before, top_left_corner_val_after)", "def _renorm(self):\n self.demoted = set()\n # convert all to lowest level\n self._demote_all()\n # now promote as needed\n for d in range(self.maxdepth, 2, -1):\n plist = self.pixeldict[d].copy()\n for p in plist:\n if p % 4 == 0:\n nset = set((p, p+1, p+2, p+3))\n if p+1 in plist and p+2 in plist and p+3 in plist:\n # remove the four pixels from this level\n self.pixeldict[d].difference_update(nset)\n # add a new pixel to the next level up\n self.pixeldict[d-1].add(p/4)\n self.demoted = set()\n return", "def draw_no_caching(self) -> List[int]:\n # sample might be faster?\n if not HAVE_NUMPY:\n # slower\n random.shuffle(EIGHTY_NUMBERS)\n else:\n # faster\n np.random.shuffle(EIGHTY_NUMBERS)\n\n drawing = EIGHTY_NUMBERS[0 : self.spots]\n list.sort(drawing)\n return drawing", "def buildWinterImage():\n img = Image.open(\"terrain.png\")\n terrainImage = list(Image.open(\"terrain.png\").getdata())\n terrainArray = []\n cols = 0\n row = []\n for pixel in terrainImage:\n row.append(pixel)\n cols += 1\n if cols == 395:\n cols = 0\n terrainArray.append(row)\n row = []\n for row in range(500):\n for col in range(395):\n # checking if the pixel is in water\n if terrainTypes[terrainArray[row][col][:3]] == \"lake\" or \\\n terrainTypes[terrainArray[row][col][:3]] == \"ice\":\n edge = False\n # checking if this is the edge of the water body\n if col+1 < 395 and (terrainTypes[terrainArray[row][col+1][:3]] != \"lake\"\\\n and terrainTypes[terrainArray[row][col+1][:3]] != \"ice\"):\n edge = True\n elif col-1 >= 0 and (terrainTypes[terrainArray[row][col-1][:3]] != \"lake\"\\\n and terrainTypes[terrainArray[row][col-1][:3]] != \"ice\"):\n edge = True\n elif row+1 < 500 and (terrainTypes[terrainArray[row+1][col][:3]] != \"lake\"\\\n and terrainTypes[terrainArray[row+1][col][:3]] != \"ice\"):\n edge = True\n elif row-1 >= 0 and (terrainTypes[terrainArray[row-1][col][:3]] != \"lake\"\\\n and terrainTypes[terrainArray[row-1][col][:3]] != \"ice\"):\n edge = True\n if edge:\n # converting water to ice\n for i in range(7):\n if col+i > 394 or (terrainTypes[terrainArray[row][col+i][:3]] != \"lake\"\\\n and terrainTypes[terrainArray[row][col+i][:3]] != \"ice\"):\n break\n else:\n img.putpixel((col+i,row),(100,200,255))\n for i in range(7):\n if col-i < 0 or (terrainTypes[terrainArray[row][col-i][:3]] != \"lake\"\\\n and terrainTypes[terrainArray[row][col-i][:3]] != \"ice\"):\n break\n else:\n img.putpixel((col-i,row),(100,200,255))\n for i in range(7):\n if row+i > 499 or (terrainTypes[terrainArray[row+i][col][:3]] != \"lake\"\\\n and terrainTypes[terrainArray[row+i][col][:3]] != \"ice\"):\n break\n else:\n img.putpixel((col,row+i),(100,200,255))\n if row-i < 0 or (terrainTypes[terrainArray[row-i][col][:3]] != \"lake\"\\\n and terrainTypes[terrainArray[row-i][col][:3]] != \"ice\"):\n break\n else:\n img.putpixel((col,row-i),(100,200,255))\n return img" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the is_password_set of this StorageRemoteKeySettingAllOf.
def is_password_set(self, is_password_set): self._is_password_set = is_password_set
[ "def _set_isPassword(self, *args) -> \"bool\" :\n return _core.StringValueCommandInput__set_isPassword(self, *args)", "def is_encryption_key_set(self, is_encryption_key_set):\n\n self._is_encryption_key_set = is_encryption_key_set", "def _setSavePassword(self, checked):\r\n\r\n self.savePasswordCheckBox.setChecked(checked)", "def set_credentials(self, password):\n\t\tself.password = password", "def password(self, password):\n self._configuration.password = password", "def set_password(self, password):\n self.password_hash = generate_password_hash(password)", "def test_set_password_mode(self):\n self.server_widget.password_mode = 'silent'\n assert self.client_widget.password_mode == self.server_widget.password_mode", "def _password(self, new_password):\n self.__password = new_password", "def force_password_change(self, value):\n self._force_password_change = bool(value)", "def _set_password(site, login, password):\n try:\n keyring.set_password(site, login, password)\n except:\n return", "def can_change_password(self, can_change_password):\n\n self._can_change_password = can_change_password", "def syncPasswords(self):\n raise NotImplementedError", "def rcon_set_rcon_password(self, password):\n result = self.send_rcon_command(RCON_RCON_PASSWORD, args=(password,))\n self.rcon_password = password", "def set_password_mode(self, mode):\n if mode:\n self.send_raw(bytes([IAC, WILL, ECHO]))\n else:\n self.send_raw(bytes([IAC, WONT, ECHO]))", "def toggle_password(self, show_password):\n textbox_type = self.get_attribute(\n 'type', WD_PF.SELENIUM.SHOW_PASSWORD_INPUT\n )\n\n if show_password and textbox_type == 'password':\n self.button(WD_PF.SELENIUM.SHOW_PASSWORD)", "def set_password_login(boolean):\n\n if boolean == \"True\":\n sed(\"/etc/ssh/sshd_config\", \"PasswordAuthentication no\",\n \"#PasswordAuthentication yes\", use_sudo=True)\n\n elif boolean == \"False\":\n sed(\"/etc/ssh/sshd_config\", \"#PasswordAuthentication yes\",\n \"PasswordAuthentication no\", use_sudo=True)", "def change_password(self, password):\r\n self.password = password", "def set_server_password(self, password: str):\n return self._request_handler(json={\n \"jsonrpc\": \"2.0\",\n \"id\": \"rpc_call_id\",\n \"method\": \"SetServerPassword\",\n \"params\": {\n \"PlainTextPassword_str\": password\n }\n })", "def _get_isPassword(self) -> \"bool\" :\n return _core.StringValueCommandInput__get_isPassword(self)", "def _save_pass(self, password):\n keyring.set_password('PyBox', self.cfg['user'], password)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the primary_server of this StorageRemoteKeySettingAllOf.
def primary_server(self, primary_server): self._primary_server = primary_server
[ "def _set_server_mode_primary(server, mode):\n allowed_mode = \\\n (_server.MySQLServer.WRITE_ONLY, _server.MySQLServer.READ_WRITE)\n _do_set_server_mode(server, mode, allowed_mode)", "def _set_server_status_primary(server, update_only):\n raise _errors.ServerError(\n \"If you want to make a server (%s) primary, please, use the \"\n \"group.promote function.\" % (server.uuid, )\n )", "def set_master(self, master):\n self.master_host = master", "def __set_minion_master(self):\n master_id = self.master_remote.hostname\n for rem in self.remotes.iterkeys():\n # remove old master public key if present. Minion will refuse to\n # start if master name changed but old key is present\n delete_file(rem, '/etc/salt/pki/minion/minion_master.pub',\n sudo=True, check=False)\n\n # set master id\n sed_cmd = ('echo master: {} > '\n '/etc/salt/minion.d/master.conf').format(master_id)\n rem.run(args=[\n 'sudo',\n 'sh',\n '-c',\n sed_cmd,\n ])", "def set_primary(self, card_id):\n data = {'payment_object_id': card_id}\n response = requests.put(self.endpoint + '/set_primary', headers=self.headers, data=data)\n \n return response.json()", "def _set_multi_area_adjacency_primary(self, v, load=False):\n if hasattr(v, \"_utype\"):\n v = v._utype(v)\n try:\n t = YANGDynClass(\n v,\n base=YANGBool,\n default=YANGBool(\"true\"),\n is_leaf=True,\n yang_name=\"multi-area-adjacency-primary\",\n parent=self,\n path_helper=self._path_helper,\n extmethods=self._extmethods,\n register_paths=True,\n namespace=\"http://openconfig.net/yang/network-instance\",\n defining_module=\"openconfig-network-instance\",\n yang_type=\"boolean\",\n is_config=True,\n )\n except (TypeError, ValueError):\n raise ValueError(\n {\n \"error-string\": \"\"\"multi_area_adjacency_primary must be of a type compatible with boolean\"\"\",\n \"defined-type\": \"boolean\",\n \"generated-type\": \"\"\"YANGDynClass(base=YANGBool, default=YANGBool(\"true\"), is_leaf=True, yang_name=\"multi-area-adjacency-primary\", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='boolean', is_config=True)\"\"\",\n }\n )\n\n self.__multi_area_adjacency_primary = t\n if hasattr(self, \"_set\"):\n self._set()", "def SetMasterIpAddress(self, master_ip):\n master = self.master.get()\n master.external_ip = master_ip\n master.put()", "def handle_set_all(self, msg):\n assert isinstance(msg, MSG_SET_ALL)\n\n # Always store the last SET_ALL on the server\n\n self.master.set_contents( msg[\"data\"] )\n\n new_client_id = msg['client_id']\n\n if new_client_id != -1:\n \n for client in self.master.clients:\n \n if client.id == new_client_id:\n\n client.send( MSG_SET_ALL(self.client_id(), self.master.get_contents(), new_client_id) )\n\n break\n \n return", "def setAllMaster(self, master):\n self.logger.info(\"setting master for all leds to %d\"%(master))\n self._connManager.send(self.protocolArne.setMaster(master))", "def set_primary_for_bonding_device(self, bond_port, slave_port, invert_verify=False):\n self.dut.send_expect(\"set bonding primary %d %d\" % (slave_port, bond_port), \"testpmd> \")\n out = self.get_info_from_bond_config(\"Primary: \\[\", \"\\d*\", bond_port)\n if not invert_verify:\n self.verify(str(slave_port) in out,\n \"Set bonding primary port failed\")\n else:\n self.verify(str(slave_port) not in out,\n \"Set bonding primary port successfully,should not success\")", "def SetMasterInstance(self, master_instance):\n self.master = master_instance.key\n self.put()", "def set_keys(self, client_private_key, server_public_key):\n d_client_private_key = Data(client_private_key)\n d_server_public_key = Data(server_public_key)\n status = self._lib_vsce_uokms_client.vsce_uokms_client_set_keys(self.ctx, d_client_private_key.data, d_server_public_key.data)\n VsceStatus.handle_status(status)", "def set_primary_controller(cls, nodes):\n sorted_nodes = sorted(\n nodes, key=lambda node: node['uid'])\n\n primary_controller = cls.filter_by_roles(\n sorted_nodes, ['primary-controller'])\n\n if not primary_controller:\n controllers = cls.filter_by_roles(\n sorted_nodes, ['controller'])\n if controllers:\n controllers[0]['role'] = 'primary-controller'", "def set_Server(self, value):\n super(UpdateTicketInputSet, self)._set_input('Server', value)", "def change_remote_server(self):\n pass", "def configure_master(\n self,\n ssh_client: paramiko.client.SSHClient,\n cluster: FlintrockCluster):\n raise NotImplementedError", "def determine_new_master(self):\n self.master_host = determine_host_address()", "def ammo_type_primary_icon(self, ammo_type_primary_icon):\n\n self._ammo_type_primary_icon = ammo_type_primary_icon", "def assign_clients(self):\n for drone in self.drones:\n if self.solution[drone]:\n drone.specify_client(self.solution[drone].pop(0))", "def is_primary_key(self, is_primary_key):\n\n self._is_primary_key = is_primary_key" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the secondary_server of this StorageRemoteKeySettingAllOf.
def secondary_server(self, secondary_server): self._secondary_server = secondary_server
[ "def fpolicy_set_secondary_servers(self, secondary_servers, policy_name):\n return self.request( \"fpolicy-set-secondary-servers\", {\n 'secondary_servers': [ secondary_servers, 'secondary-servers', [ SecondaryServerInfo, 'None' ], True ],\n 'policy_name': [ policy_name, 'policy-name', [ basestring, 'None' ], False ],\n }, {\n } )", "def _set_server_mode_secondary(server, mode):\n allowed_mode = \\\n (_server.MySQLServer.OFFLINE, _server.MySQLServer.READ_ONLY)\n _do_set_server_mode(server, mode, allowed_mode)", "def _set_server_status_secondary(server, update_only):\n allowed_status = [_server.MySQLServer.SPARE]\n status = _server.MySQLServer.SECONDARY\n mode = _server.MySQLServer.READ_ONLY\n _do_set_status(server, allowed_status, status, mode, update_only)", "def secondary_language(self, secondary_language):\n\n self._secondary_language = secondary_language", "def change_remote_server(self):\n pass", "def push_certs_to_vtm(self, vtm_name, server_certificate_secondary, server_certificate):\n # The VTM requires the CERT as a string without the leading or trailing lines or newline\n server_certificate_st = self.format_cert(server_certificate)\n server_certificate_secondary_st = self.format_cert(server_certificate_secondary)\n\n url = self.VTM_SETTINGS_URL.format(\n url=self.url, vtm_name=vtm_name\n )\n\n data = {\n \"properties\": {\n \"remote_licensing\": {\n }\n }\n }\n\n # Work out which certs need updating. Don't change cert unless we need to.\n # vTM does not error if there is nothing in the put body\n remote_server_certificate, remote_server_cert_secondary = \\\n self.get_vtm_certs(vtm_name)\n\n if remote_server_certificate != server_certificate_st:\n data['properties']['remote_licensing']['server_certificate'] = server_certificate_st\n\n if remote_server_cert_secondary != server_certificate_secondary_st:\n data['properties']['remote_licensing']['server_certificate_secondary'] = \\\n server_certificate_secondary_st\n\n # Fire and forget. The vTM will create a new chanel and this one will close.\n # We won't see the response\n try:\n self.session.put(\n url,\n data=json.dumps(data),\n auth=self.basic_auth,\n verify=self.sd_api_cert_file,\n headers=self.HEADERS,\n timeout=(3.05, 0.5)\n )\n except requests.exceptions.Timeout:\n pass\n\n # Wait for vTM connection to re-establish\n retry_time_limit = datetime.now() + timedelta(seconds=20)\n while not self._is_connection_to_vtm_open(vtm_name) and datetime.now() < retry_time_limit:\n time.sleep(0.1)\n\n # Get the SSL certs to check that the operation happened successfully\n settings_response = self.session.get(\n url, auth=self.basic_auth, verify=self.sd_api_cert_file\n )\n\n vtm_remote_licensing = settings_response.json()['properties']['remote_licensing']\n\n if not (server_certificate_st == vtm_remote_licensing['server_certificate'] or\n server_certificate_secondary_st ==\n vtm_remote_licensing['server_certificate_secondary']):\n raise self.SdApiError('Failed to update vTM {vtm_name}'.format(vtm_name=vtm_name))", "def _configure_as_slave(group, server):\n try:\n if group.master:\n master = _server.MySQLServer.fetch(group.master)\n master.connect()\n _utils.switch_master(server, master)\n except _errors.DatabaseError as error:\n msg = \"Error trying to configure server ({0}) as slave: {1}.\".format(\n server.uuid, error)\n _LOGGER.debug(msg)\n raise _errors.ServerError(msg)", "def set_server(self, observatory):\n url = config.get_server_url(observatory)\n if url is not None:\n api.set_crds_server(url)\n return observatory", "def setSecondary(self, item):\n self.setItem(1, item)", "def secondary_domain(self):\n return self._domains[\"secondary\"]", "def secondaryStrategy(self, strategy):\n assert isinstance(strategy, SimpleStrategy)\n self.__secondaryStrategy = strategy", "def set_Server(self, value):\n super(UpdateTicketInputSet, self)._set_input('Server', value)", "def add_server(self, server):\n assert(isinstance(server, MySQLServer))\n assert(server.group_id == None)\n server.group_id = self.__group_id", "def _set_server_mode_primary(server, mode):\n allowed_mode = \\\n (_server.MySQLServer.WRITE_ONLY, _server.MySQLServer.READ_WRITE)\n _do_set_server_mode(server, mode, allowed_mode)", "def configure(self, server, monitoring):\n # Providers\n for provider in self.providers:\n server.providers_add(provider)\n \n # Services\n for service in self.services:\n monitoring.add(service)", "def check_server_settings(self, server):\n if server.id not in self.settings:\n self.settings[server.id] = {}\n if \"SHEET_ID\" not in self.settings[server.id]:\n self.settings[server.id][\"SHEET_ID\"] = \"\"\n if \"ROLES\" not in self.settings[server.id]:\n self.settings[server.id][\"ROLES\"] = []\n dataIO.save_json(JSON, self.settings)", "def set_ntp_server(self, server, index=0):\n return None", "def update(self):\n new_servers = []\n server_list = remote.list_servers(SERVER_URI)\n organisation_list = remote.list_organisations(ORGANISATION_URI)\n for server_data in server_list:\n server_type = server_data.pop('server_type')\n if server_type == 'institute_access':\n server = InstituteAccessServer(**server_data)\n new_servers.append(server)\n elif server_type == 'secure_internet':\n server = SecureInternetServer(**server_data)\n new_servers.append(server)\n else:\n raise ValueError(server_type, server_data)\n for organisation_data in organisation_list:\n server = OrganisationServer(**organisation_data)\n new_servers.append(server)\n # Atomic update of server map.\n # TODO keep custom other servers\n self.servers = new_servers\n self.is_loaded = True", "def _set_server_status_primary(server, update_only):\n raise _errors.ServerError(\n \"If you want to make a server (%s) primary, please, use the \"\n \"group.promote function.\" % (server.uuid, )\n )", "def _assign_secondary_ip_():\n interface_idx = 0\n node = env.nodes[0]\n cidr='%s/%s' % (env.secondary_ip,env.secondary_ip_cidr_prefix_size)\n\n if (_get_secondary_ip_node_().id == node.id):\n debug(\"VPC Secondary IP %s already assigned to %s\" % (cidr, pretty_instance(node)))\n else:\n info(\"Assigning VPC Secondary IP %s to %s\" % (cidr, pretty_instance(node)))\n connect().assign_private_ip_addresses(node.interfaces[interface_idx].id, env.secondary_ip, allow_reassignment=True)\n # Notify opsys that it has a new address (This seems to only happen automatically with Elastic IPs). Write to /etc to make persistent.\n has_address = run('ip addr | grep %s' % cidr, quiet=True)\n if not has_address:\n sudo('ip addr add %s dev eth0' % cidr)\n append('/etc/network/interfaces','up ip addr add %s dev eth%d' % (cidr,interface_idx),use_sudo=True)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the server_certificate of this StorageRemoteKeySettingAllOf.
def server_certificate(self, server_certificate): self._server_certificate = server_certificate
[ "def set_ServerCertificateName(self, value):\n super(UploadServerCertificateInputSet, self)._set_input('ServerCertificateName', value)", "def set_keys(self, client_private_key, server_public_key):\n d_client_private_key = Data(client_private_key)\n d_server_public_key = Data(server_public_key)\n status = self._lib_vsce_uokms_client.vsce_uokms_client_set_keys(self.ctx, d_client_private_key.data, d_server_public_key.data)\n VsceStatus.handle_status(status)", "def push_certs_to_vtm(self, vtm_name, server_certificate_secondary, server_certificate):\n # The VTM requires the CERT as a string without the leading or trailing lines or newline\n server_certificate_st = self.format_cert(server_certificate)\n server_certificate_secondary_st = self.format_cert(server_certificate_secondary)\n\n url = self.VTM_SETTINGS_URL.format(\n url=self.url, vtm_name=vtm_name\n )\n\n data = {\n \"properties\": {\n \"remote_licensing\": {\n }\n }\n }\n\n # Work out which certs need updating. Don't change cert unless we need to.\n # vTM does not error if there is nothing in the put body\n remote_server_certificate, remote_server_cert_secondary = \\\n self.get_vtm_certs(vtm_name)\n\n if remote_server_certificate != server_certificate_st:\n data['properties']['remote_licensing']['server_certificate'] = server_certificate_st\n\n if remote_server_cert_secondary != server_certificate_secondary_st:\n data['properties']['remote_licensing']['server_certificate_secondary'] = \\\n server_certificate_secondary_st\n\n # Fire and forget. The vTM will create a new chanel and this one will close.\n # We won't see the response\n try:\n self.session.put(\n url,\n data=json.dumps(data),\n auth=self.basic_auth,\n verify=self.sd_api_cert_file,\n headers=self.HEADERS,\n timeout=(3.05, 0.5)\n )\n except requests.exceptions.Timeout:\n pass\n\n # Wait for vTM connection to re-establish\n retry_time_limit = datetime.now() + timedelta(seconds=20)\n while not self._is_connection_to_vtm_open(vtm_name) and datetime.now() < retry_time_limit:\n time.sleep(0.1)\n\n # Get the SSL certs to check that the operation happened successfully\n settings_response = self.session.get(\n url, auth=self.basic_auth, verify=self.sd_api_cert_file\n )\n\n vtm_remote_licensing = settings_response.json()['properties']['remote_licensing']\n\n if not (server_certificate_st == vtm_remote_licensing['server_certificate'] or\n server_certificate_secondary_st ==\n vtm_remote_licensing['server_certificate_secondary']):\n raise self.SdApiError('Failed to update vTM {vtm_name}'.format(vtm_name=vtm_name))", "def set_client_cert_and_key(self, cert_file, key_file):\n\n self.cert_file = cert_file\n if (key_file != None):\n self.key_file = key_file\n else:\n self.key_file = cert_file", "def set_node_certificate(self, pkey_settings):\n params = {}\n\n if pkey_settings:\n params[\"privateKeyPassphrase\"] = pkey_settings\n\n return self._post_json(f'{self.hostname}/node/controller/reloadCertificate', params)", "def _config_selfsigned_certificate(self, context):\n\n mode = constants.CERT_MODE_SSL\n passphrase = None\n certificate_file = constants.SSL_PEM_SS_FILE\n\n # Generate a self-signed server certificate to enable https\n csr_config = \"\"\"\n [ req ]\n default_bits = 2048\n distinguished_name = req_distinguished_name\n prompt = no\n [ req_distinguished_name ]\n CN = StarlingX\n \"\"\"\n\n try:\n with open(os.devnull, \"w\") as fnull:\n openssl_cmd = \"(openssl req -new -x509 -sha256 \\\n -keyout {file} -out {file} -days 365 -nodes \\\n -config <(echo \\\"{config}\\\")) && sync\" \\\n .format(file=certificate_file, config=csr_config)\n subprocess.check_call(openssl_cmd, # pylint: disable=not-callable\n stdout=fnull, stderr=fnull,\n shell=True, executable='/usr/bin/bash')\n except subprocess.CalledProcessError as e:\n LOG.exception(e)\n msg = \"Fail to generate self-signed certificate to enable https.\"\n raise exception.SysinvException(_(msg))\n\n with open(certificate_file) as pemfile:\n pem_contents = pemfile.read()\n\n LOG.info(\"_config_selfsigned_certificate mode=%s file=%s\" % (mode, certificate_file))\n\n cert_list, private_key = \\\n self._extract_keys_from_pem(mode, pem_contents,\n serialization.PrivateFormat.PKCS8,\n passphrase)\n\n personalities = [constants.CONTROLLER]\n\n config_uuid = self._config_update_hosts(context, personalities)\n private_bytes = self._get_private_bytes_one(private_key)\n public_bytes = self._get_public_bytes(cert_list)\n file_content = private_bytes + public_bytes\n config_dict = {\n 'personalities': personalities,\n 'file_names': [constants.SSL_PEM_FILE],\n 'file_content': file_content,\n 'permissions': constants.CONFIG_FILE_PERMISSION_ROOT_READ_ONLY,\n 'nobackup': True,\n }\n self._config_update_file(context, config_uuid, config_dict)\n\n # copy the certificate to shared directory\n with os.fdopen(os.open(constants.SSL_PEM_FILE_SHARED,\n os.O_CREAT | os.O_TRUNC | os.O_WRONLY,\n constants.CONFIG_FILE_PERMISSION_ROOT_READ_ONLY),\n 'wb') as f:\n f.write(file_content)\n\n # Inventory the self signed certificate.\n # In case the self signed cert is ICA signed,\n # skip these intermediate CA certs.\n for cert in cert_list:\n if not cert.get('is_ca', False):\n values = {\n 'certtype': mode,\n 'signature': cert.get('signature'),\n 'start_date': cert.get('cert').not_valid_before,\n 'expiry_date': cert.get('cert').not_valid_after,\n }\n self.dbapi.certificate_create(values)\n break\n else:\n msg = \"Fail to inventory the self signed certificate, \\\n no leaf cert found.\"\n raise exception.SysinvException(_(msg))", "def verify_ssl_certificate(self, value):\n for driver in self.drivers:\n driver.verify_ssl_certificate = value", "def set_CertificateBody(self, value):\n super(UploadServerCertificateInputSet, self)._set_input('CertificateBody', value)", "def set_PrivateKey(self, value):\n super(UploadServerCertificateInputSet, self)._set_input('PrivateKey', value)", "def set_server(self, observatory):\n url = config.get_server_url(observatory)\n if url is not None:\n api.set_crds_server(url)\n return observatory", "def save_kubernetes_rootca_cert(self, context, certificate_file):\n return self.call(context, self.make_msg('save_kubernetes_rootca_cert',\n ca_file=certificate_file))", "def ssl_verify_server_cert(self):\n return \"\"\"--ssl-verify-server-cert\"\"\"", "def vpn_get_server_cert_paths(self):\n vpn_base = os.path.join(self.get_ejbca_home(), 'vpn')\n ca = os.path.join(vpn_base, 'VPN_Server-CA.pem')\n crt = os.path.join(vpn_base, 'VPN_Server.pem')\n key = os.path.join(vpn_base, 'VPN_Server-key.pem')\n return ca, crt, key", "def set_ntp_server(self, server, index=0):\n return None", "def modem_certificate(self, modem_certificate):\n\n self._modem_certificate = modem_certificate", "def set_certs_per_vips():\n (cakey, cacert) = zaza.openstack.utilities.cert.generate_cert(\n ISSUER_NAME,\n generate_ca=True)\n os.environ['TEST_CAKEY'] = base64.b64encode(cakey).decode()\n os.environ['TEST_CACERT'] = base64.b64encode(cacert).decode()\n for vip_name, vip_ip in os.environ.items():\n if vip_name.startswith('TEST_VIP'):\n (key, cert) = zaza.openstack.utilities.cert.generate_cert(\n '*.serverstack',\n alternative_names=[vip_ip],\n issuer_name=ISSUER_NAME,\n signing_key=cakey)\n os.environ[\n '{}_KEY'.format(vip_name)] = base64.b64encode(key).decode()\n os.environ[\n '{}_CERT'.format(vip_name)] = base64.b64encode(cert).decode()", "def validate_server_purpose(self,certificate):\r\n\r\n\t\tserver_auth = x509.oid.ExtendedKeyUsageOID.SERVER_AUTH\r\n\t\textended_key_usages = certificate.extensions.get_extension_for_oid(ExtensionOID.EXTENDED_KEY_USAGE)\r\n\t\treturn any(extension for extension in extended_key_usages.value if extension.dotted_string == server_auth.dotted_string)", "def host_ssl(self, host_ssl):\n\n self._host_ssl = host_ssl", "def set_server_cert_verification(self, enable):\n\n if (enable != True and enable != False):\n return self.fail_response(13001, \"NaServer::set_server_cert_verification: invalid argument \" + str(enable) + \" specified\");\n if (not self.use_https()):\n return self.fail_response(13001,\"in NaServer::set_server_cert_verification: server certificate verification can only be enabled or disabled for HTTPS transport\")\n if (enable == True and ssl_import == False):\n return self.fail_response(13001,\"in NaServer::set_server_cert_verification: server certificate verification cannot be used as 'ssl' module is not imported.\")\n self.need_server_auth = enable\n self.need_cn_verification = enable\n return None", "def server_credentials(self, created_at=None, id=None, server_certificate=None, server_uri=None):\n from mbed_cloud.foundation import ServerCredentials\n\n return ServerCredentials(\n _client=self._client,\n created_at=created_at,\n id=id,\n server_certificate=server_certificate,\n server_uri=server_uri,\n )" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns [Candle] of the last year (if excluding_last = 252 days)
def last_remaining(self): df = pd.read_csv('^GSPC.csv', index_col='Date', parse_dates=True) df = df[-1 * self.excluding_last:] # for example, past 252 days # for 2017 # years_to_chop_off = 10 # 1: chop off 2018 to get just 2017 # df = df[:-252*years_to_chop_off] # print "self.excluding_last", self.excluding_last return Candle.swingCandlesFromDataframe(df)
[ "def last_year(self):\n return self._years[-1]", "def last_close_date(country=\"US\"):\r\n return yyyymmdd(n_trading_days_before(today(), 1, country=country))", "def iso_year(self) -> Series:", "def cve_last_year():\n current_time = datetime.now()\n\n cves = CVE.query.filter(\n current_time.year == db.extract(\"year\", CVE.published_date)\n ).all()\n\n return {\n \"cves\": cves_schema.dump(cves)\n }", "def get_previous_close(self, ticker, unadjusted=False):\n end_point = f\"https://api.polygon.io/v2/aggs/ticker/{ticker}/prev\" \\\n f\"?unadjusted={str(unadjusted).lower()}\" \\\n f\"&apiKey={self.API_KEY}\"\n content = requests.get(end_point)\n data = content.json()[\"results\"]\n return pd.DataFrame(data)", "def getYear():", "def get_last_trade(self, ticker):\n end_point = f\"https://api.polygon.io/v1/last/stocks/{ticker}?apiKey={self.API_KEY}\"\n content = requests.get(end_point)\n data = content.json()\n return data[\"last\"]", "def get_last_trade_date():\n df = sf.get_stock('IBM')\n return df.index.max()", "def centuryFromYear(y):\n return 1 + (y-1)//100", "def get_year_ending(date) -> datetime.date:\n\tdate = getdate(date)\n\tnext_year_start = datetime.date(date.year + 1, 1, 1)\n\treturn add_to_date(next_year_start, days=-1)", "def worst_year_no(strat: Strategy) -> int:\n rel_diff = relative_yearly_returns(strat)\n if len(rel_diff) > 0:\n return min(rel_diff.index, key=lambda day: rel_diff.at[day]).year\n else:\n raise InsufficientTimeframe", "def forward_only(df):\n df = df[dates.curmonyear_str :]\n return df", "def worst_year(strat: Strategy) -> Decimal:\n rel_diff = relative_yearly_returns(strat)\n if len(rel_diff) > 0:\n return rel_diff.min()\n else:\n raise InsufficientTimeframe", "def last_closed_period(self, base_date):\n first_day = '{}/{}'.format(base_date.year, base_date.month)\n first_day = datetime.strptime(first_day, '%Y/%m')\n first_day = first_day - timedelta(days=1)\n\n return '{:02}/{:0004}'.format(first_day.month, first_day.year)", "def liturgical_year_end(year):\n next_xmas = dt.date(year, 12, 25)\n return next_xmas - dt.timedelta(next_xmas.weekday() + 23)", "def _get_year():\n x = datetime.datetime.now()\n return x.year if x >= datetime.datetime(x.year, 12, 1) else x.year - 1", "def years_to_keep(self):\n return self._years_to_keep", "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 fetch_90(self):\n before = self.today - datetime.timedelta(days=120)\n self.fetch_from(before.year, before.month)\n self.data = self.data[-90:]\n return self.data" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get image data and cleanup.
def get_image_data(img): fpath = 'ocr_images/{}'.format(img) ref_name = fpath.replace('/', '__').replace('.', '___') + '.txt' @cached(ref_name, directory='ocr_images') def get(): img = Image.open(fpath) res = pytesseract.image_to_string(img) ppr(res) return res return get()
[ "def get_raw_data(self):\n raise OSError(\"GXPARM.XDS does not support image data!\")", "def getImgData(inputImg, outputImg):\n copy = ' '.join(['3dcopy', inputImg, outputImg])\n\n if os.path.exists(outputImg):\n print outputImg.split('/')[-1], 'Already exists, removing... '\n os.remove(outputImg)\n\n os.popen(copy)", "def get_image_data(self):\n\n # Reading image_data file\n with open(self.IMAGE_DIRECTORY + '/image_data.yml', 'r') as f:\n # Getting all data\n data = yaml.safe_load(f)\n # Getting image_data\n image_data = data['image_data']\n\n # Return the array of data\n return image_data", "def _read_image(self, coco_image_dir, gt_data):\n img_coco = self.refexp_dataset.loadImgs(ids=gt_data['image_id'])[0]\n return misc.imread(os.path.join(coco_image_dir, img_coco['file_name']))", "def receive_image(self):\n\t\timage_bytes = BytesIO(self.receive_and_decrypt())\n\t\timage_bytes.seek(0) # return file cursor to beginning of file\n\n\t\treturn Image.open(image_bytes)", "def get_image(self):", "def image(self):\n\n # PIL \"raw\" decoder modes for the various image dataTypes\n dataTypesDec = {\n 1: 'F;16S', #16-bit LE signed integer\n 2: 'F;32F', #32-bit LE floating point\n 6: 'F;8', #8-bit unsigned integer\n 7: 'F;32S', #32-bit LE signed integer\n 9: 'F;8S', #8-bit signed integer\n 10: 'F;16', #16-bit LE unsigned integer\n 11: 'F;32', #32-bit LE unsigned integer\n 14: 'F;8', #binary\n }\n\n # get relevant Tags\n tag_root = 'root.ImageList.1'\n data_offset = int( self.tags[\"%s.ImageData.Data.Offset\" % tag_root] )\n data_size = int( self.tags[\"%s.ImageData.Data.Size\" % tag_root] )\n data_type = int( self.tags[\"%s.ImageData.DataType\" % tag_root] )\n im_width = int( self.tags[\"%s.ImageData.Dimensions.0\" % tag_root] )\n im_height = int( self.tags[\"%s.ImageData.Dimensions.1\" % tag_root] )\n\n if self.debug > 0:\n print \"Notice: image data in %s starts at %s\" % (\n os.path.split(self._filename)[1], hex(data_offset)\n )\n print \"Notice: image size: %sx%s px\" % (im_width, im_height)\n\n # check if image DataType is implemented, then read\n if data_type in dataTypesDec:\n decoder = dataTypesDec[data_type]\n if self.debug > 0:\n print \"Notice: image data type: %s ('%s'), read as %s\" % (\n data_type, dataTypes[data_type], decoder\n )\n t1 = time.time()\n self._f.seek( data_offset )\n rawdata = self._f.read(data_size)\n im = Image.frombytes( 'F', (im_width, im_height), rawdata,\n 'raw', decoder )\n if self.debug > 0:\n t2 = time.time()\n print \"| read image data: %.3g s\" % (t2-t1)\n else:\n raise Exception(\n \"Cannot extract image data from %s: unimplemented DataType (%s:%s).\" %\n (os.path.split(self._filename)[1], data_type, dataTypes[data_type])\n )\n\n # if image dataType is BINARY, binarize image\n # (i.e., px_value>0 is True)\n if data_type == 14:\n # convert Image to 'L' to apply point operation\n im = im.convert('L')\n # binarize\n im = im.point(lambda v: v > 0 or False)\n\n return im", "def get_image_data(self):\n return {\n 'id': self.id,\n 'name': self.get_filename(),\n 'size': self.file.size,\n 'url': self.get_absolute_url(),\n 'thumbnail_url': self.get_thumbnail_url(),\n 'delete_url': self.get_delete_url(),\n 'delete_type': 'DELETE'\n }", "def image_data(self, image_name):\n # If we already have the data, return it\n if image_name in self._image_data:\n im = self._image_data[image_name]\n else:\n # If we don't already have the data, load it\n\n # Get the class of the image we are loading\n try:\n image_class = self._image_types[image_name]\n except KeyError:\n image_class = DESImage\n\n fname = self.config.get(self.config_section, image_name)\n im = image_class.load(fname)\n logger.info('Reading %s image from %s', image_name, fname)\n self._image_data[image_name] = im\n\n return im", "def _get_image(self):\n attr_name = '_image_cache'\n if not getattr(self, attr_name, None):\n self.seek(0)\n setattr(self, attr_name, Image.open(self.file))\n return getattr(self, attr_name)", "def get_images(self):\n pass", "def get_data(self):\n datas = self.img.getdata()\n w, h = self.get_size()\n r_avg_color = 0\n g_avg_color = 0\n b_avg_color = 0\n self.data = list()\n for i in range(len(datas)):\n r_avg_color += datas[i][0]\n g_avg_color += datas[i][1]\n b_avg_color += datas[i][2]\n self.data.append(datas[i])\n r_avg_color = r_avg_color // len(datas)\n g_avg_color = g_avg_color // len(datas)\n b_avg_color = b_avg_color // len(datas)\n self.set_avg_color((r_avg_color, g_avg_color, b_avg_color))\n return self.data", "def testimg():\n return testimage().array()", "def fetch(self):\n api = self.doapi_manager\n return api._image(api.request(self.url)[\"image\"])", "def image(self):\n if self.has_metadata:\n self.extract_metadata()\n tempdir_path = self.make_tempdir()\n tempfile_path = os.path.join(tempdir_path, self.filename)\n warnings.simplefilter('error', Image.DecompressionBombWarning)\n try: # Do image conversions\n with Image.open(self.src_path) as img_in:\n with Image.frombytes(img_in.mode, img_in.size, img_in.tobytes()) as img_out:\n img_out.save(tempfile_path)\n self.src_path = tempfile_path\n except Exception as e: # Catch decompression bombs\n # TODO: change this from all Exceptions to specific DecompressionBombWarning\n self.add_error(e, \"Caught exception (possible decompression bomb?) while translating file {}.\".format(self.src_path))\n self.make_dangerous('Image file containing decompression bomb')\n if not self.is_dangerous:\n self.add_description('Image file')", "def screen_shot_to_object(self) -> np.ndarray:\n pic_path = self.screen_shot()\n # temp file will be automatically removed after usage\n data = cv2.imread(pic_path, cv2.COLOR_RGB2GRAY)\n os.remove(pic_path)\n return data", "def load_img(self, data_path):\n img = Image.open(data_path)\n random.seed(self.seed)\n return self.transform(img)", "def get_updated_image_data(self):\n if self.slice == self.total_slices:\n return self.full_image", "def getData(self):\n\n if not self.intCompression:\n _dataSize = self.header['Width']*self.header['Width']\n \n _image = self.open()\n # Jump over the header\n _image.read(self.header['HeaderSize'])\n # Read the remaining bytes\n _data = _image.read()\n # unpack\n _fmt = self.header['EndianType'] + \"H\" * _dataSize\n _data = struct.unpack(_fmt, _data)\n \n _image.close()\n assert _dataSize == len(_data)\n \n return _data\n else:\n raise XIOError, \"Sorry, this image is internaly compressed.\"" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Simply splits text into paragraphs by splitting on the string '\n\n'
def split_into_paras(text): paras = string.split(text, "\n\n") return paras
[ "def _split_paragraphs(self, text):\n\n import re\n import textwrap\n\n text = textwrap.dedent(text).strip()\n text = re.sub('\\n\\n[\\n]+', '\\n\\n', text)\n\n last_sub_indent = None\n paragraphs = list()\n for line in text.splitlines():\n (indent, sub_indent) = self._indents(line)\n is_text = len(line.strip()) > 0\n\n if is_text and indent == sub_indent == last_sub_indent:\n paragraphs[-1] += ' ' + line\n else:\n paragraphs.append(line)\n\n if is_text:\n last_sub_indent = sub_indent\n else:\n last_sub_indent = None\n\n return paragraphs", "def get_paragraphs(text):\n return [s.strip() for s in re.split(\"\\n+\", text) if s.strip()]", "def paragraphs(string):\n return [line.strip() for line in string.split('\\n')]", "def segment_by_lines(text: str):\n\treturn text.splitlines()", "def sentence_split(text, properties={'annotators': 'ssplit', 'outputFormat': 'json'}):\n annotated = nlp.annotate(text, properties)\n sentence_split = list()\n for sentence in annotated['sentences']:\n s = [t['word'] for t in sentence['tokens']]\n k = [item.lower() for item in s if item not in [\",\", \".\", '...', '..']]\n sentence_split.append(\" \".join(k))\n return sentence_split", "def split_by_newline(text, start=0):\r\n index = start\r\n while 1:\r\n new_index = text.find('\\n', index)\r\n if new_index == -1:\r\n yield (-1, text[index:])\r\n break\r\n yield (new_index + 1, text[index:new_index])\r\n index = new_index + 1", "def split_sentences(cls, text):\n last_index = 0\n intervaled = []\n for match in cls.SENTENCE_SPLITTER.finditer(text):\n begin, end = match.span()\n intervaled.append(text[last_index:begin])\n intervaled.append(text[begin:end])\n last_index = end\n intervaled.append(text[last_index:])\n\n if len(intervaled) > 1 and not intervaled[-1].strip():\n end = intervaled.pop()\n sep = intervaled.pop()\n intervaled[-1] += sep + end\n\n return intervaled", "def sep_sentences_to_lines(infile, outfile, sep_paragraphs=True):\n\n with open(infile, 'r') as i:\n text = i.read()\n\n paragraphs = text.split('\\n\\n')\n\n with open(outfile, 'w') as o:\n for par in paragraphs:\n sentences = nltk.sent_tokenize(par)\n for sentence in sentences:\n o.write(sentence + '\\n')\n\n if sep_paragraphs:\n o.write('\\n')", "def paragraphs(cls, nb=3):\r\n return [cls.paragraph() for _ in range(0, nb)]", "def share_text_by_paragraph(text):\n dict_of_paragraphs = {}\n count = 0\n paragraphs = text.split('\\n')\n for pr in paragraphs:\n if pr != '' and pr != ' ':# or len(pr) < 1:\n dict_of_paragraphs[count] = pr\n count += 1\n return dict_of_paragraphs", "def _split_text_by_ents(cls, text: str, entities: List[WordLemma]) -> List[str]:\n first_entity_start = entities[0].start_char\n text_parts = [text[:first_entity_start]]\n for i, entity in enumerate(entities[:-1]):\n start_index = entity.end_char\n stop_index = entities[i + 1].start_char\n text_part = text[start_index:stop_index]\n text_parts.append(text_part)\n last_entity_stop = entities[-1].end_char\n text_parts.append(text[last_entity_stop:])\n return text_parts", "def split_newlines(s):\n return re.findall(NEWLINE_PTR, s)", "def test_paragraphs(self):\n self.assertEqual(\n paragraphs(1),\n [\n \"Lorem ipsum dolor sit amet, consectetur adipisicing elit, \"\n \"sed do eiusmod tempor incididunt ut labore et dolore magna \"\n \"aliqua. Ut enim ad minim veniam, quis nostrud exercitation \"\n \"ullamco laboris nisi ut aliquip ex ea commodo consequat. \"\n \"Duis aute irure dolor in reprehenderit in voluptate velit \"\n \"esse cillum dolore eu fugiat nulla pariatur. Excepteur sint \"\n \"occaecat cupidatat non proident, sunt in culpa qui officia \"\n \"deserunt mollit anim id est laborum.\"\n ],\n )", "def split_into_sentences(text: str) -> typing.List[str]:\n\n return nltk.sent_tokenize(text)", "def wrap_text(text, wrap_chars):\r\n\r\n # split text on sentence punctuation and remove empty strings\r\n text_paragraph = re.split('([^.?!]+[.?!])', text)\r\n text_paragraph = [i for i in text_paragraph if i != '']\r\n\r\n # wrap text lines, append space item for paragraph spacing line\r\n text_list = []\r\n for text_line in text_paragraph:\r\n text_line_wrap = textwrap.wrap(\r\n text_line, int(wrap_chars), break_on_hyphens=False\r\n )\r\n for text_line_wrap_line in text_line_wrap:\r\n text_list.append(text_line_wrap_line.strip())\r\n text_list.append(' ')\r\n\r\n # remove last added space item for paragraph spacing line, return list\r\n if len(text_list) > 0:\r\n while text_list[-1] == ' ':\r\n text_list.pop()\r\n\r\n return text_list", "def test_sentence_segmentation(self):\n\n input = 'This is the first paragraph.\\n\\n\\nThis is the second paragraph.'\n re_paragraph_splitter = '\\n\\n+'\n result = self.datacleaner.sentence_segmentation(input, re_paragraph_splitter)\n self.assertEqual(result, ['This is the first paragraph.', 'This is the second paragraph.'])", "def _split(self):\n text = self.md\n self.parts = parts = []\n self.headers = headers = []\n lines = []\n \n # Split in parts\n for line in text.splitlines():\n if line.startswith(('# ', '## ', '### ', '#### ', '##### ')):\n # Finish pending lines\n parts.append('\\n'.join(lines))\n lines = []\n # Process header\n level = len(line.split(' ')[0])\n title = line.split(' ', 1)[1]\n title_short = title.split('(')[0].split('<')[0].strip().replace('`', '')\n headers.append((level, title_short))\n parts.append((level, title_short, title))\n else:\n lines.append(line)\n parts.append('\\n'.join(lines))\n \n # Now convert all text to html\n for i in range(len(parts)):\n if not isinstance(parts[i], tuple):\n parts[i] = markdown.markdown(parts[i], extensions=[]) + '\\n\\n'", "def preprocess(text: str) -> List[str]:\n return __PARAGRAPH_SEP.split(\n Tokenizer.join_hyphenated_words_across_linebreaks(text)\n )", "def make_list(text):\n poses = text.split(\"\\n\")\n # poses.append(poses)\n # To set a stop point, append None to the end of ou list.\n poses.append(None)\n\n return poses" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get ths stem word for 'word'
def get_stem(word): #stub #PLACEHOLDER ps = PorterStemmer() return word
[ "def stem(word):\n global _stemmer\n if _stemmer is None:\n _stemmer = nltk.stem.porter.PorterStemmer()\n return _stemmer.stem(word)", "def getStemmer():\n return nltk.stem.PorterStemmer().stem", "def find_term(self, question):\n\n term = None\n\n for regex in self.regexes:\n match = re.match(regex, question.lower())\n if match:\n term = stem(match.groups(1))\n break\n\n return term", "def stem_tweet(tweet_text):\n # Remove numbers\n text_rc = re.sub('[0-9]+', '', tweet_text)\n # Split on whitespace\n tokens = re.split('\\W+', text_rc)\n # Remove stopwords and apply stemming\n text = [ps.stem(word) for word in tokens if word not in stopword]\n return ' '.join(text)", "def stem(s):\r\n if(s[-1:] == 's'):\r\n if(len(s) < 3):\r\n s = s\r\n else:\r\n s = s[:-1]\r\n return stem(s)\r\n \r\n\r\n elif(s[-3:] == 'ing'):\r\n if(len(s) < 5):\r\n s = s\r\n else:\r\n if(s[-4] == s[-5]):\r\n s = s[:-4]\r\n else:\r\n s = s[:-3]\r\n elif(s[-2:] == 'er'):\r\n s = s[:-2]\r\n\r\n elif(s[-2:] == 'ed'):\r\n if(len(s) < 4):\r\n s = s\r\n else:\r\n s = s[:-2]\r\n elif(s[-2:] == 'es'):\r\n if(len(s) < 4):\r\n s = s\r\n else:\r\n s = s[:-2]\r\n elif(s[-3:] == 'est'):\r\n if(len(s) < 5):\r\n s = s\r\n else:\r\n s = s[:-3]\r\n elif(s[-3:] == 'less'):\r\n if(len(s) < 5):\r\n s = s\r\n else:\r\n s = s[:-3]\r\n elif(s[-1:] == 'y'):\r\n if(len(s) < 5):\r\n s = s \r\n else:\r\n s = s[:-1] + 'i'\r\n return s", "def noun_stem(s): \n # add code here\n if s in unchanging_plurals:\n return s\n elif re.match(\"men\", s[len(s)-3: len(s)]):\n return re.sub(\"men\", \"man\", s)\n elif verb_stem(s) in unchanging_plurals:\n return ''\n else:\n\treturn verb_stem(s)", "def get_synonym(word, part_of_speech=None):\n if part_of_speech:\n return Word(word).synonyms(partOfSpeech=part_of_speech)[0]\n else:\n return Word(word).synonyms()", "def test_stem_words():\n\n # check for stemmed version of certain words\n test_str = 'The dog was running up the sidewalk.' # should be stemmed\n stemmed_text = text_utilities.stem_words(test_str)\n stemmed_text = stemmed_text.split(' ')\n assert not stemmed_text[3] == 'running'", "def _stem_words(stemmer, words):\n return [stemmer.stem(word.lower()) for word in words]", "def stem_and_filter(self, text):\n tokenized = word_tokenize(text)\n tokenized = [w for w in tokenized if w not in stop_words] # Remove stop words from tokenized text\n stemmed = \" \".join([ps.stem(w) for w in tokenized])\n return stemmed", "def lemmatize_stemming(self, word_without_punctuation):\n stemmer = SnowballStemmer('english')\n return stemmer.stem(WordNetLemmatizer().lemmatize(word_without_punctuation, pos='v'))", "def stem(s):\r\n special=['s']\r\n one_singular=['y','e','a']\r\n singular=['on','er','us','en','st']\r\n plural=['ie','ey','es']\r\n three_end=['ier','ing','dom','er','ism','ist','ion','ous','iou']\r\n four_end=['ible','able','ment','ness','ship','sion','tion','ance','ence','ious']\r\n two_prefix=['re','un','co','de']\r\n three_prefix=['pre','dis']\r\n if len(s)>=3 and s[-1] in special:\r\n if s[-3:-1] in plural:\r\n return s[:-3]\r\n if s[-4:-1] in three_end:\r\n return s[:-4]\r\n if len(s)>=5:\r\n if s[-5:-1]in four_end:\r\n return s[:-5]\r\n if s[:2] in two_prefix:\r\n return s[2:]\r\n if s[:3] in three_prefix:\r\n return s[3:]\r\n if s[-2:-1] in one_singular:\r\n return s[:-2]\r\n else:\r\n return s[:-1]\r\n if len(s)>=3:\r\n if s[:2] in two_prefix:\r\n return s[2:]\r\n if s[:3] in three_prefix:\r\n return s[3:]\r\n if s[-1] in one_singular:\r\n return s[:-1]\r\n if s[-2:] in plural:\r\n return s[:-2]\r\n if s[-3:] in three_end:\r\n return s[:-3]\r\n if len(s)>=5:\r\n if s[-4]in four_end:\r\n return s[:-4] \r\n else:\r\n return s\r\n if s[-1]in one_singular:\r\n return s[:-1]\r\n if s[-2:] in singular:\r\n return s\r\n if s[-2:]in plural:\r\n return s\r\n else:\r\n return s", "def get_synonym(self, word:str) -> str:\n word = word.lower()\n return self.lookup_dict.get(word, word)", "def verb_stem(s):\n def match(p):\n return re.match(p + '$', s, re.IGNORECASE)\n\n verbStem = \"\"\n\n if match('.*(?<!.[aeiousxyz]|sh|ch)s'):\n verbStem = s[:-1]\n elif match('.*([^s]se|[^z]ze)s'):\n verbStem = s[:-1]\n elif match('.*[aeiou]ys'):\n verbStem = s[:-1]\n elif match('[^aeiou]ies'):\n verbStem = s[:-1]\n elif match('.*.[^aeiou]ies'):\n verbStem = s[:-3] + 'y'\n elif match('.*(o|x|ch|ss|zz|sh)es'):\n verbStem = s[:-2]\n elif match('.*(?<!.[iosxz]|sh|ch)es'):\n verbStem = s[:-1]\n elif match('has'):\n verbStem = 'have'\n if (not (s, 'VB') in tagSetOfBrown and not (s, 'VBZ') in tagSetOfBrown):\n return ''\n\n return verbStem", "def get_word(self):\n # Todo get a list of words fron somewhere\n pass", "def normalise(word, stemmer, lemmatizer):\n word = word.lower()\n #word = stemmer.stem(word)\n word = lemmatizer.lemmatize(word)\n return word", "def get_word(self, word_str):\n return self.words[word_str]", "def uses_stemming(self):\n return self._stemming", "def stem_text(text):\n text = utils.to_unicode(text)\n stemmer = PorterStemmer()\n return ' '.join(stemmer.stem(word) for word in text.split())" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
gets the lemma for 'word' (similar to stem, but guaranteed to be a real word) pos is an optional part of speech tag
def get_lemmas(word, pos=None): #stub #PLACEHOLDER Lemmatizer = WordNetLemmatizer() lemma = None if pos != None: try: lemma = Lemmatizer.lemmatize(word, pos=pos) except KeyError: lemma = Lemmatizer.lemmatize(word) return lemma
[ "def lemmatize(word, pos='n'):\n if not pos.strip():\n return word\n\n return wordnet_lemmatizer.lemmatize(word, pos=pos)", "def lemmatize(doc):\n lemma = [token.lemma_ for token in doc\n if not token.is_punct and not token.is_space\n and (token.text == \"US\"\n or token.lower_ not in STOP_WORDS)\n and not token.tag_ == \"POS\" and not token.text == \"'s\"]\n return lemma", "def lemma(word) -> 'lemma':\n lemmas = wn.lemmas(word['value'])\n return [{'value': f\"{l.synset().name()}.{l.name()}\"} for l in lemmas]", "def lemmatize_word(word):\n return lemmatizer.lemmatize(word,'v')", "def lemmatize(word):\n global _lemmatizer\n if _lemmatizer is None:\n _lemmatizer = nltk.WordNetLemmatizer()\n return _lemmatizer.lemmatize(word)", "def lemmatize_spa(self, spa_word):\n # spa_word is a word form\n res1 = [i[0] for i in self.spa_lemmas if i[1]==spa_word]\n if len(res1)==1:\n return res1[0]\n # spa_word is already a lemma\n res2 = [i[0] for i in self.spa_lemmas if i[0]==spa_word]\n if len(res2)>0:\n return res2[0]\n return \"\"", "def lemmatize_stemming(self, word_without_punctuation):\n stemmer = SnowballStemmer('english')\n return stemmer.stem(WordNetLemmatizer().lemmatize(word_without_punctuation, pos='v'))", "def get_lemma(self, token: str, lang: str) -> Optional[str]:\n # filters\n if token.isnumeric():\n return token\n\n candidate = (\n # supervised searches\n self._dictionary_lookup.get_lemma(token, lang)\n or self._hyphen_search.get_lemma(token, lang)\n or self._rules_search.get_lemma(token, lang)\n or self._prefix_search.get_lemma(token, lang)\n # weakly supervised / greedier searches\n or self._affix_search.get_lemma(token, lang)\n )\n\n # additional round\n if candidate is not None and self._greedy_dictionary_lookup is not None:\n candidate = self._greedy_dictionary_lookup.get_lemma(candidate, lang)\n\n return candidate", "def lemmatize_sentence(sentence):\n\n sentence = [(stem.WordNetLemmatizer().lemmatize(word, pos_tag), pos_tag) if pos_tag else (word, pos_tag)\n for word, pos_tag in sentence]\n\n return sentence", "def disambiguate_word(word, tag, tweet_pos):\n sent = [key[\"token\"] for key in tweet_pos]\n return lesk(sent, word, tag)", "def lemmatize_words(\n unlem: List[str],\n lemmatizer_name: str,\n pos_tag: Union[str, List[str]] = \"n\",\n verbose: bool = False,\n) -> List[str]:\n if lemmatizer_name == \"nltk\":\n lemmatized = nltk_lemmatize(unlem, pos_tag, verbose)\n elif lemmatizer_name == \"spacy\":\n lemmatized = spacy_lemmatize(unlem, pos_tag, verbose)\n elif lemmatizer_name == \"spacy_old\":\n lemmatized = old_spacy_lemmatize(unlem, verbose)\n elif lemmatizer_name == \"pymorphy-ru\":\n lemmatized = pymorphy_ru_lemmatize(unlem, verbose)\n else:\n raise ValueError(f\"Incorrect lemmatizer type: {lemmatizer_name}\")\n return lemmatized", "def luanerize_word(word):\n\n import nltk # pylint: disable=import-outside-toplevel\n\n wnl = nltk.stem.WordNetLemmatizer()\n lemma = wnl.lemmatize(word.strip(string.punctuation))\n return word.replace(lemma, LUAN)", "def get_wordform2lemma(\n vocabulary: List[str],\n lemmatizer: str,\n pos_tag: str = \"n\",\n verbose: bool = False\n) -> Dict[str, str]:\n lemmatized = lemmatize_words(vocabulary, lemmatizer, pos_tag, verbose)\n return dict(zip(vocabulary, lemmatized))", "def _lemma_via_patternlib(self, w, pos, props={}):\n if(not(self.pattern_module)):\n raise RuntimeError('pattern.de module not loaded')\n if(pos.startswith('N') and \"number\" in props and props[\"number\"]!=\"Sg\"): # pos == 'NP': singularize noun\n return self.pattern_module.singularize(w)\n elif(pos.startswith('V') and \"form\" in props and props[\"form\"]!=\"INF\"): # get infinitive of verb\n return self.pattern_module.conjugate(w)\n elif(pos.startswith('ADJ') or pos.startswith('ADV')): # get baseform of adjective or adverb\n return self.pattern_module.predicative(w)\n\n return w", "def get_lemma(self, token: str, lang: str) -> str:\n limit = 6 if lang in SHORTER_GREEDY else 8\n if len(token) <= limit:\n return token\n\n dictionary = self._dictionary_factory.get_dictionary(lang)\n candidate = token\n for _ in range(self._steps):\n if candidate not in dictionary:\n break\n\n new_candidate = dictionary[candidate]\n\n if (\n len(new_candidate) > len(candidate)\n or levenshtein_dist(new_candidate, candidate) > self._distance\n ):\n break\n\n candidate = new_candidate\n\n return candidate", "def lemmatization(phrase):\n wordnet_lemmatizer = WordNetLemmatizer()\n nltk_tokens = nltk.word_tokenize(phrase)\n \n # Uncomment the first time to download\n #nltk.download('wordnet')\n lemmas=[]\n for w in nltk_tokens:\n #print(\"Actual: %s Lemma: %s\" % (w,wordnet_lemmatizer.lemmatize(w)))\n lemmas.append(\"Actual: %s Lemma: %s \" % (w,wordnet_lemmatizer.lemmatize(w)))\n \n return lemmas", "def lemmatize_words(sentence):\n lemmatizer = WordNetLemmatizer()\n wordnet_map = {\"N\": wordnet.NOUN, \"V\": wordnet.VERB, \"J\": wordnet.ADJ, \"R\": wordnet.ADV}\n\n pos_tagged_text = nltk.pos_tag(sentence.split())\n\n return \" \".join(\n [\n lemmatizer.lemmatize(word, wordnet_map.get(pos[0], wordnet.NOUN))\n for word, pos in pos_tagged_text\n ]\n )", "def get_wordnet_pos(self,treebank_tag):\r\n if treebank_tag.startswith('J'):\r\n return wordnet.ADJ\r\n elif treebank_tag.startswith('V'):\r\n return wordnet.VERB\r\n elif treebank_tag.startswith('N'):\r\n return wordnet.NOUN\r\n elif treebank_tag.startswith('R'):\r\n return wordnet.ADV\r\n else:\r\n # As default pos in lemmatization is Noun\r\n return wordnet.NOUN", "def _get_wordnet_pos(self, word):\n\n tag = nltk.pos_tag([word])[0][1][0].upper()\n tag_dict = {\"J\": wordnet.ADJ,\n \"N\": wordnet.NOUN,\n \"V\": wordnet.VERB,\n \"R\": wordnet.ADV}\n return tag_dict.get(tag, wordnet.NOUN)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Use Audio3DManager.loadSfx to load a sound with 3D positioning enabled
def loadSfx(self, name): sound = None if name: sound = self.audio_manager.getSound(name, 1) return sound
[ "def load_audio(self, path):\n pass", "def import_sounds(self):\n pygame.mixer.pre_init(buffer=1024)\n self.troll_sound = pygame.mixer.Sound('sounds/troll_music.wav')", "def load_sounds(self):\n try:\n pygame.mixer.init()\n except:\n print 'Cannot load sound'\n self.soundon = False\n finally:\n pygame.mixer.music.load(data.filepath('purity.ogg'))\n self.sfx = {'click': pygame.mixer.Sound(data.filepath('click.ogg')),\n 'complete': pygame.mixer.Sound(data.filepath('complete.ogg')),\n 'hitroid': pygame.mixer.Sound(data.filepath('atari.ogg')),\n 'error': pygame.mixer.Sound(data.filepath('error.ogg')),\n 'pbar': pygame.mixer.Sound(data.filepath('pbar.ogg')),\n 'startgame': pygame.mixer.Sound(data.filepath('startgame.ogg'))\n }\n self.soundon = True", "def __loadAudio(self):\n fileLocs=FileLocations()\n self.__menuSoundsFilename=[\"\\menu_01_01.ogg\", \"\\menu_01_02.ogg\", \"\\menu_01_05.ogg\",\"\\menu_01_06.ogg\"]\n #self.__menuSoundsFilename=[\"\\menu_01_01.ogg\", \"\\menu_01_02.ogg\", \"\\menu_01_03.ogg\", \"\\menu_01_04.ogg\", \"\\menu_01_05.ogg\", \"\\menu_01_06.ogg\"]\n self.__menuSound=[]\n for filename in self.__menuSoundsFilename:\n self.__menuSound.append(pygame.mixer.Sound(fileLocs.menuSounds+filename))\n \n self.__buzzer = pygame.mixer.Sound(fileLocs.soundEffects+\"\\\\fx_00_00.ogg\")\n self.__narrationChannel = pygame.mixer.Channel(0)", "def load_song(filename):\n try:\n return Sound(file=filename)\n except pygame.error as e:\n return None", "def load_mp3(mp3_file_name, file_type):\n if mp3_file_name.startswith('https://') or mp3_file_name.startswith('http://'):\n mp3_file_name = download_file(mp3_file_name, file_type)\n if not mp3_file_name.lower().endswith('.mp3'):\n raise SystemExit(\n 'Incorrect audio file format. The file must have .mp3 extension'\n )\n return AudioSegment.from_mp3(mp3_file_name)", "def load_sound_library(self):\n if not AudioEngine._ffmpeg2_loaded:\n AudioEngine._ffmpeg2_loaded = True\n else:\n return\n import pyglet_ffmpeg2\n pyglet_ffmpeg2.load_ffmpeg()", "def music_library_load():\r\n print \"libload\"\r\n print Settings.FILE_LOCATION_LIBRARY\r\n if Settings.LIB_USE_MULTI:\r\n basepath = fileGetPath(MpGlobal.FILEPATH_LIBRARY)\r\n return musicMergeLoad_LIBZ(basepath,Settings.LIB_MULTI)\r\n else:\r\n return musicLoad_LIBZ(MpGlobal.FILEPATH_LIBRARY)", "def play_sound(filename):\n # read from sound file\n data, fs = sf.read(filename, dtype='float32')\n\n # play from soundfile\n sd.play(data, fs)\n sd.wait()\n return", "def load_sounds(self):\r\n\t\tself.sounds = 'pinwheel.wav','die.wav','square.wav','start.wav', \\\r\n\t\t'rhombus.wav','crash.wav' ,'triangle2.wav','octagon.wav','deathstar.wav',\\\r\n\t\t'deathstar2.wav','die1.wav'\r\n\t\tfor filename in self.sounds:\r\n\t\t\tGlobal.sounds[filename] = pygame.mixer.Sound('sounds/'+filename)", "def _load_audio(self, path):\n self.current_audio_file_path = path\n self.player.init()\n self.player.music.load(path)\n self.player.music.set_volume(.25)", "def play_sound(self, filename):\n if filename not in self._sounds.keys():\n loaded = raylibpy.load_sound(filename)\n self._sounds[filename] = loaded\n\n sound = self._sounds[filename]\n raylibpy.play_sound(sound)", "def Sound(sound_file_name):\n return pygame.mixer.Sound(get_file(sound_file_name))", "def load_c3d(self):\n\n print(\"Loading c3d..\")\n\n basic_filter = \"*.c3d\"\n last_directory = pm.optionVar(q=\"lastPeelC3dDir\")\n\n # open file browser\n self.c3d_files = pm.fileDialog2(fm=4, fileFilter=basic_filter, dialogStyle=2, dir=last_directory)\n\n print(\"Found these c3d..\", self.c3d_files)\n\n if self.c3d_files is None or len(self.c3d_files) == 0:\n return\n\n self.populate_c3d_table()", "def __init__(self, name: str, scad3d: Scad3D, offset: P3D) -> None:\n # Initialize the parent super *SCAD3D* class:\n super().__init__(name)\n # Stuff values into *translate3d* (i.e. *self*):\n # translate3d: Translate3D = self\n self.scad3d: Scad3D = scad3d\n self.offset: P3D = offset", "def BACKGROUND_MUSIC(self): \n musicSound = Sound(source = 'ninja.wav')\n musicSound.play()", "def open_3ds_gui (self):\n debug (\"In MayaViTkGUI::open_3ds_gui ()\")\n file_name = tk_fopen (title=\"Open 3D Studio file\", \n initialdir=Common.config.initial_dir,\n filetypes=[(\"3D Studio files\", \"*.3ds\"), \n (\"All files\", \"*\")])\n self.open_3ds (file_name)", "def TestSound():\n SoundsPath = os.path.join(AudioFilesPath, MySet.Sound + \".mp3\")\n Parent.PlaySound(SoundsPath, MySet.Volume*0.01)", "def loadSoundFolder(self, path):\r\n files = glob.glob(\"fx/\" + path + \"/*.ogg\")\r\n self.log.info(\r\n \"loading sound folder: fx/%s (%d files)\" %\r\n (path, len(files)))\r\n for elem in files:\r\n self.sounds[path + \"/\" +\r\n os.path.basename(elem)] = sound_lib.sample.Sample(elem)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Control the presence of the Doppler effect. Default is 1.0 Exaggerated Doppler, use >1.0 Diminshed Doppler, use <1.0
def setDopplerFactor(self, factor): self.audio_manager.audio3dSetDopplerFactor(factor)
[ "def setDopplerFactor(self, factor: 'float') -> \"void\":\n return _coin.SoVRMLSound_setDopplerFactor(self, factor)", "def getDopplerFactor(self) -> \"float\":\n return _coin.SoVRMLSound_getDopplerFactor(self)", "def ford(self):\n chance = random.randint(0,100)\n percentChance = 5 * self.waterdepth\n if (chance > (100 - percentChance)):\n msg = \"DUDE FLIP THE WAGON!\"\n return", "def take_effect(self, player):\n\t\tpass", "def SoListenerDopplerElement_setDopplerFactor(state: 'SoState', node: 'SoNode', factor: 'float') -> \"void\":\n return _coin.SoListenerDopplerElement_setDopplerFactor(state, node, factor)", "def setDopplerFactor(state: 'SoState', node: 'SoNode', factor: 'float') -> \"void\":\n return _coin.SoListenerDopplerElement_setDopplerFactor(state, node, factor)", "def getDopplerFactor(state: 'SoState') -> \"float\":\n return _coin.SoListenerDopplerElement_getDopplerFactor(state)", "def add_dp_noise(self, p):\n if self.added_noise:\n assert False, 'Noise can only be added once. Already have noise: %.3f' % (\n self.added_noise)\n def flip(x):\n if x > 0:\n return 0\n return 1\n for i in range(self.m):\n if numpy.random.uniform(0, 1) < p:\n self.sketch[i] = flip(self.sketch.get(i, 0))\n self.added_noise = p", "def setDopplerVelocity(self, velocity: 'float') -> \"void\":\n return _coin.SoVRMLSound_setDopplerVelocity(self, velocity)", "def manga_dither(cmd, dither, actorState):\n cmd.respond('text=%s' % qstr('Changing guider dither position to %s.' % dither))\n timeLim = 60 # could take as long as a long guider exposure+readout, etc.\n ditherPos = 'ditherPos=%s' % dither\n cmdVar = actorState.actor.cmdr.call(\n actor='guider',\n forUserCmd=cmd,\n cmdStr='mangaDither %s' % (ditherPos),\n keyVars=[],\n timeLim=timeLim)\n if cmdVar.didFail:\n timeout = 'Timedout=%s' % ('Timeout' in cmdVar.lastReply.keywords)\n cmd.error('text=%s' % qstr('Failed to move guider to new dither position: %s' % timeout))\n return not cmdVar.didFail", "def SoListenerDopplerElement_getDopplerFactor(state: 'SoState') -> \"float\":\n return _coin.SoListenerDopplerElement_getDopplerFactor(state)", "def take_effect(self, player):\n\t\tif player.get_lantern():\n\t\t\tplayer.get_lantern().add_oil(self.oil_value)", "def doppler_factor_shift(wave, velocity):\n beta = velocity / constants.c\n doppler_factor = ((1 + beta) / (1 - beta)) ** 0.5\n\n y = wave * doppler_factor\n return y", "def swamp():\n\n magicMgr = spellbook.getManager()\n if magicMgr.fireflies:\n magicMgr.fireflies.destroy()\n magicMgr.fireflies = None\n magicMgr.groundFog.destroy()\n magicMgr.groundFog = None\n else:\n magicMgr.fireflies = Fireflies()\n if magicMgr.fireflies:\n magicMgr.fireflies.reparentTo(localAvatar)\n magicMgr.fireflies.startLoop()\n\n magicMgr.groundFog = GroundFog()\n if magicMgr.groundFog:\n magicMgr.groundFog.reparentTo(localAvatar)\n magicMgr.groundFog.startLoop()\n\n return 'Swamp effects toggled'", "def SoLazyElement_enableSeparateBlending(state: 'SoState', sfactor: 'int', dfactor: 'int', alpha_sfactor: 'int', alpha_dfactor: 'int') -> \"void\":\n return _coin.SoLazyElement_enableSeparateBlending(state, sfactor, dfactor, alpha_sfactor, alpha_dfactor)", "def loudness(self, loudness):\r\n loudness_value = '1' if loudness else '0'\r\n self.renderingControl.SetLoudness([\r\n ('InstanceID', 0),\r\n ('Channel', 'Master'),\r\n ('DesiredLoudness', loudness_value)\r\n ])", "def dodge(self):\n roll=random.randint(self.min_dodge, self.dodge_limit)\n # if roll is returned, then the character dodged\n return roll > 4", "def SoLazyElement_enableBlending(state: 'SoState', sfactor: 'int', dfactor: 'int') -> \"void\":\n return _coin.SoLazyElement_enableBlending(state, sfactor, dfactor)", "def doppler_shift(r_wave, r_vel):\n\treturn r_wave * (1 + (r_vel / ap.constants.c))" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Controls the maximum distance (in units) that this sound stops falling off. The sound does not stop at that point, it just doesn't get any quieter. You should rarely need to adjust this. Default is 1000000000.0
def setSoundMaxDistance(self, sound, dist): sound.set3dMaxDistance(dist)
[ "def max_velocity(self):\n return 10 * self.velocity_scale", "def max_speed(self, value):\n\n pass", "def max_speed(self):\n raise NotImplementedError", "def limit_speed(self):\n\n if self.x_speed > 0:\n self.x_speed = max(0, self.x_speed - 0.3)\n else:\n self.x_speed = min(0, self.x_speed + 0.3)\n\n if self.y_speed > 0:\n self.y_speed = max(0, self.y_speed - 0.3)\n else:\n self.y_speed = min(0, self.y_speed + 0.3)\n\n self.x_speed = min(self.x_speed, 4)\n self.x_speed = max(self.x_speed, -4)\n\n self.y_speed = min(self.y_speed, 4)\n self.y_speed = max(self.y_speed, -4)", "def set_stop_wavelength(self,val): #documented\n if self.__is_int_or_float(val) and self.__is_between(val,600,1800):\n if val < self.get_start_wavelength():\n self.__verbose_output( \"error: stop wavelength can not be set to < start wavelength\",1)\n else:\n self.send_message(\"STO %.1f\"%(val)) \n else:\n self.__verbose_output( \"error: set_stop_wavelength() - invalid argument\",1)", "def max_radius():\r\n return 20", "def set_tolerance():\n return 1e-5", "def dist(self):\n measurement = us_dist(15)\n if measurement < self.HARD_STOP_DIST:\n print('hard stop triggered during dist')\n self.stop()\n time.sleep(.05)\n print('I see something ' + str(measurement) + \"cm away\")\n return measurement", "def disableStopSize(self):\n\n self._stopSize = -1", "def brake(self):\n \n if self.speed == 0:\n self.speed = 0\n else:\n self.speed -= 5", "def stop(self):\n self.set_speed(Vector(0., 0.))", "def max_turn_speed(self, value):\n\n pass", "def set_center_wavelength(self,val): #tested and documented\n if self.__is_int_or_float(val) and self.__is_between( val, 600, 1750):\n self.send_message(\"CNT %.2f\"%val)\n else:\n self.__verbose_output(\"error: set_center_wavelength() - invalid argument\",1)", "def setMaxSpeed(self, speed):\n if speed >= 0:\n getHandle().maxSpeed = speed", "def GENfricStop(ballObj):\n if mag(ballObj.velocity) <= MOVETHRESHOLD:\n ballObj.velocity = vector(0,0,0)", "def max_sample_rate(self) -> int:\n return int(self.entity.player.max_sample_rate)", "def set_max_velocity_scaling_factor(self, value):\n if value > 0 and value <= 1:\n self._g.set_max_velocity_scaling_factor(value)\n else:\n raise MoveItCommanderException(\n \"Expected value in the range from 0 to 1 for scaling factor\"\n )", "def speed_count(self) -> int:\n return ATTR_MAX_FAN_STEPS", "def speed_of_sound(self, altitude):\n\n return sqrt(1.4 * 1716.56 * self.temperature(altitude))", "def getJumpLimit(self) -> \"float\":\n return _coin.SoDragPointDragger_getJumpLimit(self)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the velocity of the sound.
def getSoundVelocity(self, sound): if sound in self.vel_dict: vel = self.vel_dict[sound] if vel is not None: return vel for known_object in list(self.sound_dict.keys()): if self.sound_dict[known_object].count(sound): node_path = known_object.getNodePath() if not node_path: # The node has been deleted. del self.sound_dict[known_object] continue clock = ClockObject.getGlobalClock() return node_path.getPosDelta(self.root) / clock.getDt() return VBase3(0, 0, 0)
[ "def velocity(self):\r\n if self.sprint:\r\n return self._absDirection * self.sprintSpeed\r\n else:\r\n return self._absDirection * self.baseSpeed", "def getDopplerVelocity(self) -> \"float\":\n return _coin.SoVRMLSound_getDopplerVelocity(self)", "def get_velocity(self):\n return self.vr.simxGetObjectVelocity(self.car_handle, \n vrep.simx_opmode_buffer)[0]", "def get_velocity(self):\n linear, angular = self._physics_client.getBaseVelocity(self.uid)\n return np.asarray(linear), np.asarray(angular)", "def velocity_p(self):\n return self._velocity_p", "def velocity(self) -> qty.Velocity:\n v = self._flow_rate / self._cross_section.area()\n return qty.Velocity(v)", "def velocity(self, t):\n pass", "def getListenerVelocity(self):\n if self.listener_vel is not None:\n return self.listener_vel\n elif self.listener_target is not None:\n clock = ClockObject.getGlobalClock()\n return self.listener_target.getPosDelta(self.root) / clock.getDt()\n else:\n return VBase3(0, 0, 0)", "def velocity(slowness):\n return 0.3048 / ((slowness * (10**(-6))))", "def v(self):\n return self.velocity + self.dv()", "def sound_get_volume(self):\n v = self.player.get_property('volume') * 100 / 4\n return long(v)", "def sound_velocity(C_eff, rho):\n return C_eff / rho", "def velocity(self):\n if self.rest_value is None:\n raise ValueError(\"Cannot get velocity representation of spectral \"\n \"axis without specifying a reference value.\")\n if self.velocity_convention is None:\n raise ValueError(\"Cannot get velocity representation of spectral \"\n \"axis without specifying a velocity convention.\")\n\n equiv = getattr(u.equivalencies, 'doppler_{0}'.format(\n self.velocity_convention))(self.rest_value)\n\n new_data = self.spectral_axis.to(u.km/u.s, equivalencies=equiv).quantity\n\n # if redshift/rv is present, apply it:\n if self.spectral_axis.radial_velocity is not None:\n new_data += self.spectral_axis.radial_velocity\n\n return new_data", "def get_velocity(position):\r\n x, y = position\r\n vel = np.array([gradx_interp(y, x)[0][0],\r\n grady_interp(y, x)[0][0]])\r\n\r\n return vel / np.linalg.norm(vel)", "def velocity(self, time, *particle):\n\n\t\treturn self.variable(time, *particle, variable='velocity')", "def getDopplerVelocity(state: 'SoState') -> \"SbVec3f const &\":\n return _coin.SoListenerDopplerElement_getDopplerVelocity(state)", "def SoListenerDopplerElement_getDopplerVelocity(state: 'SoState') -> \"SbVec3f const &\":\n return _coin.SoListenerDopplerElement_getDopplerVelocity(state)", "def angular_velocity(self):\n return 0.0", "def get_speed(self):\n velocity = self.get_linear_velocity()\n speed = np.linalg.norm(velocity)\n return speed" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If velocity is set to auto, the velocity will be determined by the previous position of the object the listener is attached to and the frame dt. Make sure if you use this method that you remember to clear the previous transformation between frames.
def setListenerVelocityAuto(self): self.listener_vel = None
[ "def velocity(self, t):\n pass", "def object_velocity(self, object_id, object_type, local_frame=False):\n if not isinstance(object_type, int):\n object_type = _str2type(object_type)\n velocity = np.empty(6, dtype=np.float64)\n if not isinstance(object_id, int):\n object_id = self.model.name2id(object_id, object_type)\n mujoco.mj_objectVelocity(self._model.ptr, self._data, object_type,\n object_id, velocity, local_frame)\n # MuJoCo returns velocities in (angular, linear) order, which we flip here.\n return velocity.reshape(2, 3)[::-1]", "def getListenerVelocity(self):\n if self.listener_vel is not None:\n return self.listener_vel\n elif self.listener_target is not None:\n clock = ClockObject.getGlobalClock()\n return self.listener_target.getPosDelta(self.root) / clock.getDt()\n else:\n return VBase3(0, 0, 0)", "def update(self):\n self.rect.x += self.x_velocity\n self.rect.y += self.y_velocity", "def update(self, dt):\n super().update(dt)\n self.velocity.norm = min(self.velocity.norm, self.max_speed)", "def update_velocity(self, msg):\n\t\tself.ekf.vel = enu_to_ned(np.array([[msg.twist.linear.x], [msg.twist.linear.y], [msg.twist.linear.z]]))", "def set_velocity(self, velocity):\n self.mover.set_velocity(velocity)", "def apply_velocity(self, **kwargs):\n if self.position.get_distance(self._target) < 30:\n if self._target == self._start:\n self._target = self._end\n else:\n self._target = self._start\n\n direction = (self._target - self.position).normalized()\n self.velocity = direction * 2\n self.position += self.velocity\n self.generate_vertices()", "def physics_update(self) -> None:\n if not self.stopped:\n self.velocity += helpers.V(magnitude=self.gravity_power, angle=180)", "def update(self, time_step):\r\n self.position.propagate(self.velocity, time_step)", "def update_position_dead(self):\n self.rect.y += self.y_velocity * self.dtime", "def setVel(self,cmd):\n if self.time == 0.0:\n self.time = time.time()\n # update the velocity, assume the velocity takes times to change (to avoid local minimum)\n self.curVel = self.inertia*array(cmd)+(1-self.inertia)*self.curVel\n self.pose[0:2] = self.pose[0:2]+array(self.curVel)*(time.time()-self.time)\n self.time = time.time()\n # the orintation is kept the same (rad)\n # TODO: allows more robot models", "def setVelocity(self, velocity):\r\n self._velocity = velocity", "def velocity(self):\r\n if self.sprint:\r\n return self._absDirection * self.sprintSpeed\r\n else:\r\n return self._absDirection * self.baseSpeed", "def update(self, **kwargs):\n self.apply_velocity()", "def update_velocity_body(self, msg):\n\t\tself.ekf.vel_body = enu_to_ned(np.array([[msg.twist.linear.x], [msg.twist.linear.y], [msg.twist.linear.z]]))", "def angular_velocity(self):\n return 0.0", "def update_velocity(self, entity):\n collision_type = self.detect_collision(entity)\n if (collision_type > 0):\n if (collision_type == 4):\n ## This is a top or bottom collision\n entity.velocity = entity.velocity[0] , entity.velocity[1] * -1\n elif(collision_type == 1):\n ## This is a left or right collision\n entity.velocity = entity.velocity[0] * -1, entity.velocity[1]\n elif (collision_type > 4):\n ## This is multiple collision occuring\n entity.velocity = entity.velocity[0] * -1, entity.velocity[1] * -1\n else:\n return", "def move(self):\n # We first limit the velocity to not get bubbles that go faster than what we can enjoy.\n if self.velocity.length() > self.MAX_VELOCITY:\n self.velocity.scale_to_length(self.MAX_VELOCITY)\n\n self.position += self.velocity\n debug.vector(self.velocity, self.position, scale=10)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the velocity of the listener.
def getListenerVelocity(self): if self.listener_vel is not None: return self.listener_vel elif self.listener_target is not None: clock = ClockObject.getGlobalClock() return self.listener_target.getPosDelta(self.root) / clock.getDt() else: return VBase3(0, 0, 0)
[ "def get_velocity(self):\n return self.vr.simxGetObjectVelocity(self.car_handle, \n vrep.simx_opmode_buffer)[0]", "def get_velocity(self):\n linear, angular = self._physics_client.getBaseVelocity(self.uid)\n return np.asarray(linear), np.asarray(angular)", "def velocity(self):\r\n if self.sprint:\r\n return self._absDirection * self.sprintSpeed\r\n else:\r\n return self._absDirection * self.baseSpeed", "def SoListenerDopplerElement_getDopplerVelocity(state: 'SoState') -> \"SbVec3f const &\":\n return _coin.SoListenerDopplerElement_getDopplerVelocity(state)", "def getDopplerVelocity(state: 'SoState') -> \"SbVec3f const &\":\n return _coin.SoListenerDopplerElement_getDopplerVelocity(state)", "def velocity_p(self):\n return self._velocity_p", "def getDopplerVelocity(self) -> \"float\":\n return _coin.SoVRMLSound_getDopplerVelocity(self)", "def velocity(self, t):\n pass", "def velocity(self) -> qty.Velocity:\n v = self._flow_rate / self._cross_section.area()\n return qty.Velocity(v)", "def v(self):\n return self.velocity + self.dv()", "def get_y_velocity(self):\n return self.__dy", "def get_velocity(position):\r\n x, y = position\r\n vel = np.array([gradx_interp(y, x)[0][0],\r\n grady_interp(y, x)[0][0]])\r\n\r\n return vel / np.linalg.norm(vel)", "def velocity(self):\n if self.vmax > 0:\n mod = VelField(x_0=self.x_0,\n y_0=self.y_0,\n r_eff=self.r_eff,\n ellip=self.ellip,\n theta=self.theta,\n vmax=self.vmax,\n q=self.q)\n result = mod(self.x, self.y)\n else:\n result = np.ones(shape=self.x.shape)\n\n return result", "def vel_coef(self):\n return self._vel_coef", "def angular_velocity(self):\n return 0.0", "def get_linear_velocity(self):\n return np.array(self._dc.get_rigid_body_linear_velocity(self.handle))", "def get_angular_velocity(self):\n return np.array(self._dc.get_rigid_body_angular_velocity(self.handle))", "def velocity(slowness):\n return 0.3048 / ((slowness * (10**(-6))))", "def get_waypoint_velocity(waypoint):\n return waypoint.twist.twist.linear.x" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sound will come from the location of the object it is attached to. If the object is deleted, the sound will automatically be removed.
def attachSoundToObject(self, sound, object): # sound is an AudioSound # object is any Panda object with coordinates for known_object in list(self.sound_dict.keys()): if self.sound_dict[known_object].count(sound): # This sound is already attached to something #return 0 # detach sound self.sound_dict[known_object].remove(sound) if len(self.sound_dict[known_object]) == 0: # if there are no other sounds, don't track # the object any more del self.sound_dict[known_object] if object not in self.sound_dict: self.sound_dict[WeakNodePath(object)] = [] self.sound_dict[object].append(sound) return 1
[ "def play_sound(sound_object):\n sound_object.play()\n time.sleep(0.5)\n sound_object.stop()", "def BACKGROUND_MUSIC(self): \n musicSound = Sound(source = 'ninja.wav')\n musicSound.play()", "def hit_sound(self):\n self.alien_explosion_sound.play()", "def PlaySound(self):\n\t if (self.sounds != None):\n\t lst_idx = randint(0, len(self.sounds)-1)\n\t snd_list = self.sounds[lst_idx]\n\t pygame.mixer.music.stop()\n\t for idx, snd in enumerate(snd_list):\n\t if (idx == 0):\n\t pygame.mixer.music.load(snd)\n\t pygame.mixer.music.play()\n\t else:\n\t pygame.mixer.music.queue(snd)", "def playback_word(self):\n playsound(self.sound_file)", "def import_sounds(self):\n pygame.mixer.pre_init(buffer=1024)\n self.troll_sound = pygame.mixer.Sound('sounds/troll_music.wav')", "def emit_sound(self, sound):\n sound_manager.emit_sound(sound, self.index)", "def TestSound():\n SoundsPath = os.path.join(AudioFilesPath, MySet.Sound + \".mp3\")\n Parent.PlaySound(SoundsPath, MySet.Volume*0.01)", "def play_bg_music(self):\n pygame.mixer.music.play(-1)", "def soundAlarm(self):\n\n self._beeper.start()", "def audioObject(self):\n return self.audioObjects[-1] if self.audioObjects is not None else None", "def play_sound(self, filename):\n if filename not in self._sounds.keys():\n loaded = raylibpy.load_sound(filename)\n self._sounds[filename] = loaded\n\n sound = self._sounds[filename]\n raylibpy.play_sound(sound)", "def openSoundTool(sound):\n #import SoundExplorer\n thecopy = duplicateSound(sound)\n #Constructor has side effect of showing it\n SoundExplorer(thecopy)", "def play_sound() -> None:\n # Please note that I do not like to put import statements here because\n # it is categorized as a code smell. However, I need this to get rid of\n # the message in the beginning that is forced upon every developer who\n # needs Pygame. On a side note, I am looking to replace Pygame with\n # PySide2 in the future.\n from os import environ\n environ['PYGAME_HIDE_SUPPORT_PROMPT'] = \"True\"\n\n import pygame.mixer\n pygame.mixer.init()\n pygame.mixer.music.load(\"../../media/beep.wav\")\n pygame.mixer.music.play()", "def sound_source(self):\n return self._dupli_object", "def play(sound):\n if not isinstance(sound,Sound):\n #print \"play(sound): Input is not a sound\"\n #raise ValueError\n repTypeError(\"play(sound): Input is not a sound\")\n sound.play()", "def _playSound(self):\n self.sound.play()\n self.timesPlayed += 1\n self.isPlaying = True\n self.shouldPlay = False\n self._resetTimer()", "def register_sound(self, path) -> pygame.mixer.Sound:\n try:\n effect = pygame.mixer.Sound(path)\n self.sound_effects[path] = effect\n return effect\n except pygame.error:\n raise FileExistsError(\"File '{0}' does not exist. Check your path to the sound.\".format(path))", "def Sound(sound_file_name):\n return pygame.mixer.Sound(get_file(sound_file_name))" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns a list of sounds attached to an object
def getSoundsOnObject(self, object): if object not in self.sound_dict: return [] sound_list = [] sound_list.extend(self.sound_dict[object]) return sound_list
[ "def get_all_audio(self):\n return [x.file for x in self.audio_data.values()]", "def _get_sounds(directory):\n dirlist = os.listdir(directory)\n sound = {}\n for fx in dirlist:\n if fx[-3:] == \"wav\":\n sound[fx[:-4]] = pg.mixer.Sound(os.path.join(directory,fx))\n return sound", "async def sounds(message):\n\n sound_embed = await embed_list(\n title='Sound List', \n description='All currently loaded sounds', \n column_header=':loud_sound: Sound Names', \n list_to_embed=soundfiles, \n footer='Play a sound with \"{}[sound name]\"'.format(SOUNDBOT_PREFIX)\n )\n\n await message.channel.send(embed=sound_embed)", "def __get_sound_resources(self):\r\n resources = []\r\n preload_manager = servers.get_preload_manager()\r\n for i in range( preload_manager.getnumsoundstopreload() ):\r\n resources.append( preload_manager.getsoundtopreload(i) )\r\n return resources", "def get_audios(self) -> List[Dict[str, str]]:\n with self.cursor(dictionary=True) as cur:\n cur.execute(self.SELECT_AUDIOS)\n return list(cur)", "def load_sounds(self):\r\n\t\tself.sounds = 'pinwheel.wav','die.wav','square.wav','start.wav', \\\r\n\t\t'rhombus.wav','crash.wav' ,'triangle2.wav','octagon.wav','deathstar.wav',\\\r\n\t\t'deathstar2.wav','die1.wav'\r\n\t\tfor filename in self.sounds:\r\n\t\t\tGlobal.sounds[filename] = pygame.mixer.Sound('sounds/'+filename)", "def getSamples(sound):\n if not isinstance(sound, Sound):\n #print(\"getSamples(sound): Input is not a sound\")\n #raise ValueError\n repTypeError(\"getSamples(sound): Input is not a sound\")\n return sound.getSamples()", "def list_mp3(self):\n os.chdir(self.dir)\n return glob.glob(\"*.mp3\")", "def sound_mode_list(self):\n return self._soundmode_list", "async def enumerate_sounds():\n soundfiles.clear()\n\n # find all mp3 files in the soundboard directory\n for f in os.listdir('soundboard/'):\n soundname = os.path.splitext(str(f))[0]\n if os.path.isfile('soundboard/{}.mp3'.format(soundname)):\n soundfiles.append(soundname)\n\n # optional: sort the files alphabetically\n soundfiles.sort()", "def all_speakers():\n return [_Speaker(id=s['id']) for s in _pulse.sink_list]", "def attachSoundToObject(self, sound, object):\n # sound is an AudioSound\n # object is any Panda object with coordinates\n for known_object in list(self.sound_dict.keys()):\n if self.sound_dict[known_object].count(sound):\n # This sound is already attached to something\n #return 0\n # detach sound\n self.sound_dict[known_object].remove(sound)\n if len(self.sound_dict[known_object]) == 0:\n # if there are no other sounds, don't track\n # the object any more\n del self.sound_dict[known_object]\n\n if object not in self.sound_dict:\n self.sound_dict[WeakNodePath(object)] = []\n\n self.sound_dict[object].append(sound)\n return 1", "def getAudio(self):\n\t\tpass", "def get_waves(self) -> typing.List[SimpleWave]:\r\n\r\n return self._waves", "def get_beep_names(self):\n return self.beeps.keys()", "def load_sounds(self):\n try:\n pygame.mixer.init()\n except:\n print 'Cannot load sound'\n self.soundon = False\n finally:\n pygame.mixer.music.load(data.filepath('purity.ogg'))\n self.sfx = {'click': pygame.mixer.Sound(data.filepath('click.ogg')),\n 'complete': pygame.mixer.Sound(data.filepath('complete.ogg')),\n 'hitroid': pygame.mixer.Sound(data.filepath('atari.ogg')),\n 'error': pygame.mixer.Sound(data.filepath('error.ogg')),\n 'pbar': pygame.mixer.Sound(data.filepath('pbar.ogg')),\n 'startgame': pygame.mixer.Sound(data.filepath('startgame.ogg'))\n }\n self.soundon = True", "def findSound(fileName):\n return fileSearch(fileName, \"sounds\", [\"wav\", \"mp3\"])", "def plays(self):\r\n return GenPlays(itertools.chain(*map(lambda d: d.plays, self)))", "def title_streams(self):\n return [stream[\"tags\"].get(\"handler_name\") for stream in self.audio_streams]", "def sound_source(self):\n return self._dupli_object" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates position of sounds in the 3D audio system. Will be called automatically in a task.
def update(self, task=None): # Update the positions of all sounds based on the objects # to which they are attached # The audio manager is not active so do nothing if hasattr(self.audio_manager, "getActive"): if self.audio_manager.getActive()==0: return Task.cont for known_object, sounds in list(self.sound_dict.items()): node_path = known_object.getNodePath() if not node_path: # The node has been deleted. del self.sound_dict[known_object] continue pos = node_path.getPos(self.root) for sound in sounds: vel = self.getSoundVelocity(sound) sound.set3dAttributes(pos[0], pos[1], pos[2], vel[0], vel[1], vel[2]) # Update the position of the listener based on the object # to which it is attached if self.listener_target: pos = self.listener_target.getPos(self.root) forward = self.root.getRelativeVector(self.listener_target, Vec3.forward()) up = self.root.getRelativeVector(self.listener_target, Vec3.up()) vel = self.getListenerVelocity() self.audio_manager.audio3dSetListenerAttributes(pos[0], pos[1], pos[2], vel[0], vel[1], vel[2], forward[0], forward[1], forward[2], up[0], up[1], up[2]) else: self.audio_manager.audio3dSetListenerAttributes(0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1) return Task.cont
[ "def set_player_position(self, position):", "def position(self, position):\n self._position = position\n\n # Pyglet uses 3d coordinates, convert 2d to a 3d tuple\n self._player.position = (position[0], position[1], 0)", "def update(self):\r\n self.updateVelocities()\r\n self.updatePositions()", "def update_position(self):\n\t\tself.heading += self.turn_rate\n\t\tself.position[0] += -sin(self.heading) * self.speed\n\t\tself.position[1] += cos(self.heading) * self.speed", "def import_sounds(self):\n pygame.mixer.pre_init(buffer=1024)\n self.troll_sound = pygame.mixer.Sound('sounds/troll_music.wav')", "def _update_position(self, (x, y), (q, z), angle):\n self._current_position = (x, y)\n self._current_direction = (q, z)\n self._current_angle = angle\n self._senderPi_position.sent_position(x, y)\n self._senderPi_direction.sent_direction(self.get_angle())\n self._current_angle = (angle * 180.0) / pi\n self.add_to_console(\"[ \" + str(datetime.now().time())[:11] + \" ] \"\n + \"Current position: \" + str(self.get_position()))", "def updatePositions(self) -> None:\r\n for idx in range(self.size()):\r\n self.bodies[idx].updatePosition()", "def change_pyttsx3_volume(self, new_volume: float):\r\n self.pyttsx3_volume = new_volume", "def playback_word(self):\n playsound(self.sound_file)", "def update_positions(self):\n\n # Get all player's snake positions\n all_players_positions = list(self.get_all_players_positions())\n\n # Send these positions to all players\n for player in self.players.values():\n\n player.Send({\"action\": \"game_state\", \"message\": {\n 'step': self.step,\n 'players': all_players_positions,\n 'foods': list(self.foods.keys())\n }})", "def set_pyttsx3_properties(self):\r\n self.engine.setProperty(\"rate\", self.pyttsx3_rate)\r\n self.engine.setProperty(\"volume\", self.pyttsx3_volume)\r\n self.engine.setProperty(\"voice\", self.lang)", "def update_xyz(self):\n # Take the values from the corresponding spinBoxes\n goal = list()\n goal.append(self.spinx.value())\n goal.append(self.spiny.value())\n goal.append(self.spinz.value())\n # Ask the server to move xyz\n from_arm_server(7, goal)\n # Update sliders and labels\n self.refresh_joints()", "def TestSound():\n SoundsPath = os.path.join(AudioFilesPath, MySet.Sound + \".mp3\")\n Parent.PlaySound(SoundsPath, MySet.Volume*0.01)", "def set_position(self, position):\n self.mediaplayer.set_position(position / 1000.0)", "def update_pos(self) -> None:\n self.pos = (self.pos[0] + self.touch.dpos[0], self.pos[1] + self.touch.dpos[1])", "def update_volume(self, volumn):\n for sound in self.sound_dict.values():\n sound.set_volume(volumn)\n pygame.mixer.music.set_volume(volumn)", "def update_track(self, index, lon, lat, time, uavg, teke,\n radius_s, radius_e, amplitude, temp=None, salt=None,\n contour_e=None, contour_s=None, uavg_profile=None,\n shape_error=None):\n self.tracklist[index].append_pos(\n lon, lat, time, uavg, teke,\n radius_s, radius_e, amplitude, temp=temp,\n salt=salt, contour_e=contour_e,\n contour_s=contour_s, uavg_profile=uavg_profile,\n shape_error=shape_error)", "def update(self, plays, feedback):\n N = self.N[plays]\n self.means[plays] = (self.means[plays]*N + feedback) / \\\n (N+1) # update empirical mean\n self.N[plays] += 1 # update counters\n\n if self.init:\n # end init. if all arms have been pulled at least init_count times\n self.init = (self.N == 0).any()", "def audacious_playlist_position(self):\n self.writeCommand('audacious_playlist_position')\n return self" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Detaches any existing sounds and removes the update task
def disable(self): taskMgr.remove("Audio3DManager-updateTask") self.detachListener() for object in list(self.sound_dict.keys()): for sound in self.sound_dict[object]: self.detachSound(sound)
[ "def destroyPlayTimers(self):\n try:\n gobject.source_remove(self.timSec)\n except:\n pass", "def purge():\n common.debug('Purging library: {}'.format(g.library()))\n for library_item in g.library().values():\n execute_library_tasks(library_item['videoid'], remove_item,\n common.get_local_string(30030),\n sync_mylist=False)", "def reset_audio(self):\r\n for audio_file in self.vehicle_audio_list:\r\n if audio_file.state() == 1:\r\n audio_file.stop()", "def delete_unfingerprinted_audios(self) -> None:\n with self.cursor() as cur:\n cur.execute(self.DELETE_UNFINGERPRINTED)", "def delete(self):\n if self._source:\n self.source.is_player_source = False\n if self._audio_player:\n self._audio_player.delete()\n self._audio_player = None\n if self._texture:\n self._texture = None", "def playlist_updated():\n files = dict()\n for m in control.emergency_playlist:\n log.debug(\"E: \" + m.messageId)\n files[m.messageId] = m.messageId\n\n for m in control.playlist:\n log.debug(\"P: \" + m.messageId)\n files.pop(m.messageId, None)\n\n for f in files:\n log.info(\"Deleting \" + get_filename(f))\n os.unlink(get_filename(f))\n\n control.emergency_playlist = control.playlist[:]", "def clean():\n _rpc.request('AudioLibrary.Clean')", "async def unload(self) -> None:\n if self._startup_task:\n # If we were waiting on startup, cancel that and let the task finish before proceeding\n self._startup_task.cancel(f\"Removing add-on {self.name} from system\")\n with suppress(asyncio.CancelledError):\n await self._startup_task\n\n for listener in self._listeners:\n self.sys_bus.remove_listener(listener)\n\n if not self.path_data.is_dir():\n return\n\n _LOGGER.info(\"Removing add-on data folder %s\", self.path_data)\n await remove_data(self.path_data)", "def cleanup_files(self):\n os.system(\"rm -r /tmp/kernelpop\")", "def unPause():\n if os.path.exists(pauseFile):\n os.remove(pauseFile)", "def disable(self):\n self.registrar.unregister_service(\"play\")\n self.registrar.unregister_service(\"listen\")\n self.registrar.unregister_service(\"pause\")\n self.registrar.unregister_service(\"stop\")\n self.registrar.unregister_service(\"song\")", "def delAsset(self):\n pass", "def remove(self, args):\n self.logger.info(\"removing song \" + args.id + \" from library\")\n self.databaser.remove(args.id)", "def purge():", "async def stop(self):\n self.playing = False\n self.pm.clean()\n self.entries[:] = []\n\n await self.bot.say(\":information_source: Stopping the blindtest\")\n\n if self.player is not None:\n if self.player.is_playing() is True:\n self.player.stop()\n\n if self.voice is not None:\n if self.voice.is_connected() is True:\n await self.voice.disconnect()\n \n self.voice = None\n self.player = None", "def disarm(self):\n self.act = None\n Framework.removeTimeEvent(self)", "def stopmusic(cls) -> None:\n pygame.mixer.music.stop()", "def unwatch(self):\n self.is_watched = False", "def cleanup() -> None:\n\n global _broadcaster\n _broadcaster = None" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Runs the vhdeps CLI. The commandline arguments are taken from `args` when specified, or `sys.argv` by default. The return value is the exit code for the process. If the backtrace option is passed, exceptions will not be caught.
def run_cli(args=None): parser = argparse.ArgumentParser( usage='vhdeps <target> [entities...] [flags...] [--] [target-flags...]', description='This script is a VHDL dependency analyzer. Given a list ' 'of VHDL files and/or directories containing VHDL files, it can ' 'generate a compile order and output this in various formats, such ' 'as a TCL file to be sourced by a Modelsim-compatible simulator. ' 'Specify --targets to list the available targets/output formats. ' 'In addition, this script can check some style rules, and prevents ' 'accidental black-box insertion due to missing entities for component ' 'declarations, by making you explicitly opt out of this behavior when ' 'necessary.') # Positional arguments. parser.add_argument( 'target', metavar='target', nargs='?', default=None, help='Target simulator/synthesizer. Specify --targets to print the ' 'list of supported targets.') parser.add_argument( 'entity', metavar='entity', nargs='*', help='Specifies the toplevel entity/ies to be compiled. When specified, ' 'the compile order will be such that only these entities and their ' 'dependencies are included. If not specified, all files are included. ' 'Entities are specified by their VHDL name, optionally prefixed with ' 'the library they\'re compiled into. Glob-style pattern matching is ' 'also supported.') # Source directory specifications. At least one of these should be # specified for this program to do anything useful. parser.add_argument( '-i', '--include', metavar='{{version:}lib:}path', action='append', default=[], help='Includes VHDL files for dependency analysis. If the path is a ' 'directory, it is scanned recursively; if it is a file, only that ' 'file is added. If the path contains * or ?, it is instead treated as ' 'a non-recursive file glob, so \'<path>/*.vhd\' can be used to ' 'include a directory non-recursively. If lib is specified, it marks ' 'that files must be compiled into the specified library name instead ' 'of the default (work). If version is specified, all files in the ' 'directory are assumed to have the given VHDL version, regardless of ' 'version tags in the filenames.') parser.add_argument( '-I', '--strict', metavar='{{version:}lib:}path', action='append', default=[], help='Same as -i, but also enforces style rules. Specify --style for more ' 'information.') parser.add_argument( '-x', '--external', metavar='{{version:}lib:}path', action='append', default=[], help='Same as -i, but the included files are allowed to have unresolved ' '"black-box" components. Useful for interfaces to Verilog or for vendor ' 'libraries.') # Filters. parser.add_argument( '-d', '--desired-version', metavar='desired-version', type=int, default=None, help='Desired VHDL version, specified as 2-digit or 4-digit year. Default ' '2008. This is used when multiple versions of a VHDL file are available, ' 'indicated through *.<version>.* tags in the filename, where <version> is ' 'a two-digit year. A file can be tagged with multiple versions if it is ' 'compatible with multiple versions. Files that are not tagged at all are ' 'assumed to be valid in all versions of VHDL.') parser.add_argument( '-v', '--version', metavar='version', type=int, default=None, help='Target VHDL version, specified as 2-digit or 4-digit year. Default ' 'is mixed-mode. When specified, files that include version tags for only ' '*other* VHDL versions are filtered out. These version tags are indicated ' 'through *.<version>.* tags in the filename, where <version> is a ' 'two-digit year. Targets that do not support mixing different VHDL ' 'versions require this flag to be set.') parser.add_argument( '-m', '--mode', choices=['sim', 'syn', 'all'], default='sim', help='Specifies the target compilation mode. Defaults to sim. This flag ' 'controls a filename filter intended to be used to mark files as ' 'simulation- or synthesis-only: if a VHDL filename matches *.sim.* it is ' 'considered simulation-only, if it matches *.syn.* it is considered ' 'synthesis-only. Specify -m all to disable this filter.') # Output control. parser.add_argument( '-o', '--outfile', default=None, help='Output file. If not specified, stdout is used.') # Debugging. parser.add_argument( '--stacktrace', action='store_true', help='Print complete Python stack traces instead of just the message.') # Help information. parser.add_argument( '--targets', action='store_true', help='List the supported targets.') parser.add_argument( '--style', action='store_true', help='Print information about the VHDL style rules enforced by ' '--strict.') parser.add_argument( '--vhdeps-version', action='version', version='vhdeps ' + __version__, help='Prints the current version of vhdeps and exits.') try: # Parse the command line. if args is None: args = sys.argv[1:] if '--' in args: index = args.index('--') target_args = args[index+1:] args = parser.parse_args(args[:index]) else: args, target_args = parser.parse_known_args(args) # Print additional information and exit if requested using --targets or # --style. --help also falls within this category, but argparse handles # that internally. if args.targets: target_mod.print_help() return 0 if args.style: print('The following style rules are enforced by -I/--strict:') print(' - Each VHDL file must define exactly one entity or exactly one package.') print(' - VHDL package names must use the _pkg suffix.') print(' - The filename must match the name of the VHDL entity/package.') return 0 # Select the target. if args.target is None: print('Error: no target specified.', file=sys.stderr) parser.print_usage() return 1 target = target_mod.get_target(args.target) if target is None: print('Error: unknown target "%s".' % args.target, file=sys.stderr) print('Specify --targets to get a listing of all supported targets.', file=sys.stderr) return 1 # Parse the target's arguments, if any. target_args = target_mod.get_argument_parser(args.target).parse_args(target_args) except SystemExit as exc: return exc.code # Construct the list of VHDL files. vhd_list = vhdl.VhdList( mode=args.mode, desired_version=args.desired_version, required_version=args.version) try: # Add the specified files/directories to the VHDL file list. def add_dir(arglist, **kwargs): for arg in arglist: arg = arg.split(':', maxsplit=2) fname = arg[-1] lib = arg[-2] if len(arg) >= 2 else 'work' override_version = int(arg[-3]) if len(arg) >= 3 else None if '*' in fname or '?' in fname: for match in glob.glob(fname): vhd_list.add_file( match, lib=lib, override_version=override_version, **kwargs) elif os.path.isdir(fname): vhd_list.add_dir( fname, lib=lib, override_version=override_version, **kwargs) elif os.path.isfile(fname): vhd_list.add_file( fname, lib=lib, override_version=override_version, **kwargs) else: raise ValueError('file/directory not found: "%s"' % fname) # Default to including the working directory if no includes are specified. if not args.include and not args.strict and not args.external: print('Including the current working directory recursively by default...', file=sys.stderr) args.include.append('.') add_dir(args.include) add_dir(args.strict, strict=True) add_dir(args.external, allow_bb=True) if not vhd_list.files: print('Warning: no VHDL files found.', file=sys.stderr) else: # Determine the compile order. vhd_list.determine_compile_order(args.entity) if not vhd_list.order: print('Warning: no design units found.', file=sys.stderr) elif not vhd_list.top: print('Warning: no toplevel entities found.', file=sys.stderr) # Run the selected target with the selected output file or stdout. if args.outfile is None: code = target.run(vhd_list, sys.stdout, **vars(target_args)) else: with open(args.outfile, 'w') as output_file: code = target.run(vhd_list, output_file, **vars(target_args)) if code is None: code = 0 return code except Exception as exc: #pylint: disable=W0703 if args.stacktrace: raise print('%s: %s' % (str(type(exc).__name__), str(exc)), file=sys.stderr) return 1 except KeyboardInterrupt as exc: if args.stacktrace: raise return 1
[ "def main():\n backup_args = None\n try:\n\n freezer_config.config(args=sys.argv[1:])\n freezer_config.setup_logging()\n backup_args = freezer_config.get_backup_args()\n if backup_args.config:\n # reload logging configuration to force oslo use the new log path\n if backup_args.log_config_append:\n CONF.set_override('log_config_append',\n backup_args.log_config_append)\n\n freezer_config.setup_logging()\n\n if len(sys.argv) < 2:\n CONF.print_help()\n sys.exit(1)\n freezer_main(backup_args)\n\n except Exception as err:\n quiet = backup_args.quiet if backup_args else False\n LOG.exception(err)\n LOG.critical(\"Run freezer agent process unsuccessfully\")\n return fail(1, err, quiet)", "def main(args=None):\n click.echo(\"Replace this message by putting your code into \" \"zlmdb.cli.main\")\n click.echo(\"See click documentation at http://click.pocoo.org/\")\n return 0", "def check_dependencies(args):\n missing_deps = []\n\n # The list of modules we need to be available in the Python\n # distribution.\n required_modules = [\"pytest\", \"e3\"]\n if args.verify_style_conformance:\n required_modules.append(\"flake8\")\n\n # The list of programs we need to be installed and accessible\n # through the PATH.\n required_programs = [\n (\"/bin/csh\", \"/bin/csh\"),\n (\"checkstyle\", \"Java style checker (checkstyle)\"),\n (\"coverage\", \"pytest-cov plugin for pytest\"),\n (\"gnatls\", \"GNAT Pro in your PATH\"),\n ]\n\n # First, check that the Python being used is recent enough.\n python_version = StrictVersion(\n \"{v.major}.{v.minor}\".format(v=sys.version_info))\n if python_version < MINIMUM_PYTHON_VERSION:\n print(\"ERROR: Your version of Python is too old: \"\n \"({v.major}.{v.minor}.{v.micro}-{v.releaselevel})\"\n .format(v=sys.version_info))\n print(\" Minimum version required: {}\"\n .format(MINIMUM_PYTHON_VERSION))\n print(\"Aborting.\")\n sys.exit(1)\n\n # Next, check that all required dependencies are there.\n for module_name in required_modules:\n if importlib.util.find_spec(module_name) is None:\n missing_deps.append(f\"Python module: {module_name}\")\n\n for exe, description in required_programs:\n if shutil.which(exe) is None:\n missing_deps.append(description)\n\n # If anything was missing, report it and abort.\n if missing_deps:\n print(\"ERROR: The testing environment is missing the following:\")\n for dep in missing_deps:\n print(f\" - {dep}\")\n sys.exit(1)", "def main():\n option_parser = optparse.OptionParser(usage=USAGE)\n\n option_parser.add_option('', '--target', default='Release',\n help='build target (Debug or Release)')\n option_parser.add_option('', '--build-dir', default='chrome',\n help='path to main build directory (the parent of '\n 'the Release or Debug directory)')\n options, args = option_parser.parse_args()\n if args:\n option_parser.error('No args are supported')\n\n build_dir = os.path.abspath(options.build_dir)\n exe_path = os.path.join(build_dir, options.target, 'crash_service.exe')\n if not os.path.exists(exe_path):\n raise chromium_utils.PathNotFound('Unable to find %s' % exe_path)\n\n # crash_service's window can interfere with interactive ui tests.\n cmd = exe_path + ' --no-window'\n\n print '\\n' + cmd + '\\n',\n\n # We cannot use Popen or os.spawn here because buildbot will wait until\n # the process terminates before going to the next step. Since we want to\n # keep the process alive, we need to explicitly say that we want the\n # process to be detached and that we don't want to inherit handles from\n # the parent process.\n si = win32process.STARTUPINFO()\n details = win32process.CreateProcess(None, cmd, None, None, 0,\n win32process.DETACHED_PROCESS, None,\n None, si)\n print '\\nCreated with process id %d\\n' % details[2]\n return 0", "def main():\n parser = argparse.ArgumentParser(description='Verify and install dependencies.')\n parser.add_argument('command', help=\"What to do.\")\n\n parser.add_argument('dependencies', nargs='+', help=\"Path to dependency files.\")\n\n args = parser.parse_args()\n\n full_file_paths = [os.path.abspath(path) for path in args.dependencies]\n\n parse_dependencies(full_file_paths)\n\n return True", "def run_cli(args):\n print(\"TODO: You can implement a non-Harmony CLI here.\")\n print('To see the Harmony CLI, pass `--harmony-action=invoke '\n '--harmony-input=\"$(cat example/example_message.json)\" '\n '--harmony-sources=example/source/catalog.json --harmony-output-dir=tmp/`')", "def main_revdeps(args):\n # Load symbols from Kconfig\n kconfig = autokernel.kconfig.load_kconfig(args.kernel_dir)\n\n for config_symbol in args.config_symbols:\n sym = get_sym_by_name(kconfig, config_symbol)\n log.info(\"Dependents for {}:\".format(sym.name))\n for d in sym._dependents: # pylint: disable=protected-access\n print(d)", "def run():\n args = get_args()\n try:\n conf = main(args)\n except: # noqa\n if not logger.handlers:\n # Add a logging handler if main failed to do so.\n logging.basicConfig()\n logger.exception(\n \"Program terminated abnormally, see stack trace \"\n \"below for more information\",\n exc_info=True)\n logger.info(\n \"If you suspect this is a bug or need help, please open an issue \"\n \"on https://github.com/ESMValGroup/ESMValTool/issues and attach \"\n \"the run/recipe_*.yml and run/main_log_debug.txt files from the \"\n \"output directory.\")\n sys.exit(1)\n else:\n if conf[\"remove_preproc_dir\"]:\n logger.info(\"Removing preproc containing preprocessed data\")\n logger.info(\"If this data is further needed, then\")\n logger.info(\"set remove_preproc_dir to false in config\")\n shutil.rmtree(conf[\"preproc_dir\"])\n logger.info(\"Run was successful\")", "def main(args=None):\n parsed_args = _parse_args(args)\n _initialize_configuration(parsed_args.pop('subcommand'), parsed_args.pop('config_file'))\n subcommand_class = parsed_args.pop('subcommand_class') # defined in _parse_args() by subparser.set_defaults()\n\n try:\n unhandled_exception_handler = UnhandledExceptionHandler.singleton()\n with unhandled_exception_handler:\n subcommand_class().run(**parsed_args)\n\n finally:\n # The force kill countdown is not an UnhandledExceptionHandler teardown callback because we want it to execute\n # in all situations (not only when there is an unhandled exception).\n _start_app_force_kill_countdown(seconds=10)", "def v_run(self, cmd, args, returncode_ok=lambda x:x == 0):\n cmd = [cmd]\n if self.verbose:\n cmd.append('-v')\n cmd.extend(args)\n return self.run(cmd, returncode_ok)", "def main(argv=None):\n if argv is None:\n argv = sys.argv\n \n try:\n try:\n \n # create the top-level parser\n d = \"\"\"This is the CLI for clippyl's bedgraph creation program\"\"\"\n parser = argparse.ArgumentParser(description=d)\n \n #bam_fp_l, required\n parser.add_argument('bam', nargs='+')\n \n #readid_db_fp_l, optional kwarg\n # Note: if the cleav_db_fp is set to None then it is assumed that all\n # the reads in the sam file are adapter-clipped.\n # note: there must be one cleav_file per bam_file\n parser.add_argument('--discardUnclipped_db', nargs='+', \n default=None)\n \n #TODO: parameterize the normalization factor because clippedonly \n # and histonly files do not contain all reads\n \n #only hits-clip is currently supported (optional kwarg)\n #TODO: incorporate code for par-clip and iclip\n parser.add_argument('--clipseq_method', choices=['hits-clip',],\n default='hits-clip')\n \n #TODO: allow argparse from argument file\n #https://docs.python.org/3/library/argparse.html#fromfile-prefix-chars\n \n # parse the args\n args = parser.parse_args(argv)\n #print(args) #debugging\n \n if args.clipseq_method == 'hits-clip':\n hitsclip_bg_dump(args)\n else:\n #TODO: incorporate par-clip and iclip options\n pass\n \n except SystemExit as exitStat:\n raise Usage(exitStat)\n \n except Usage as err:\n return err.exitStat", "def main(cli_args=None):\n\n # create an argument parser\n parser = argparse.ArgumentParser(\n description=\"duckpy: Duckyscript interpreter written in Python\",\n prog=\"duckpy\"\n )\n\n # add arguments\n parser.add_argument(\n \"dscript\", help=\"duckyscript file to execute (should be plaintext)\"\n )\n parser.add_argument(\n \"-v\", \"--verbose\", help=\"Print log messages to screen (level INFO)\",\n action='store_true', default=False\n )\n parser.add_argument(\n \"-vv\", \"--vverbose\", help=\"Print log messages to screen (level \"\n \"DEBUG). Note that this will print a \"\n \"lot of output.\",\n action='store_true', default=False\n )\n\n # parse\n if cli_args:\n # pass in given cli arguments string\n args = parser.parse_args(cli_args.split(' '))\n else:\n # otherwise get arguments from call\n args = parser.parse_args()\n\n # setup logging levels\n log_level = LOG_LEVEL_DEFAULT # should be set to warning\n if args.vverbose:\n log_level = logging.DEBUG\n elif args.verbose:\n log_level = logging.INFO\n logging.getLogger('duckpy').setLevel(log_level)\n\n # execute script and exit\n script = DuckyScript(args.dscript)\n script.run()", "def run_main(args=sys.argv[1:]):\n # By default, DKR will only log errors\n logger.setLevel(logging.ERROR)\n\n args = parse_arguments(args)\n main(args['base'], args['invocation'])", "def version(args):\n print(f\"Cli - Version : {Helpers.cli_version()}\")", "def run_cli_test(\n test_case_instance,\n cli_argv,\n exit_code,\n output,\n output_checker=lambda output: (lambda q: output[output.find(q) + len(q) :])(\n \"error: \"\n ),\n exception=SystemExit,\n return_args=False,\n):\n argparse_mock, args = MagicMock(), None\n with patch(\"argparse.ArgumentParser._print_message\", argparse_mock), patch(\n \"sys.argv\", cli_argv\n ):\n from offconf.__main__ import main\n\n main_f = partial(main, cli_argv=cli_argv, return_args=return_args)\n if exit_code is None:\n args = main_f()\n else:\n with test_case_instance.assertRaises(exception) as e:\n args = main_f()\n if exit_code is not None:\n test_case_instance.assertEqual(\n *(e.exception.code, exception(exit_code).code)\n if exception is SystemExit\n else (str(e.exception), output)\n )\n if exception is not SystemExit:\n pass\n elif argparse_mock.call_args is None:\n test_case_instance.assertIsNone(output)\n else:\n test_case_instance.assertEqual(\n output_checker(\n (\n argparse_mock.call_args.args\n if version_info[:2] > (3, 7)\n else argparse_mock.call_args[0]\n )[0]\n ),\n output,\n )\n return output, args", "def run():\n sys.exit(main(sys.argv[1:]) or 0)", "def main():\n args = parse_args()\n\n api.check_database()\n\n args.func(args)\n sys.exit(0)", "def run(pyi_args=sys.argv[1:], pyi_config=None):\n misc.check_not_running_as_root()\n\n try:\n parser = optparse.OptionParser(\n usage='%prog [opts] <scriptname> [ <scriptname> ...] | <specfile>'\n )\n __add_options(parser)\n PyInstaller.makespec.__add_options(parser)\n PyInstaller.build.__add_options(parser)\n PyInstaller.log.__add_options(parser)\n PyInstaller.compat.__add_obsolete_options(parser)\n\n opts, args = parser.parse_args(pyi_args)\n PyInstaller.log.__process_options(parser, opts)\n\n # Print program version and exit\n if opts.version:\n print get_version()\n raise SystemExit(0)\n\n if not args:\n parser.error('Requires at least one scriptname file '\n 'or exactly one .spec-file')\n\n # Skip creating .spec when .spec file is supplied\n if args[0].endswith('.spec'):\n spec_file = args[0]\n else:\n spec_file = run_makespec(opts, args)\n\n run_build(opts, spec_file, pyi_config)\n\n except KeyboardInterrupt:\n raise SystemExit(\"Aborted by user request.\")", "def run_program(path, args=[], raises=DummyException, stderr=False):\n path = str(DIRECTORY / path)\n old_args = sys.argv\n assert all(isinstance(a, str) for a in args)\n warnings.simplefilter(\"ignore\", ResourceWarning)\n try:\n sys.argv = [path] + args\n with redirect_stdout(StringIO()) as output:\n error = StringIO() if stderr else output\n with redirect_stderr(error):\n try:\n if '__main__' in sys.modules:\n del sys.modules['__main__']\n SourceFileLoader('__main__', path).load_module()\n except raises:\n pass\n except SystemExit as e:\n if e.args != (0,):\n raise SystemExit(output.getvalue()) from e\n else:\n if raises is not DummyException:\n raise AssertionError(\"{} not raised\".format(raises))\n if stderr:\n return output.getvalue(), error.getvalue()\n else:\n return output.getvalue()\n finally:\n sys.argv = old_args" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
orders a teardrop trace by identifying the streptavidin molecule.
def order_teardrop_trace(td_indices, strep_ind): td_indices = np.append([strep_ind], td_indices, axis=0) # append strep td_indices = order_trace(td_indices, 0) # start ordering with strep td_indices = np.append(td_indices, [strep_ind], axis=0) # close loop return td_indices
[ "def local_tetrahedral_order(dumpfile, filetype = 'lammps', moltypes = '', ppp = [1,1,1], outputfile = ''):\r\n\r\n d = readdump(dumpfile, 3, filetype, moltypes)\r\n d.read_onefile()\r\n num_nearest = 4 #number of selected nearest neighbors\r\n results = np.zeros((max(d.ParticleNumber), d.SnapshotNumber))\r\n\r\n for n in range(d.SnapshotNumber):\r\n hmatrixinv = np.linalg.inv(d.hmatrix[n])\r\n Positions = d.Positions[n]\r\n for i in range(d.ParticleNumber[n]):\r\n RIJ = Positions - Positions[i]\r\n matrixij = np.dot(RIJ, hmatrixinv)\r\n RIJ = np.dot(matrixij - np.rint(matrixij) * ppp, d.hmatrix[n]) #remove PBC\r\n\r\n RIJ_norm = np.linalg.norm(RIJ, axis = 1)\r\n nearests = np.argpartition(RIJ_norm, num_nearest + 1)[:num_nearest + 1]\r\n nearests = [j for j in nearests if j != i]\r\n for j in range(num_nearest - 1):\r\n for k in range(j + 1, num_nearest):\r\n medium1 = np.dot(RIJ[nearests[j]], RIJ[nearests[k]])\r\n medium2 = RIJ_norm[nearests[j]] * RIJ_norm[nearests[k]]\r\n results[i, n] += (medium1 / medium2 + 1.0/ 3) ** 2\r\n\r\n results = np.column_stack((np.arange(d.ParticleNumber[0]) + 1, 1.0 - 3.0 / 8 * results))\r\n\r\n names = 'id q_tetra'\r\n if outputfile:\r\n numformat = '%d ' + '%.6f ' * (results.shape[1] - 1)\r\n np.savetxt(outputfile, results, fmt = numformat, header = names, comments = '')\r\n\r\n print ('---------calculate local tetrahedral order over---------')\r\n return results, names", "def match_order(self):\n\n if self.spectrograph.norders is None:\n msgs.error('Coding error: norders not defined for {0}!'.format(\n self.spectrograph.__class__.__name__))\n if self.spectrograph.orders is None:\n msgs.error('Coding error: orders not defined for {0}!'.format(\n self.spectrograph.__class__.__name__))\n if self.spectrograph.order_spat_pos is None:\n msgs.error('Coding error: order_spat_pos not defined for {0}!'.format(\n self.spectrograph.__class__.__name__))\n\n offset = self.par['order_offset']\n if offset is None:\n offset = 0.0\n\n # This requires the slits to be synced! Masked elements in\n # slit_cen are for bad slits.\n slit_cen = self.slit_spatial_center()\n\n # Calculate the separation between the order and every\n sep = self.spectrograph.order_spat_pos[:,None] - slit_cen[None,:] - offset\n # Find the smallest offset for each order\n slit_indx = np.ma.MaskedArray(np.ma.argmin(np.absolute(sep), axis=1))\n\n # Minimum separation between the order and its matching slit;\n # keep the signed value for reporting, but used the absolute\n # value of the difference for vetting below.\n sep = sep[(np.arange(self.spectrograph.norders),slit_indx)]\n min_sep = np.absolute(sep)\n\n # Report\n msgs.info('Before vetting, the echelle order, matching left-right trace pair, and '\n 'matching separation are:')\n msgs.info(' {0:>6} {1:>4} {2:>6}'.format('ORDER', 'PAIR', 'SEP'))\n msgs.info(' {0} {1} {2}'.format('-'*6, '-'*4, '-'*6))\n for i in range(self.spectrograph.norders):\n msgs.info(' {0:>6} {1:>4} {2:6.3f}'.format(self.spectrograph.orders[i], i+1, sep[i]))\n msgs.info(' {0} {1} {2}'.format('-'*6, '-'*4, '-'*6))\n\n # Single slit matched to multiple orders\n uniq, cnts = np.unique(slit_indx.compressed(), return_counts=True)\n for u in uniq[cnts > 1]:\n indx = slit_indx == u\n # Keep the one with the smallest separation\n indx[np.argmin(min_sep[indx]) + np.where(indx)[0][1:]] = False\n # Disassociate the other order from any slit\n slit_indx[np.logical_not(indx) & (slit_indx == u)] = np.ma.masked\n\n # Flag and remove orders separated by more than the provided\n # threshold\n if self.par['order_match'] is not None:\n indx = (min_sep > self.par['order_match']) \\\n & np.logical_not(np.ma.getmaskarray(min_sep))\n if np.any(indx):\n # Flag the associated traces\n _indx = np.isin(np.absolute(self.traceid), (slit_indx[indx]).compressed()+1)\n self.edge_msk[:,_indx] = self.bitmask.turn_on(self.edge_msk[:,_indx],\n 'ORDERMISMATCH')\n # Disassociate these orders from any slit\n slit_indx[indx] = np.ma.masked\n\n # Unmatched slits\n indx = np.logical_not(np.isin(np.arange(self.nslits), slit_indx.compressed()))\n if np.any(indx):\n # This works because the traceids are sorted and synced\n indx = np.repeat(indx, 2)\n self.edge_msk[:,indx] = self.bitmask.turn_on(self.edge_msk[:,indx], 'NOORDER')\n\n # Warning that there are missing orders\n missed_order = np.ma.getmaskarray(slit_indx)\n if np.any(missed_order):\n msgs.warn('Did not find all orders! Missing orders: {0}'.format(\n ', '.join(self.spectrograph.orders[missed_order].astype(str))))\n\n # Instantiate the order ID; 0 means the order is unassigned\n self.orderid = np.zeros(self.nslits*2, dtype=int)\n found_orders = self.spectrograph.orders[np.logical_not(missed_order)]\n nfound = len(found_orders)\n indx = (2*slit_indx.compressed()[:,None] + np.tile(np.array([0,1]), (nfound,1))).ravel()\n self.orderid[indx] = (np.array([-1,1])[None,:]*found_orders[:,None]).ravel()", "def calc_order(self, algo, mdata, fdata):\n\n # prepare:\n n_states = fdata.n_states\n n_turbines = algo.n_turbines\n pdata = Data.from_points(points=fdata[FV.TXYH])\n\n # calculate streamline x coordinates for turbines rotor centre points:\n # n_states, n_turbines_source, n_turbines_target\n coosx = np.zeros((n_states, n_turbines, n_turbines), dtype=FC.DTYPE)\n for ti in range(n_turbines):\n coosx[:, ti, :] = self.get_wake_coos(\n algo, mdata, fdata, pdata, np.full(n_states, ti)\n )[..., 0]\n\n # derive turbine order:\n # TODO: Remove loop over states\n order = np.zeros((n_states, n_turbines), dtype=FC.ITYPE)\n for si in range(n_states):\n order[si] = np.lexsort(keys=coosx[si])\n\n return order", "def trio_phase(self, parents=False, callset=None):\n\n for c in self.io[0].snp_chromosomes():\n if c in self.io[1].snp_chromosomes() and c in self.io[2].snp_chromosomes():\n _logger.info(\"Phasing SNP data for chromosome '%s'.\" % c)\n ch, fa, mo = {}, {}, {}\n pos, ref, alt, nref, nalt, gt, flag, qual = self.io[0].read_snp(c, callset=callset)\n for i in range(len(pos)):\n k = str(pos[i])+\":\"+ref[i]+\">\"+alt[i]\n ch[k] = (gt[i] % 4,i)\n pos1, ref1, alt1, nref1, nalt1, gt1, flag1, qual1 = self.io[1].read_snp(c, callset=callset)\n for i in range(len(pos1)):\n k = str(pos1[i])+\":\"+ref1[i]+\">\"+alt1[i]\n fa[k] = (gt1[i] % 4,i)\n pos2, ref2, alt2, nref2, nalt2, gt2, flag2, qual2 = self.io[2].read_snp(c, callset=callset)\n for i in range(len(pos2)):\n k = str(pos2[i])+\":\"+ref2[i]+\">\"+alt2[i]\n mo[k] = (gt2[i] % 4,i)\n\n _logger.info(\"Phasing SNP data for child '%s'.\" % c)\n rpos, rref, ralt, rnref, rnalt, rgt, rflag, rqual = [], [], [], [], [], [], [], []\n for i in range(len(pos)):\n k = str(pos[i])+\":\"+ref[i]+\">\"+alt[i]\n resgt = ch[k][0]\n if ch[k][0]==0 or ch[k][0]==3:\n resgt = ch[k][0] + 4\n else:\n if k in fa and k in mo and fa[k][0]!=0 and mo[k][0]!=0:\n if fa[k][0]==3 and mo[k][0] in [1,2]:\n resgt = 5\n #_logger.debug(\"Phasing 5 (1/1 0/1). SNP: %s:%s\" % (c, k))\n elif mo[k][0]==3 and fa[k][0] in [1,2]:\n resgt = 6\n #_logger.debug(\"Phasing 6 (0/1 1/1). SNP: %s:%s\" % (c, k))\n else:\n _logger.debug(\"Unable to phase. Not unique - skipping. SNP: %s:%s\" % (c,k))\n elif k in fa and fa[k][0]!=0:\n resgt = 5\n #_logger.debug(\"Phasing 5 (?/1 0/0). SNP: %s:%s\" % (c, k))\n elif k in mo and mo[k][0]!=0:\n resgt = 6\n #_logger.debug(\"Phasing 6 (0/0 ?/1). SNP: %s:%s\" % (c, k))\n else:\n _logger.debug(\"Unable to phase. Not present in parents - skipping. SNP: %s:%s\" % (c,k))\n if resgt != -1:\n rpos.append(pos[i])\n rref.append(ref[i])\n ralt.append(alt[i])\n rnref.append(nref[i])\n rnalt.append(nalt[i])\n rgt.append(gt[i])\n rflag.append(flag[i])\n rqual.append(qual[i])\n rgt[-1] = resgt\n _logger.info(\"Writing phased SNP data for child '%s'.\" % c)\n self.io[0].save_snp(c, rpos, rref, ralt, rnref, rnalt, rgt, rflag, rqual, update=True, callset=callset)\n if parents:\n _logger.info(\"Phasing SNP data for parent 1 '%s'.\" % c)\n rpos, rref, ralt, rnref, rnalt, rgt, rflag, rqual = [], [], [], [], [], [], [], []\n for i in range(len(pos1)):\n k = str(pos1[i])+\":\"+ref1[i]+\">\"+alt1[i]\n resgt = fa[k][0]\n if fa[k][0]==0 or fa[k][0]==3:\n resgt = fa[k][0] + 4\n else:\n if k in ch and ch[k][0]!=0 and (k not in mo or mo[k][0]==0):\n resgt = 5\n elif k in ch and ch[k][0]==3:\n resgt = 5\n elif (k not in ch or ch[k][0]==0):\n resgt = 6\n else:\n _logger.debug(\"Unable to phase. Not unique. SNP: %s:%s\" % (c,k))\n if resgt != -1:\n rpos.append(pos1[i])\n rref.append(ref1[i])\n ralt.append(alt1[i])\n rnref.append(nref1[i])\n rnalt.append(nalt1[i])\n rgt.append(gt1[i])\n rflag.append(flag1[i])\n rqual.append(qual1[i])\n rgt[-1] = resgt\n _logger.info(\"Writing phased SNP data for parent 1 '%s'.\" % c)\n self.io[1].save_snp(c, rpos, rref, ralt, rnref, rnalt, rgt, rflag, rqual, update=True,\n callset=callset)\n\n _logger.info(\"Phasing SNP data for parent 2 '%s'.\" % c)\n rpos, rref, ralt, rnref, rnalt, rgt, rflag, rqual = [], [], [], [], [], [], [], []\n for i in range(len(pos2)):\n k = str(pos2[i])+\":\"+ref2[i]+\">\"+alt2[i]\n resgt = mo[k][0]\n if mo[k][0]==0 or mo[k][0]==3:\n resgt = mo[k][0] + 4\n else:\n if k in ch and ch[k][0]!=0 and (k not in fa or fa[k][0]==0):\n resgt = 6\n elif k in ch and ch[k][0]==3:\n resgt = 6\n elif (k not in ch or ch[k][0]==0):\n resgt = 5\n else:\n _logger.debug(\"Unable to phase. Not unique. SNP: %s:%s\" % (c,k))\n if resgt != -1:\n rpos.append(pos2[i])\n rref.append(ref2[i])\n ralt.append(alt2[i])\n rnref.append(nref2[i])\n rnalt.append(nalt2[i])\n rgt.append(gt2[i])\n rflag.append(flag2[i])\n rqual.append(qual2[i])\n rgt[-1] = resgt\n\n _logger.info(\"Writing phased SNP data for parent 2 '%s'.\" % c)\n self.io[2].save_snp(c, rpos, rref, ralt, rnref, rnalt, rgt, rflag, rqual, update=True,\n callset=callset)\n else:\n _logger.info(\"Chromosome '%s' not present in parents data.\" % c)", "def postOrderTrav(self):\n for child in self.children:\n if child.children:\n child.postOrderTrav()\n else:\n pass\n #This might be a place where different work paths can be broken down\n #print(\"---Path---\")\n print(child.instruction)", "def init_db_trace_directions():\n\n # TODO: potentially rewrite according to new dao API\n # for db_nodes in conf.cluster[\"public_ips\"]:\n #node_ids = [x[\"id\"] for x in conf.cluster[\"public_ips\"]]\n # Khalid Update: replace the above expression with new one\n node_ids = [x.id for x in dm.ndm.getAll() ]\n\n required_td_pairs = \\\n [p for p in [x for x in itertools.product(node_ids, node_ids) ] if p[0] != p[1]]\n\n print required_td_pairs\n existing = [ (x[1],x[2]) for x in rdm.getTraceDirections()]\n print existing\n\n for r in required_td_pairs:\n if r not in existing:\n\n td_id = rdm.insertTraceDirection(r[0], r[1])\n # rdm.insertPath(td_id, [ r[0], r[1] ] )\n\n\n\n # for src_node_id, dst_node_id in required_td_pairs:\n\n\n # print \"PAIR\", src_node_id, dst_node_id\n # td = dm.getTraceDirectionByIps(\n # dm.getEndNodeById(src_node_id)[\"ip\"],\n # dm.getEndNodeById(dst_node_id)[\"ip\"])\n\n # if not td:\n # log.warning(\"[DB] Insertin TraceDirection [%s->%s]\",\n # src_node_id, dst_node_id)\n # rdm.insertTraceDirection(src_node_id, dst_node_id)\n\n # # TODO: remove when we going to update run time state\n # dm._initTraceDirections()", "def topo_sort(self):", "def output_shp_segmented(self):\n ofn = \"{}_{}_tracks_segmented\".format(\n self.year,\n \"ATL\" if list(self.tc.keys())[0][:2] == \"AL\" else \"PAC\"\n )\n c = itertools.count(0)\n with shapefile.Writer(ofn,shapeType=3) as gis:\n gis.field(\"ID\",\"N\",\"3\")\n gis.field(\"ATCFID\",\"C\",\"8\")\n gis.field(\"ENTRY_INDEX\",\"N\")\n gis.field(\"NAME\",\"C\",\"10\")\n gis.field(\"ENTRY_TIME\",\"C\",\"16\")\n gis.field(\"NEXT_ENTRY_TIME\",\"C\",\"16\")\n gis.field(\"LAT\",\"N\",decimal=1)\n gis.field(\"LON\",\"N\",decimal=1)\n gis.field(\"NEXT_ENTRY_LAT\",\"N\",decimal=1)\n gis.field(\"NEXT_ENTRY_LON\",\"N\",decimal=1)\n gis.field(\"STATUS\",\"C\",\"3\")\n gis.field(\"PEAK_WIND\",\"N\",\"3\")\n gis.field(\"MIN_MSLP\",\"N\",\"4\")\n for TC in [t[1] for t in self.tc.items()]:\n for track in range(len(TC.entry)):\n gis.record(\n next(c),\n TC.atcfid,\n track,\n TC.name,\n TC.entry[track].entrytime.isoformat(),\n TC.entry[track+1].entrytime.isoformat() if track != len(TC.entry)-1 else None,\n TC.entry[track].location[0],\n TC.entry[track].location[1],\n TC.entry[track+1].location[0] if track != len(TC.entry)-1 else None,\n TC.entry[track+1].location[1] if track != len(TC.entry)-1 else None,\n TC.entry[track].status,\n TC.entry[track].wind if TC.entry[track].wind > 0 else \"\",\n TC.entry[track].mslp if TC.entry[track].mslp != None else \"\"\n )\n if track != len(TC.entry)-1:\n gis.line([[TC.entry[track].location_reversed,TC.entry[track+1].location_reversed]])\n else:\n gis.null()", "def postflight(self):\n taggraph_header = [\n \"ScanF\",\n \"Charge\",\n \"Retention Time\",\n \"Obs M+H\",\n \"Theo M+H\",\n \"PPM\",\n \"EM Probability\",\n \"1-lg10 EM\",\n \"Spectrum Score\",\n \"Alignment Score\",\n \"Composite Score\",\n \"Unique Siblings\",\n \"Context Mod Variants\",\n \"Num Mod Occurrences\",\n \"Context\",\n # 'Mod Context',\n \"Mods\",\n \"Mod Ambig Edges\",\n \"Mod Ranges\",\n \"Proteins\",\n \"De Novo Peptide\",\n \"De Novo Score\",\n \"Matching Tag Length\",\n \"Num Matches\",\n ]\n\n translated_headers = []\n header_translations = self.UNODE_UPARAMS[\"header_translations\"][\n \"uvalue_style_translation\"\n ]\n for original_header_key in taggraph_header:\n ursgal_header_key = header_translations[original_header_key]\n translated_headers.append(ursgal_header_key)\n translated_headers += [\n \"Spectrum Title\",\n \"Raw data location\",\n \"Calc m/z\",\n ]\n\n taggrapg_output_tdv = os.path.join(\n self.tag_graph_tmp_dir,\n \"EM_output\",\n # '{0}_TopResults.tdv'.format(\n # self.params['output_file'].replace('.csv', '')\n # )\n \"{0}_TopResults.txt\".format(self.params[\"output_file\"].replace(\".csv\", \"\")),\n )\n\n csv_out_fobject = open(\n self.params[\"translations\"][\"output_file_incl_path\"], \"w\"\n )\n csv_writer = csv.DictWriter(csv_out_fobject, fieldnames=translated_headers)\n csv_writer.writeheader()\n\n with open(taggrapg_output_tdv, \"r\") as temp_tsv:\n csv_reader = csv.DictReader(temp_tsv, delimiter=\"\\t\")\n for line_dict in csv_reader:\n out_line_dict = {}\n\n ############################################\n # all fixing here has to go into unify csv! #\n ############################################\n\n for column in taggraph_header:\n if column == \"ScanF\":\n out_line_dict[header_translations[column]] = line_dict[\n column\n ].split(\":\")[1]\n elif column == \"Context\":\n out_line_dict[header_translations[column]] = line_dict[\n column\n ].split(\".\")[1]\n else:\n out_line_dict[header_translations[column]] = line_dict[column]\n out_line_dict[\"Raw data location\"] = os.path.abspath(\n os.path.join(\n os.path.dirname(\n self.params[\"translations\"][\"mzml_input_file\"][0]\n ),\n line_dict[\"ScanF\"].split(\":\")[0] + \".mzML\",\n )\n )\n csv_writer.writerow(out_line_dict)\n\n csv_out_fobject.close()\n return", "def get_tmtikz(self,band):\n tmframe='\\\\begin{frame}[fragile]{CoMa Turingmaschine} \\n \\\n\\n \\\n\\\\begin{itemize} \\n \\\n\\item Eingabealphabet : '\n tmframe=tmframe+str(self.einalpha) \n tmframe=tmframe+' \\n \\\n\\item Bandalphabet : '\n tmframe=tmframe+str(self.bandalpha)\n tmframe=tmframe+' \\n \\\n\\item Leerzeichen : '\n tmframe=tmframe+self.leerzeichen\n tmframe=tmframe+' \\n \\\n\\item anzahl an Zustaenden : '\n tmframe=tmframe+str(self.nozust)\n tmframe=tmframe+' \\n \\\n\\item akzept. Zustaende : '\n tmframe=tmframe+str(self.akztzust)\n tmframe=tmframe+'\\n \\\n\\end{itemize} \\n \\\n\\\\begin{figure} \\n \\\n\\\\begin{tikzpicture} \\n \\\n\\n \\\n\\edef\\sizetape{0.7cm} \\n \\\n\\\\tikzstyle{tmtape}=[draw,minimum size=\\sizetape] \\n \\\n\\n \\\n%% Draw TM tape \\n \\\n\\\\begin{scope}[start chain=1 going right,node distance=-0.15mm] \\n \\\n\\\\node [on chain=1,tmtape,draw=none] {$\\\\ldots$}; \\n \\\n'\n tmframe=tmframe+band\n tmframe=tmframe+' \\n \\\n\\\\node [on chain=1,tmtape,draw=none] {$\\ldots$}; \\n \\\n\\end{scope} \\n \\\n\\end{tikzpicture} \\n \\\n\\\\begin{tikzpicture} \\n \\\n\\\\node [draw,align=left]{akt. Zustand}; \\n \\\n\\\\begin{scope}[start chain=2 going right] \\n \\\n\\\\node [draw,left=3cm,arrow box,name=p,on chain=2,arrow box arrows={north:.5cm},minimum size=0.5cm] {}; \\n \\\n\\draw[on chain=2]{}; \\n \\\n\\\\node [draw, name=q,left=0cm,on chain=2]{'\n tmframe=tmframe+self.kopf_q\n tmframe=tmframe+'}; \\n \\\n\\draw [<-] (p) -- (q); \\n \\\n\\chainin (q) [join]; \\n \\\n\\end{scope} \\n \\\n\\end{tikzpicture} \\n \\\n\\end{figure} \t\\n \\\n\\end{frame} \\n'\n return tmframe", "def test_getSCPosTRP(): \n ff = martini22()\n scs= ff.sidechains['TRP'][1]\n Top = Topology()\n scpos = Top.getSCPos(scs,np.array([0.,0.,0.]),4)\n npt.assert_array_almost_equal(scpos,np.array([[0.,0.,0.3],\n [0.,0.135,0.27*np.sqrt(3)/2+0.3],\n [0.,-0.135,0.27*np.sqrt(3)/2+0.3],\n [0.,0.,0.27*np.sqrt(3)+0.3]]))", "def order_parts(self):\n product_ids = []\n for line in self.operations:\n product_ids.append(line.product_id.id)\n for line in self.fees_lines:\n product_ids.append(line.product_id.id)\n return {\n 'name': ('Repair Order Products'),\n 'view_mode': 'tree,form',\n 'res_model': 'product.product',\n 'view_id': False,\n 'type': 'ir.actions.act_window',\n 'domain': [('id', 'in', product_ids)]\n }", "def redefine_order(self):\n\n # If we are doing a torsion_test we have to redo the order as follows:\n # 1 Skip the finalise step to create a pickled ligand at the torsion_test stage\n # 2 Do the torsion_test and delete the torsion_test attribute\n # 3 Do finalise again to save the ligand with the correct attributes\n if getattr(self.molecule, \"torsion_test\", None) not in [None, False]:\n self.order = OrderedDict(\n [\n (\"finalise\", self.skip),\n (\"torsion_test\", self.torsion_test),\n (\"finalise\", self.skip),\n ]\n )\n\n else:\n start = (\n self.molecule.restart\n if self.molecule.restart is not None\n else \"parametrise\"\n )\n end = self.molecule.end if self.molecule.end is not None else \"finalise\"\n skip = self.molecule.skip if self.molecule.skip is not None else []\n\n # Create list of all keys\n stages = list(self.order)\n\n # Cut out the keys before the start_point and after the end_point\n # Add finalise back in if it's removed (finalise should always be called).\n stages = stages[stages.index(start) : stages.index(end) + 1] + [\"finalise\"]\n\n # Redefine self.order to only contain the key, val pairs from stages\n self.order = OrderedDict(\n pair for pair in self.order.items() if pair[0] in set(stages)\n )\n\n for pair in self.order.items():\n self.order[pair[0]] = self.skip if pair[0] in skip else pair[1]", "def traces(self):\r\n\t\treturn [b'TR'+i for i in b'ABCDEF' if self.query(b'DISP:TRAC:STAT? TR'+i)]", "def PDBline(self, ser_num, trad={}, fixedAtom=False):\n\t\t#print \"PDBline \", self\n\t\ttObj = self.getInfo()\n\t\tif fixedAtom:\n\t\t\t#return \"%s%5i %-4s%c%3s %c%4i%c %8.3f%8.3f%8.3f%6.2f%6.2f %2s%1.4f\" % (\"ATOM \",ser_num,self._name,' ',self._residue,self._chain,1,' ',self._coordinates[0],self._coordinates[1],self._coordinates[2],1 ,0.0,self._element,self._charge)\n\t\t\treturn \"%s%5i %-4s%c%3s %c%4i%c %8.3f%8.3f%8.3f%6.2f%6.2f %2s\" % (\"ATOM \",ser_num%100000,tObj._name,' ',tObj._residue,tObj._chain,1,' ',self.getCoord()[0],self.getCoord()[1],self.getCoord()[2],1 ,0.0,tObj._element)\n\t\telse:\n\t\t\t#return \"%s%5i %-4s%c%3s %c%4i%c %8.3f%8.3f%8.3f%6.2f%6.2f %2s%1.4f\" % (\"ATOM \",ser_num,self._name,' ',self._residue,self._chain,1,' ',self._coordinates[0],self._coordinates[1],self._coordinates[2],0,0.0,self._element,self._charge)\n\t\t\treturn \"%s%5i %-4s%c%3s %c%4i%c %8.3f%8.3f%8.3f%6.2f%6.2f %2s\" % (\"ATOM \",ser_num%100000,tObj._name,' ',tObj._residue,tObj._chain,1,' ',self.getCoord()[0],self.getCoord()[1],self.getCoord()[2],0,0.0,tObj._element)", "def segs2trunks(segmentFrame,referenceFrame, custRefs, logFileName, error = False):\r\n for j in range(2): #1 = base loop; 2 = top loop\r\n for i in range(len(segmentFrame.index)): #i = all row indices\r\n if j == 0: #set this variable to determine if we calculate reference coordinates for base or top of segment\r\n string = 'base'\r\n else:\r\n string = 'top'\r\n \r\n #get name of base or top ref depending on value of \"j\"\r\n refName = str(segmentFrame['{0} ref'.format(string)].iloc[i])\r\n refName = refName.replace(\" \",\"\")\r\n refHt = segmentFrame['{0} z'.format(string)].iloc[i]\r\n \r\n if string == 'base':\r\n dashes = segmentFrame['name'].iloc[i].count('-') #More than two dashes in the base name means this is a mid-segment segment \r\n else:\r\n dashes = 1 #if it is the top of a segment is shouldn't matter so long as the reference if correct \r\n\r\n if dashes >2 and refName.isalpha():\r\n f.print2Log(logFileName, \"Careful there buddy: the reference for mid-segment {0} is {1} and should probably be the segment base\".format(segmentFrame['name'].iloc[i],refName))\r\n \r\n #This operates on rows with a letter ref that does not equal 'calc', is not a mid-segment segment, that does not have @ notation and that is not in cust refs\r\n if len(custRefs)>0: #Are there cust refs to test against?\r\n test = (refName.isalpha() and refName.lower() != 'calc' and dashes < 2 and not any(custRefs['name'].isin([refName]))) or (refName.count('@') > 0)\r\n else:\r\n test = (refName.isalpha() and refName.lower() != 'calc' and dashes < 2) or (refName.count('@') > 0)\r\n if test:\r\n #if refname uses the @ notation\r\n if refName.count('@') > 0:\r\n rn = refName\r\n refName = rn.split('@')[0]\r\n refHt = float(rn.split('@')[1]) \r\n #if refName is 'Mtop' then refHt is highest top in main trunks \r\n elif ('M' in refName and 'top' in refName):\r\n tempFrame = referenceFrame['M']\r\n refHt = round(float(tempFrame['top z'].max()),2)\r\n refName = 'M'\r\n elif isinstance(refHt,np.float64) or isinstance(refHt, np.int64): #convert numpy.floats to native floats, not sure why but several heights are imported as numpy.float not float\r\n refHt = refHt.item()\r\n \r\n if type(refHt) != float and type(refHt) != int:\r\n print(\"Check the {0} reference height for segment {1}, it is not a number.\".format(string,segmentFrame['name'].iloc[i]))\r\n f.print2Log(logFileName,\"Check the {0} reference height for segment {1}, it is not a number.\".format(string,segmentFrame['name'].iloc[i]))\r\n error = True\r\n\r\n if all([refName != key for key in referenceFrame]):\r\n print('The refName \"{0}\" for the {1} of segment \"{2}\" does not match any of the trunk names'.format(refName, string, segmentFrame.loc[i,'name']))\r\n f.print2Log(logFileName, 'The refName \"{0}\" for the {1} of segment \"{2}\" does not match any of the trunk names'.format(refName, string, segmentFrame.loc[i,'name']))\r\n \r\n #Call appropriate rows from mainT or segment data from the reference data.frame provided \r\n tRows = referenceFrame['{0}'.format(refName)]\r\n x=refHt >= tRows['base z']\r\n y=refHt <= tRows['top z']\r\n interpRow = tRows[[a and b for a, b in zip(x, y)]][:1] #intersection of boolean vectors is correct index\r\n \r\n #Interp x,y,r\r\n if interpRow.empty:\r\n print(\"There are no main trunk sections surrounding the {0} height of the segment: {1}\".format(string,segmentFrame['name'].iloc[i]))\r\n f.print2Log(logFileName, \"There are no main trunk sections surrounding the {0} height of the segment: {1}, if referencing the main below this segment use M@height for the ref\\n\".format(string,segmentFrame['name'].iloc[i]))\r\n error = True\r\n \r\n else:\r\n interpVals = f.linearInterp(interpRow,refHt) #dictionary of interpolated values under 'ref_X','ref_Y', and 'ref_R'\r\n \r\n if interpVals['errors']:\r\n f.print2Log(logFileName, \"Target height of {0} of segment {1} is not between reference heights\".format(string, segmentFrame['name'].iloc[i]))\r\n error = True\r\n #Copy x,y,r to sement row\r\n segmentFrame.at[i,'{0} ref x'.format(string)] = interpVals['ref_X'].iloc[0]\r\n segmentFrame.at[i,'{0} ref y'.format(string)] = interpVals['ref_Y'].iloc[0]\r\n segmentFrame.at[i,'{0} ref radius'.format(string)] = interpVals['ref_R'].iloc[0] \r\n \r\n #Calculate positional information for this row and column as well. \r\n refVals = [interpVals['ref_X'].iloc[0],interpVals['ref_Y'].iloc[0], interpVals['ref_R'].iloc[0]]\r\n positionMeasures = [segmentFrame['{0} dist'.format(string)].iloc[i],segmentFrame['{0} azi'.format(string)].iloc[i],\r\n segmentFrame['{0} radius'.format(string)].iloc[i],segmentFrame['{0} ref type'.format(string)].iloc[i]]\r\n \r\n calcs = f.calcPosition(refVals, positionMeasures,calcType = 'segment')\r\n \r\n segmentFrame.at[i,'{0} x'.format(string)] = calcs['x']\r\n segmentFrame.at[i,'{0} y'.format(string)] = calcs['y']\r\n #pdb.set_trace()\r\n if calcs['error'] == True:\r\n f.print2Log(logFileName,'Segment {0} reference assumed to be face to pith (reference to target)'.format(segmentFrame['name'].iloc[i]))\r\n error = calcs['error']\r\n \r\n f.closingStatement(logFileName, error)\r\n \r\n return (segmentFrame)", "def dartsFromMDTraj(self, system, file_list, topology=None, residueList=None, basis_particles=None):\n if residueList == None:\n residueList = self.residueList\n if basis_particles == None:\n basis_particles = self.basis_particles\n n_dartboard = []\n dartboard = []\n for md_file in file_list:\n if topology == None:\n temp_md = md.load(md_file)\n else:\n temp_md = md.load(md_file, top=topology)\n context_pos = temp_md.openmm_positions(0)\n print('context_pos', context_pos, 'context_pos')\n print('context_pos type', type(context_pos._value))\n print('temp_md', temp_md)\n context_pos = np.asarray(context_pos._value) * unit.nanometers\n total_mass, mass_list = self.get_particle_masses(system, set_self=False, residueList=residueList)\n com = self.calculate_com(\n pos_state=context_pos, total_mass=total_mass, mass_list=mass_list, residueList=residueList)\n #get particle positions\n particle_pos = []\n for particle in basis_particles:\n print('particle %i position' % (particle), context_pos[particle])\n particle_pos.append(context_pos[particle])\n new_coord = findNewCoord(particle_pos[0], particle_pos[1], particle_pos[2], com)\n #keep this in for now to check code is correct\n #old_coord should be equal to com\n old_coord = findOldCoord(particle_pos[0], particle_pos[1], particle_pos[2], new_coord)\n n_dartboard.append(new_coord)\n dartboard.append(old_coord)\n print('n_dartboard from pdb', n_dartboard)\n print('dartboard from pdb', dartboard)\n\n self.n_dartboard = n_dartboard\n self.dartboard = dartboard", "def get_obspy_trace(self, network, station, evnumb, datatype='body'):\n event = self.events[evnumb-1]\n tag=datatype+'_ev_%05d' %evnumb\n st=self.waveforms[network+'.'+station][tag]\n stla, elev, stlo=self.waveforms[network+'.'+station].coordinates.values()\n evlo=event.origins[0].longitude; evla=event.origins[0].latitude; evdp=event.origins[0].depth\n for tr in st:\n tr.stats.sac=obspy.core.util.attribdict.AttribDict()\n tr.stats.sac['evlo']=evlo; tr.stats.sac['evla']=evla; tr.stats.sac['evdp']=evdp\n tr.stats.sac['stlo']=stlo; tr.stats.sac['stla']=stla \n return st", "def ech_fill_in_orders(sobjs:specobjs.SpecObjs, \n slit_left:np.ndarray, \n slit_righ:np.ndarray, \n order_vec:np.ndarray,\n order_gpm:np.ndarray,\n obj_id:np.ndarray,\n slit_spat_id:np.ndarray,\n std_trace:specobjs.SpecObjs=None,\n show:bool=False):\n # Prep\n nfound = len(sobjs)\n uni_obj_id, uni_ind = np.unique(obj_id, return_index=True)\n nobj = len(uni_obj_id)\n fracpos = sobjs.SPAT_FRACPOS\n\n # Prep\n ngd_orders = np.sum(order_gpm)\n gd_orders = order_vec[order_gpm]\n slit_width = slit_righ - slit_left\n\n # Check standard star\n if std_trace is not None and std_trace.shape[1] != ngd_orders:\n msgs.error('Standard star trace does not match the number of orders in the echelle data.')\n\n # For traces\n nspec = slit_left.shape[0]\n spec_vec = np.arange(nspec)\n slit_spec_pos = nspec/2.0\n specmid = nspec // 2\n\n gfrac = np.zeros(nfound)\n for jj in range(nobj):\n this_obj_id = obj_id == uni_obj_id[jj]\n gfrac[this_obj_id] = np.median(fracpos[this_obj_id])\n\n uni_frac = gfrac[uni_ind]\n\n # Sort with respect to fractional slit location to guarantee that we have a similarly sorted list of objects later\n isort_frac = uni_frac.argsort()\n uni_obj_id = uni_obj_id[isort_frac]\n uni_frac = uni_frac[isort_frac]\n\n sobjs_align = sobjs.copy()\n # Loop over the orders and assign each specobj a fractional position and a obj_id number\n for iobj in range(nobj):\n #for iord in range(norders):\n for iord in order_vec[order_gpm]:\n on_order = (obj_id == uni_obj_id[iobj]) & (sobjs_align.ECH_ORDER == iord)\n sobjs_align[on_order].ECH_FRACPOS = uni_frac[iobj]\n sobjs_align[on_order].ECH_OBJID = uni_obj_id[iobj]\n sobjs_align[on_order].OBJID = uni_obj_id[iobj]\n sobjs_align[on_order].ech_frac_was_fit = False\n\n # Reset names (just in case)\n sobjs_align.set_names()\n # Now loop over objects and fill in the missing objects and their traces. We will fit the fraction slit position of\n # the good orders where an object was found and use that fit to predict the fractional slit position on the bad orders\n # where no object was found\n for iobj in range(nobj):\n # Grab all the members of this obj_id from the object list\n indx_obj_id = sobjs_align.ECH_OBJID == uni_obj_id[iobj]\n nthisobj_id = np.sum(indx_obj_id)\n # Perform the fit if this objects shows up on more than three orders\n if (nthisobj_id > 3) and (nthisobj_id<ngd_orders):\n thisorderindx = sobjs_align[indx_obj_id].ECH_ORDERINDX\n thisorder = sobjs_align[indx_obj_id].ECH_ORDER\n # Allow for masked orders\n xcen_good = (sobjs_align[indx_obj_id].TRACE_SPAT).T\n slit_frac_good = (xcen_good-slit_left[:,thisorderindx])/slit_width[:,thisorderindx]\n # Fractional slit position averaged across the spectral direction for each order\n frac_mean_good = np.mean(slit_frac_good, 0)\n # Perform a linear fit to fractional slit position\n #TODO Do this as a S/N weighted fit similar to what is now in the pca_trace algorithm?\n #msk_frac, poly_coeff_frac = fitting.robust_fit(order_vec[goodorder], frac_mean_good, 1,\n pypeitFit = fitting.robust_fit(\n #order_vec[goodorder], frac_mean_good, 1,\n thisorder, frac_mean_good, 1,\n function='polynomial', maxiter=20, lower=2, upper=2,\n use_mad= True, sticky=False,\n minx = order_vec.min(), maxx=order_vec.max())\n # Fill\n goodorder = np.in1d(gd_orders, thisorder)\n badorder = np.invert(goodorder)\n frac_mean_new = np.zeros(gd_orders.size)\n frac_mean_new[badorder] = pypeitFit.eval(gd_orders[badorder])\n frac_mean_new[goodorder] = frac_mean_good\n # TODO This QA needs some work\n if show:\n frac_mean_fit = pypeitFit.eval(gd_orders)\n plt.plot(gd_orders[goodorder][pypeitFit.bool_gpm], frac_mean_new[goodorder][pypeitFit.bool_gpm], 'ko', mfc='k', markersize=8.0, label='Good Orders Kept')\n plt.plot(gd_orders[goodorder][np.invert(pypeitFit.bool_gpm)], frac_mean_new[goodorder][np.invert(pypeitFit.bool_gpm)], 'ro', mfc='k', markersize=8.0, label='Good Orders Rejected')\n plt.plot(gd_orders[badorder], frac_mean_new[badorder], 'ko', mfc='None', markersize=8.0, label='Predicted Bad Orders')\n plt.plot(gd_orders,frac_mean_new,'+',color='cyan',markersize=12.0,label='Final Order Fraction')\n plt.plot(gd_orders, frac_mean_fit, 'r-', label='Fractional Order Position Fit')\n plt.xlabel('Order Index', fontsize=14)\n plt.ylabel('Fractional Slit Position', fontsize=14)\n plt.title('Fractional Slit Position Fit')\n plt.legend()\n plt.show()\n else:\n frac_mean_new = np.full(gd_orders.size, uni_frac[iobj])\n\n\n # Now loop over the orders and add objects on the orders for \n # which the current object was not found\n for iord in range(order_vec.size):\n iorder = order_vec[iord]\n if iorder not in gd_orders:\n continue\n # Is the current object detected on this order?\n on_order = (sobjs_align.ECH_OBJID == uni_obj_id[iobj]) & (\n sobjs_align.ECH_ORDER == iorder)\n num_on_order = np.sum(on_order)\n if num_on_order == 0:\n msgs.info(f\"Adding object={uni_obj_id[iobj]} to order={iorder}\")\n # If it is not, create a new sobjs and add to sobjs_align and assign required tags\n thisobj = specobj.SpecObj('Echelle', sobjs_align[0].DET,\n OBJTYPE=sobjs_align[0].OBJTYPE,\n ECH_ORDERINDX=iord,\n ECH_ORDER=iorder)\n #thisobj.ECH_ORDERINDX = iord\n #thisobj.ech_order = order_vec[iord]\n thisobj.SPAT_FRACPOS = uni_frac[iobj]\n # Assign traces using the fractional position fit above\n if std_trace is not None:\n x_trace = np.interp(slit_spec_pos, spec_vec, std_trace[:,iord])\n shift = np.interp(\n slit_spec_pos, spec_vec, slit_left[:,iord] + \n slit_width[:,iord]*frac_mean_new[iord]) - x_trace\n thisobj.TRACE_SPAT = std_trace[:,iord] + shift\n else:\n thisobj.TRACE_SPAT = slit_left[:, iord] + slit_width[:, iord] * frac_mean_new[iord] # new trace\n thisobj.trace_spec = spec_vec\n thisobj.SPAT_PIXPOS = thisobj.TRACE_SPAT[specmid]\n # Use the real detections of this objects for the FWHM\n this_obj_id = obj_id == uni_obj_id[iobj]\n # Assign to the fwhm of the nearest detected order\n imin = np.argmin(np.abs(sobjs_align[this_obj_id].ECH_ORDERINDX - iord))\n thisobj.FWHM = sobjs_align[imin].FWHM\n thisobj.hand_extract_flag = sobjs_align[imin].hand_extract_flag\n thisobj.maskwidth = sobjs_align[imin].maskwidth\n thisobj.smash_peakflux = sobjs_align[imin].smash_peakflux\n thisobj.smash_snr = sobjs_align[imin].smash_snr\n thisobj.BOX_RADIUS = sobjs_align[imin].BOX_RADIUS\n thisobj.ECH_FRACPOS = uni_frac[iobj]\n thisobj.ECH_OBJID = uni_obj_id[iobj]\n thisobj.OBJID = uni_obj_id[iobj]\n thisobj.SLITID = slit_spat_id[iord]\n thisobj.ech_frac_was_fit = True\n thisobj.set_name()\n sobjs_align.add_sobj(thisobj)\n obj_id = np.append(obj_id, uni_obj_id[iobj])\n gfrac = np.append(gfrac, uni_frac[iobj])\n elif num_on_order == 1:\n # Object is already on this order so no need to do anything\n pass\n elif num_on_order > 1:\n msgs.error('Problem in echelle object finding. The same objid={:d} appears {:d} times on echelle orderindx ={:d}'\n ' even after duplicate obj_ids the orders were removed. '\n 'Report this bug to PypeIt developers'.format(uni_obj_id[iobj],num_on_order, iord)) \n # Return\n return sobjs_align" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
method to remove faulty short skeleton branches.
def prune_skeleton(skel, skel_ep, prune_length=0.15): pruned_skel = np.copy(skel) prune_indices = np.transpose(np.nonzero(skel)).tolist() # Set pruning length length_of_trace = len(prune_indices) max_branch_length = int(length_of_trace * prune_length) # short branch limit # Identify all end points of all branches branch_ends = np.transpose(np.nonzero(skel_ep)).tolist() # Check for branch - and if it is delete it for x_b, y_b in branch_ends: branch_coordinates = [[x_b,y_b]] branch_continues = True temp_coordinates = prune_indices[:] temp_coordinates.pop(temp_coordinates.index([x_b,y_b])) # remove end point while branch_continues: tree = cKDTree(temp_coordinates) query_point = [x_b, y_b] no_of_neighbours = len(tree.query_ball_point(query_point, r=1.5)) # If branch continues if no_of_neighbours == 1: _, ind = tree.query([x_b, y_b], distance_upper_bound=1.5) x_b, y_b = tree.data[ind].astype(int) # move one pixel branch_coordinates.append([x_b,y_b]) temp_coordinates.pop(temp_coordinates.index([x_b,y_b])) # If the branch reaches the edge of the main trace elif no_of_neighbours > 1: branch_coordinates.pop(branch_coordinates.index([x_b,y_b])) branch_continues = False is_branch = True # Weird case that happens sometimes elif no_of_neighbours == 0: is_branch = True branch_continues = False if len(branch_coordinates) > max_branch_length: branch_continues = False is_branch = False if is_branch: for x, y in branch_coordinates: pruned_skel[x,y] = False return pruned_skel
[ "def prune_branches(skeleton):\n for he in skeleton.half_edges.values():\n assert he.face.id is not None, he.id\n assert he.twin.face.id is not None, he.id\n # remove edges that have the same face on both sides\n remove = set()\n for he in skeleton.half_edges.values():\n if he.face is he.twin.face:\n remove.add(he.id)\n for edge_id in remove:\n skeleton.remove_edge(edge_id, remove_nodes=True)", "def prune(skeleton, name, pruned_dir, save_img):\n \n # print(\"\\nPruning {}...\\n\".format(name))\n \n # identify 3-way branch-points\n hit1 = np.array([[0, 1, 0],\n [0, 1, 0],\n [1, 0, 1]], dtype=np.uint8)\n hit2 = np.array([[1, 0, 0],\n [0, 1, 0],\n [1, 0, 1]], dtype=np.uint8)\n hit3 = np.array([[1, 0, 0],\n [0, 1, 1],\n [0, 1, 0]], dtype=np.uint8)\n hit_list = [hit1, hit2, hit3]\n \n # numpy slicing to create 3 remaining rotations\n for ii in range(9):\n hit_list.append(np.transpose(hit_list[-3])[::-1, ...])\n \n # add structure elements for branch-points four 4-way branchpoints\n hit3 = np.array([[0, 1, 0],\n [1, 1, 1],\n [0, 1, 0]], dtype=np.uint8)\n hit4 = np.array([[1, 0, 1],\n [0, 1, 0],\n [1, 0, 1]], dtype=np.uint8)\n hit_list.append(hit3)\n hit_list.append(hit4)\n # print(\"Creating hit and miss list\")\n \n skel_image = check_bin(skeleton)\n # print(\"Converting image to binary array\")\n \n branch_points = np.zeros(skel_image.shape)\n # print(\"Creating empty array for branch points\")\n \n for hit in hit_list:\n target = hit.sum()\n curr = ndimage.convolve(skel_image, hit, mode=\"constant\")\n branch_points = np.logical_or(branch_points, np.where(curr == target, 1, 0))\n \n # print(\"Completed collection of branch points\")\n \n # pixels may \"hit\" multiple structure elements, ensure the output is a binary image\n branch_points_image = np.where(branch_points, 1, 0)\n # print(\"Ensuring binary\")\n \n # use SciPy's ndimage module for locating and determining coordinates of each branch-point\n labels, num_labels = ndimage.label(branch_points_image)\n # print(\"Labelling branches\")\n \n # use SciPy's ndimage module to determine the coordinates/pixel corresponding to the center of mass of each\n # branchpoint\n branch_points = ndimage.center_of_mass(skel_image, labels=labels, index=range(1, num_labels + 1))\n branch_points = np.array([value for value in branch_points if not np.isnan(value[0]) or not np.isnan(value[1])],\n dtype=int)\n # num_branch_points = len(branch_points)\n \n hit = np.array([[0, 0, 0],\n [0, 1, 0],\n [0, 0, 0]], dtype=np.uint8)\n \n dilated_branches = ndimage.convolve(branch_points_image, hit, mode='constant')\n dilated_branches_image = np.where(dilated_branches, 1, 0)\n # print(\"Ensuring binary dilated branches\")\n pruned_image = np.subtract(skel_image, dilated_branches_image)\n # pruned_image = np.subtract(skel_image, branch_points_image)\n \n pruned_image = remove_particles(pruned_image, pruned_dir, name, minpixel=5, prune=True, save_img=save_img)\n\n return pruned_image", "def skeleton_image(folder, image_file, threshold=50, area_thresh=50, figsize=(10, 10), show=False):\n # Median filtered image.\n fname = '{}/{}'.format(folder, image_file)\n image0 = sio.imread(fname)\n image0 = np.ceil(255* (image0[:, :, 1] / image0[:, :, 1].max())).astype(int)\n image0 = skimage.filters.median(image0)\n filt = 'filt_{}.png'.format(image_file.split('.')[0])\n sio.imsave(folder+'/'+filt, image0)\n\n #threshold the image\n binary0 = binary_image(folder, filt, threshold=threshold, close=True, show=False)\n clean = 'clean_{}'.format(filt)\n\n #label image\n short_image, props = label_image(folder, clean, area_thresh=area_thresh, show=False)\n short = 'short_{}'.format(clean)\n short_image = short_image > 1\n # Skeletonize\n skeleton0 = skeletonize(short_image)\n\n branch_data = csr.summarise(skeleton0)\n branch_data_short = branch_data\n\n #Remove small branches\n mglia = branch_data['skeleton-id'].max()\n nbranches = []\n\n ncount = 0\n for i in range(1, mglia+1):\n bcount = branch_data[branch_data['skeleton-id']==i]['skeleton-id'].count()\n if bcount > 0:\n ids = branch_data.index[branch_data['skeleton-id']==i].tolist()\n nbranches.append(bcount)\n for j in range(0, len(ids)):\n branch_data_short.drop([ids[j]])\n\n ncount = ncount + 1\n if show:\n fig, ax = plt.subplots(figsize=(10, 10))\n draw.overlay_euclidean_skeleton_2d(image0, branch_data_short,\n skeleton_color_source='branch-type', axes=ax)\n plt.savefig('{}/skel_{}'.format(folder, short))\n\n return skeleton0, branch_data_short, nbranches, short_image, props", "def prune(self):\n self.branches = [b for b in self.branches if not self.contr(b)]", "def __cut_short_skeleton_terminal_edges(self, cut_ratio=2.0):\n\n def remove_elm(elm_id, elm_neigh, elm_box, sklabel):\n sklabel[sklabel == elm_id] = 0\n del elm_neigh[elm_id]\n del elm_box[elm_id]\n for elm in elm_neigh:\n elm_neigh[elm] = [x for x in elm_neigh[elm] if x != elm]\n return elm_neigh, elm_box, sklabel\n\n len_edg = np.max(self.sklabel)\n len_node = np.min(self.sklabel)\n logger.debug(\"len_edg: \" + str(len_edg) + \" len_node: \" + str(len_node))\n\n # get edges and nodes that are near the edge. (+bounding box)\n logger.debug(\"skeleton_analysis: starting element_neighbors processing\")\n self.elm_neigh = {}\n self.elm_box = {}\n for edg_number in list(range(len_node, 0)) + list(range(1, len_edg + 1)):\n self.elm_neigh[edg_number], self.elm_box[\n edg_number\n ] = self.__element_neighbors(edg_number)\n logger.debug(\"skeleton_analysis: finished element_neighbors processing\")\n # clear unneeded data. IMPORTANT!!\n\n self.__clean_shifted()\n # remove edges+nodes that are not connected to rest of the skeleton\n logger.debug(\n \"skeleton_analysis: Cut - Removing edges that are not\"\n + \" connected to rest of the skeleton (not counting its nodes)\"\n )\n cut_elm_neigh = dict(self.elm_neigh)\n cut_elm_box = dict(self.elm_box)\n for elm in self.elm_neigh:\n elm = int(elm)\n if elm > 0: # if edge\n conn_nodes = [i for i in self.elm_neigh[elm] if i < 0]\n conn_edges = []\n for n in conn_nodes:\n if n in self.elm_neigh:\n nn = self.elm_neigh[n] # get neighbours elements of node\n else:\n logger.debug(f\"Node {str(n)} not found! May be already deleted.\")\n continue\n\n for (e) in (nn): # if there are other edges connected to node add them to conn_edges\n if e > 0 and e not in conn_edges and e != elm:\n conn_edges.append(e)\n\n if (len(conn_edges) == 0): # if no other edges are connected to nodes, remove from skeleton\n logger.debug(f\"removing edge {str(elm)} with its nodes {str(self.elm_neigh[elm])}\")\n for night in self.elm_neigh[elm]:\n remove_elm(night, cut_elm_neigh, cut_elm_box, self.sklabel)\n self.elm_neigh = cut_elm_neigh\n self.elm_box = cut_elm_box\n\n # remove elements that are not connected to the rest of skeleton\n logger.debug(\"skeleton_analysis: Cut - Removing elements that are not connected to rest of the skeleton\")\n cut_elm_neigh = dict(self.elm_neigh)\n cut_elm_box = dict(self.elm_box)\n for elm in self.elm_neigh:\n elm = int(elm)\n if len(self.elm_neigh[elm]) == 0:\n logger.debug(f\"removing element {str(elm)}\")\n remove_elm(elm, cut_elm_neigh, cut_elm_box, self.sklabel)\n self.elm_neigh = cut_elm_neigh\n self.elm_box = cut_elm_box\n\n # get list of terminal nodes\n logger.debug(\"skeleton_analysis: Cut - get list of terminal nodes\")\n terminal_nodes = []\n for elm in self.elm_neigh:\n if elm < 0: # if node\n conn_edges = [i for i in self.elm_neigh[elm] if i > 0]\n if len(conn_edges) == 1: # if only one edge is connected\n terminal_nodes.append(elm)\n\n # init radius analysis\n logger.debug(\"__radius_analysis_init\")\n if self.volume_data is not None:\n skdst = self.__radius_analysis_init()\n\n # removes end terminal edges based on radius/length ratio\n logger.debug(\n \"skeleton_analysis: Cut - Removing bad terminal edges based on\"\n + \" radius/length ratio\"\n )\n cut_elm_neigh = dict(self.elm_neigh)\n cut_elm_box = dict(self.elm_box)\n for tn in terminal_nodes:\n te = [i for i in self.elm_neigh[tn] if i > 0][0] # terminal edge\n radius = float(self.__radius_analysis(te, skdst))\n edgst = self.__connection_analysis(int(te))\n edgst = self.__ordered_points_with_pixel_length(edg_number, edg_stats=edgst)\n edgst.update(self.__edge_length(edg_number, edgst))\n length = edgst[\"lengthEstimation\"]\n\n # logger.debug(str(radius / float(length))+\" \"+str(radius)+\" \"+str(length))\n if (radius / float(length)) > cut_ratio:\n logger.debug(f\"removing edge {str(te)} with its terminal node.\")\n remove_elm(elm, cut_elm_neigh, cut_elm_box, self.sklabel)\n self.elm_neigh = cut_elm_neigh\n self.elm_box = cut_elm_box\n\n self.__check_nodes_to_be_just_curve_from_elm_neig()\n\n # regenerate new nodes and edges from cut skeleton (sklabel)\n logger.debug(\"Regenerate new nodes and edges from cut skeleton\")\n self.sklabel[self.sklabel != 0] = 1\n skelet_nodes = self.__skeleton_nodes(self.sklabel)\n self.sklabel = self.__generate_sklabel(skelet_nodes)", "def removebl(treelist):\n print(\"removing branch lengths ... \")\n # use regex to replace branch lengths by empty\n topolist2 = [re.sub(r'(:\\-?[0-9]e?\\.?\\-?[0-9]*)', '', t) for t in treelist]\n topolist = [re.sub(r'e-[0-9]*', '', t) for t in topolist2]\n return(topolist)", "def remove_excess(dataframe):\n\n # Subset breadcrumbs that are not starts of rides.\n bad_crumbs = dataframe[dataframe.route_id ==\n dataframe.shift(periods=1).route_id]\n\n # Subset breadcrumbs in which rider did not move from current region.\n bad_crumbs = bad_crumbs[bad_crumbs.current_region ==\n bad_crumbs.shift(periods=1).current_region]\n\n # Subset crumbs in which the GPS position did not appreciably change.\n bad_crumbs = bad_crumbs[bad_crumbs.displacement <= 30]\n\n # Drop all the bad crumbs from the Dataframe view.\n clean_dataframe = dataframe.drop(bad_crumbs.index)\n\n return clean_dataframe", "def extract_graph_from_skeleton(sk): \n #used/unsused\n sk_used = np.zeros_like(sk)\n sk_unused = np.copy(sk)\n #root node\n root_position = findroot(sk)\n print('root_position',root_position)\n root = Branch(pixels=[root_position],name='root')\n setvalue(sk_used,root_position,1)\n setvalue(sk_unused,root_position,0)\n #extract rood edge\n edgelist,branchlist,endlist = next_pixels(root_position,sk_used,sk_unused)\n #assert len(edgelist)==1,'root has more than 1 branchedge'################!!!!!!!!\n rootedge = BranchEdge(edgelist[:1])\n while True:\n edgelist,branchlist,endlist = next_pixels(edgelist[0],sk_used,sk_unused)\n if edgelist:\n rootedge.add_pixels(edgelist)\n else:\n break\n assert len(branchlist)>=1,'root has no children'\n #first node(perhaps split LM and RM)\n branch1 = Branch(pixels=branchlist)\n root.add_child(branch1,rootedge)\n branch_startpoint_list = [branch1]##BFS\n edge_startpoint_list = []\n while branch_startpoint_list:\n branch1 = branch_startpoint_list.pop(0)\n edgelist,branchlist,endlist = next_pixels(branch1.pixels[0],sk_used,sk_unused)\n edge_startpoint_list = edgelist\n branch_cumulate_list = branchlist\n while branch_cumulate_list:#cumulate all the branch pixels(>3)\n bposition = branch_cumulate_list.pop(0)\n branch1.add_pixel(bposition)\n edgelist,branchlist,endlist = next_pixels(bposition,sk_used,sk_unused)\n edge_startpoint_list += edgelist\n branch_cumulate_list += branchlist\n #for each connected edge start,trace until next node\n for edge in edge_startpoint_list:\n branchedge1 = BranchEdge([edge])\n edgelist,branchlist,endlist = next_pixels(edge,sk_used,sk_unused)\n while edgelist:#trace until next node\n #print('edgelist',edgelist)\n branchedge1.add_pixels(edgelist)\n edgelist,branchlist,endlist = next_pixels(edgelist[0],sk_used,sk_unused)\n if branchlist:#next branch\n branch2 = Branch(pixels=branchlist)\n ##if branchedge too short, do nothing\n branch1.add_child(branch2,branchedge1)\n branch_startpoint_list.append(branch2)\n elif endlist:#end node\n branch2 = Branch(pixels=endlist)\n ##if branchedge too short, threshold based on rank(todo)\n branch1.add_child(branch2,branchedge1)\n else:#end without endlist (pixel value=3)\n branch2 = Branch(pixels=branchedge1.pixels[-1:])\n ##if branchedge too short, threshold based on rank(todo)\n branch1.add_child(branch2,branchedge1)\n #if this branch has only one edge, merge(may throw assert error)\n if len(branch1.edges) == 1:\n branch1.edges[0].endbracnch.rank-=1\n branch1.parent_edge.endbracnch = branch1.edges[0].endbracnch\n branch1.parent_edge.add_pixels_nocontinious(branch1.pixels)\n branch1.parent_edge.add_pixels(branch1.edges[0].pixels)\n branch1.edges[0].endbracnch.parent_edge = branch1.parent_edge\n return root", "def test_remove_line(self):\n tree = self.make_example_branch()\n self.build_tree_contents([\n ('goodbye', '')])\n output = self.run_bzr('diff --stat-dir', retcode=1)[0]\n self.assertEqualDiff(output, '''\\\n . | 1 -\n 1 directory changed, 0 insertions(+), 1 deletion(-)\n''')\n self.check_output_rules(output)", "def test_remove_line(self):\n tree = self.make_example_branch()\n self.build_tree_contents([\n ('goodbye', '')])\n output = self.run_bzr('diff --stat', retcode=1)[0]\n self.assertEqualDiff(output, '''\\\n goodbye | 1 -\n 1 file changed, 0 insertions(+), 1 deletion(-)\n''')\n self.check_output_rules(output)", "def subdCleanTopology():\n pass", "def remove_single_nodes(treenodes: pd.DataFrame):\n skids, counts = np.unique(treenodes[\"skeleton_id\"], return_counts=True)\n single_tns = skids[counts == 1]\n to_drop = np.zeros(len(treenodes), bool)\n for skid in single_tns:\n to_drop |= treenodes[\"skeleton_id\"] == skid\n return treenodes.loc[~to_drop].copy()", "def drop_short_segments(self, min_length):\n min_length = parse_depth(min_length, check_positive=True, var_name=\"min_length\")\n wells = self.iter_level(-2)\n for well in wells:\n well.segments = [segment for segment in well if segment.length >= min_length]\n return self.prune()", "def remove_odd_nodes(tree):\n for branch in tree:\n if len(branch.getchildren()) == 1:\n if branch.text is None:\n branch.getparent().replace(branch, branch[0])\n remove_odd_nodes(tree)\n return tree", "def clean_orphan_ands(self):\n self._changed = True\n for node in self._find_and_nodes():\n if len(list(self.successors(node)))==0 or len(list(self.predecessors(node)))<=1:\n self.remove_node(node)\n continue", "def prune_min(t):\n while len(t.branches) > 1:\n largest = max(t.branches,key = lambda x: x.label)\n t.branches.remove(largest)\n for b in t.branches:\n prune_min(b)", "def stackCLEAN(self):\n if None in self.stack:\n self.stack.remove(None)", "def RemoveFeatureBranch(self, branch):\n if branch == 'main':\n return\n\n self.RunCommand('git push origin --delete {0:s}'.format(branch))\n self.RunCommand('git branch -D {0:s}'.format(branch))", "def remove_segmented_harris_mirror(self):\n self.harris_sm = None" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Main function to get list urls in csv file, collect metrics form PageSpeed and pulling metrics to the prometheus
def process_request(): with open('inlist.csv', 'r') as csvfile: file_read_lines = csv.reader(csvfile, delimiter=',') for row in file_read_lines: page = ', '.join(row[:1]) # getting first row from file logging.info(f'Take URL: {page}') try: response_desktop = psd.analyse(page, strategy='desktop') url = response_desktop.url except Exception as err: logging.info('Error to get response form google: ' + str(err)) pass results = response_desktop.lighthouse_results audits_results = response_desktop.lighthouse_results_audits categories = response_desktop.categories # Total time page of load lighthouse_total_time_page_load = results.timing['total'] total_time_page_load.labels(url).set(lighthouse_total_time_page_load) # Main Performance page score lighthouse_total_performance_score = categories.performance['score'] performance_page_score.labels(url).set(lighthouse_total_performance_score) # Time to interactive metric lighthouse_time_to_interactive_score = audits_results.interactive['score'] time_to_interactive.labels(url).set(lighthouse_time_to_interactive_score) try: lighthouse_time_to_interactive_display = audits_results.interactive['displayValue'] display_value = re.match(r"[0-9]+\.*\,*[0-9]*", lighthouse_time_to_interactive_display) time_to_interactive_displayvalue.labels(url).set(float(display_value.group(0))) except Exception as err: logging.error(f'Time to interactive error: {str(err)}') time_to_interactive_displayvalue.labels(url).set(0) pass lighthouse_time_to_interactive_title = audits_results.interactive['title'] lighthouse_time_to_interactive_description = audits_results.interactive['description'] time_to_interactive_info.info({ 'title': lighthouse_time_to_interactive_title, 'description': lighthouse_time_to_interactive_description, 'url': url }) # speed index metric lighthouse_speed_index_score = audits_results.speed_index['score'] speed_index.labels(url).set(lighthouse_speed_index_score) try: lighthouse_speed_index_display = audits_results.speed_index['displayValue'] display_value = float(lighthouse_speed_index_display[:3]) speed_index_displayvalue.labels(url).set(display_value) except Exception as err: logging.error(f'speed index error: {str(err)}') speed_index_displayvalue.labels(url).set(0) pass lighthouse_speed_index_title = audits_results.speed_index['title'] lighthouse_speed_index_description = audits_results.speed_index['description'] speed_index_info.info({ 'title': lighthouse_speed_index_title, 'description': lighthouse_speed_index_description, 'url': url }) # first cpu idle metric lighthouse_first_cpu_idle_score = audits_results.first_cpu_idle['score'] first_cpu_idle_score.labels(url).set(lighthouse_first_cpu_idle_score) try: lighthouse_first_cpu_idle_display = audits_results.first_cpu_idle['displayValue'] display_value = float(lighthouse_first_cpu_idle_display[:3]) first_cpu_idle_score_displayvalue.labels(url).set(display_value) except Exception as err: logging.error(f'first_cpu_idle error: {str(err)}') first_cpu_idle_score_displayvalue.labels(url).set(0) pass lighthouse_first_cpu_idle_title = audits_results.first_cpu_idle['title'] lighthouse_first_cpu_idle_description = audits_results.first_cpu_idle['description'] first_cpu_idle_score_info.info({ 'title': lighthouse_first_cpu_idle_title, 'description': lighthouse_first_cpu_idle_description, 'url': url }) # mainthread work breakdown metric lighthouse_mainthread_work_breakdown_score = audits_results.mainthread_work_breakdown['score'] mainthread_work_breakdown.labels(url).set(lighthouse_mainthread_work_breakdown_score) try: lighthouse_mainthread_work_breakdown_display = audits_results.mainthread_work_breakdown['displayValue'] display_value = float(lighthouse_mainthread_work_breakdown_display[:3]) mainthread_work_breakdown_displayvalue.labels(url).set(display_value) except Exception as err: logging.error(f'mainthread_work_breakdown error: {str(err)}') mainthread_work_breakdown_displayvalue.labels(url).set(0) pass lighthouse_mainthread_work_breakdown_title = audits_results.mainthread_work_breakdown['title'] lighthouse_mainthread_work_breakdown_description = audits_results.mainthread_work_breakdown['description'] mainthread_work_breakdown_info.info({ 'title': lighthouse_mainthread_work_breakdown_title, 'description': lighthouse_mainthread_work_breakdown_description, 'url': url }) # first contentful paint metric lighthouse_first_contentful_paint_score = audits_results.first_contentful_paint['score'] first_contentful_paint.labels(url).set(lighthouse_first_contentful_paint_score) try: lighthouse_first_contentful_paint_display = audits_results.first_contentful_paint['displayValue'] display_value = float(lighthouse_first_contentful_paint_display[:3]) first_contentful_paint_displayvalue.labels(url).set(display_value) except Exception as err: logging.error(f'first_contentful_paint error: {str(err)}') first_contentful_paint_displayvalue.labels(url).set(0) pass lighthouse_first_contentful_paint_title = audits_results.first_contentful_paint['title'] lighthouse_first_contentful_paint_description = audits_results.first_contentful_paint['description'] first_contentful_paint_info.info({ 'title': lighthouse_first_contentful_paint_title, 'description': lighthouse_first_contentful_paint_description, 'url': url }) # first_meaningful_paint metric lighthouse_first_meaningful_paint_score = audits_results.first_meaningful_paint['score'] first_meaningful_paint.labels(url).set(lighthouse_first_meaningful_paint_score) try: lighthouse_first_meaningful_paint_display = audits_results.first_meaningful_paint['displayValue'] display_value = float(lighthouse_first_meaningful_paint_display[:3]) first_meaningful_paint_displayvalue.labels(url).set(display_value) except Exception as err: logging.error(f'first_meaningful_paint error: {str(err)}') first_meaningful_paint_displayvalue.labels(url).set(0) pass lighthouse_first_meaningful_paint_title = audits_results.first_meaningful_paint['title'] lighthouse_first_meaningful_paint_description = audits_results.first_meaningful_paint['description'] first_meaningful_paint_info.info({ 'title': lighthouse_first_meaningful_paint_title, 'description': lighthouse_first_meaningful_paint_description, 'url': url }) # render_blocking_resources metric lighthouse_render_blocking_resources_score = audits_results.render_blocking_resources['score'] render_blocking_resources.labels(url).set(lighthouse_render_blocking_resources_score) try: lighthouse_render_blocking_resources_display = audits_results.render_blocking_resources['displayValue'] display_value = re.search(r"[0-9]+\.*\,*[0-9]*", lighthouse_render_blocking_resources_display) render_blocking_resources_displayvalue.labels(url).set(float(display_value.group(0))) except Exception as err: logging.error(f'network_server_latency error: {str(err)}') render_blocking_resources_displayvalue.labels(url).set(0) pass lighthouse_render_blocking_resources_overall = audits_results.render_blocking_resources['details']['overallSavingsMs'] render_blocking_resources_overall.labels(url, 'overall', 'render_blocking_resources').set(lighthouse_render_blocking_resources_overall) lighthouse_render_blocking_resources_title = audits_results.render_blocking_resources['title'] lighthouse_render_blocking_resources_description = audits_results.render_blocking_resources['description'] render_blocking_resources_info.info({ 'title': lighthouse_render_blocking_resources_title, 'description': lighthouse_render_blocking_resources_description, 'url': url }) # uses_text_compression metric lighthouse_uses_text_compression_score = audits_results.uses_text_compression['score'] uses_text_compression.labels(url).set(lighthouse_uses_text_compression_score) # lighthouse_uses_text_compression_display = audits_results.uses_text_compression['displayValue'] # display_value = lighthouse_uses_text_compression_display # uses_text_compression_displayvalue.labels(url, display_value) # no metric lighthouse_uses_text_compression_overall = audits_results.uses_text_compression['details']['overallSavingsMs'] uses_text_compression_overall.labels(url, 'overall', 'uses_text_compression').set(lighthouse_uses_text_compression_overall) lighthouse_uses_text_compression_title = audits_results.uses_text_compression['title'] lighthouse_uses_text_compression_description = audits_results.uses_text_compression['description'] uses_text_compression_info.info({ 'title': lighthouse_uses_text_compression_title, 'description': lighthouse_uses_text_compression_description, 'url': url }) # uses_optimized_images metric lighthouse_uses_optimized_images_score = audits_results.uses_optimized_images['score'] uses_optimized_images.labels(url).set(lighthouse_uses_optimized_images_score) # lighthouse_uses_text_compression_display = audits_results.uses_text_compression['displayValue'] # display_value = lighthouse_uses_text_compression_display # uses_text_compression_displayvalue.labels(url, display_value) #no metric lighthouse_uses_optimized_images_overall = audits_results.uses_optimized_images['details']['overallSavingsMs'] uses_optimized_images_overall.labels(url, 'overall', 'uses_optimized_images').set(lighthouse_uses_optimized_images_overall) lighthouse_uses_optimized_images_title = audits_results.uses_optimized_images['title'] lighthouse_uses_optimized_images_description = audits_results.uses_optimized_images['description'] uses_optimized_images_info.info({ 'title': lighthouse_uses_optimized_images_title, 'description': lighthouse_uses_optimized_images_description, 'url': url }) # uses_long_cache_ttl metric lighthouse_uses_long_cache_ttl_score = audits_results.uses_long_cache_ttl['score'] uses_long_cache_ttl.labels(url).set(lighthouse_uses_long_cache_ttl_score) try: lighthouse_uses_long_cache_ttl_display = audits_results.uses_long_cache_ttl['displayValue'] display_value = re.match(r"[0-9]+\.*\,*[0-9]*", lighthouse_uses_long_cache_ttl_display) uses_long_cache_ttl_displayvalue.labels(url).set(float(display_value.group(0))) except Exception as err: logging.error(f'network_server_latency error: {str(err)}') uses_long_cache_ttl_displayvalue.labels(url).set(0) pass lighthouse_uses_long_cache_ttl_title = audits_results.uses_long_cache_ttl['title'] lighthouse_uses_long_cache_ttl_description = audits_results.uses_long_cache_ttl['description'] uses_long_cache_ttl_info.info({ 'title': lighthouse_uses_long_cache_ttl_title, 'description': lighthouse_uses_long_cache_ttl_description, 'url': url }) # max_potential_fid metric lighthouse_max_potential_fid_score = audits_results.max_potential_fid['score'] max_potential_fid.labels(url).set(lighthouse_max_potential_fid_score) try: lighthouse_max_potential_fid_display = audits_results.max_potential_fid['displayValue'] display_value = float(lighthouse_max_potential_fid_display[:3].replace(',','.')) max_potential_fid_displayvalue.labels(url).set(display_value) except Exception as err: logging.error(f'max_potential_fid err: {str(err)}') pass lighthouse_max_potential_fid_title = audits_results.max_potential_fid['title'] lighthouse_max_potential_fid_description = audits_results.max_potential_fid['description'] max_potential_fid_info.info({ 'title': lighthouse_max_potential_fid_title, 'description': lighthouse_max_potential_fid_description, 'url': url }) # total_blocking_time metric lighthouse_total_blocking_time_score = audits_results.total_blocking_time['score'] total_blocking_time.labels(url).set(lighthouse_total_blocking_time_score) try: lighthouse_total_blocking_time_display = audits_results.total_blocking_time['displayValue'] display_value = float(lighthouse_total_blocking_time_display[:3].replace(',','.')) total_blocking_time_displayvalue.labels(url).set(display_value) except Exception as err: logging.error(f'total_blocking_time error: {str(err)}') total_blocking_time_displayvalue.labels(url).set(0) pass lighthouse_total_blocking_time_title = audits_results.total_blocking_time['title'] lighthouse_total_blocking_time_description = audits_results.total_blocking_time['description'] total_blocking_time_info.info({ 'title': lighthouse_total_blocking_time_title, 'description': lighthouse_total_blocking_time_description, 'url': url }) # estimated_input_latency metric lighthouse_estimated_input_latency_score = audits_results.estimated_input_latency['score'] estimated_input_latency.labels(url).set(lighthouse_estimated_input_latency_score) try: lighthouse_estimated_input_latency_display = audits_results.estimated_input_latency['displayValue'] display_value = float(lighthouse_estimated_input_latency_display[:3].replace(',','.')) estimated_input_latency_displayvalue.labels(url).set(display_value) except Exception as err: logging.error(f'estimated_input_latency error: {str(err)}') estimated_input_latency_displayvalue.labels(url).set(0) pass lighthouse_estimated_input_latency_title = audits_results.estimated_input_latency['title'] lighthouse_estimated_input_latency_description = audits_results.estimated_input_latency['description'] estimated_input_latency_info.info({ 'title': lighthouse_estimated_input_latency_title, 'description': lighthouse_estimated_input_latency_description, 'url': url }) # uses_rel_preconnect metric lighthouse_uses_rel_preconnect_score = audits_results.uses_rel_preconnect['score'] uses_rel_preconnect.labels(url).set(lighthouse_uses_rel_preconnect_score) # lighthouse_uses_rel_preconnect_display = audits_results.uses_rel_preconnect['displayValue'] # display_value = lighthouse_uses_rel_preconnect_display # uses_rel_preconnect_displayvalue.labels(url, display_value) # no metric lighthouse_uses_rel_preconnect_overall = audits_results.uses_rel_preconnect['details']['overallSavingsMs'] uses_rel_preconnect_overall.labels(url, 'overall', 'uses_rel_preconnect').set(lighthouse_uses_rel_preconnect_overall) lighthouse_uses_rel_preconnect_title = audits_results.uses_rel_preconnect['title'] lighthouse_uses_rel_preconnect_description = audits_results.uses_rel_preconnect['description'] uses_rel_preconnect_info.info({ 'title': lighthouse_uses_rel_preconnect_title, 'description': lighthouse_uses_rel_preconnect_description, 'url': url }) # bootup_time metric lighthouse_bootup_time_score = audits_results.bootup_time['score'] bootup_time.labels(url).set(lighthouse_bootup_time_score) try: lighthouse_bootup_time_display = audits_results.bootup_time['displayValue'] display_value = float(lighthouse_bootup_time_display[:3]) bootup_time_displayvalue.labels(url).set(display_value) except Exception as err: logging.error(f'bootup_time error: {str(err)}') bootup_time_displayvalue.labels(url).set(0) pass lighthouse_bootup_time_wastedms = audits_results.bootup_time['details']['summary']['wastedMs'] bootup_time_wastedms.labels(url, 'bootup_time').set(lighthouse_bootup_time_wastedms) lighthouse_bootup_time_title = audits_results.bootup_time['title'] lighthouse_bootup_time_description = audits_results.bootup_time['description'] bootup_time_info.info({ 'title': lighthouse_bootup_time_title, 'description': lighthouse_bootup_time_description, 'url': url }) # unminified_css metric lighthouse_unminified_css_score = audits_results.unminified_css['score'] unminified_css.labels(url).set(lighthouse_unminified_css_score) # lighthouse_unminified_css_display = audits_results.unminified_css['displayValue'] # display_value = lighthouse_unminified_css_display # unminified_css_displayvalue.labels(url, display_value) # no this metric lighthouse_unminified_css_overall = audits_results.unminified_css['details']['overallSavingsMs'] unminified_css_overall.labels(url, 'overall', 'unminified_css').set(lighthouse_unminified_css_overall) lighthouse_unminified_css_title = audits_results.unminified_css['title'] lighthouse_unminified_css_description = audits_results.unminified_css['description'] unminified_css_info.info({ 'title': lighthouse_unminified_css_title, 'description': lighthouse_unminified_css_description, 'url': url }) # network_server_latency metric # lighthouse_network_server_latency_score = audits_results.network_server_latency['score'] # network_server_latency.labels(url).set(lighthouse_network_server_latency_score) try: lighthouse_network_server_latency_display = audits_results.network_server_latency['displayValue'] display_value = re.match(r"[0-9]+\.*\,*[0-9]*", lighthouse_network_server_latency_display) network_server_latency_displayvalue.labels(url).set(float(display_value.group(0))) except Exception as err: logging.error(f'network_server_latency error: {str(err)}') network_server_latency_displayvalue.labels(url).set(0) pass lighthouse_network_server_latency_title = audits_results.network_server_latency['title'] lighthouse_network_server_latency_description = audits_results.network_server_latency['description'] network_server_latency_info.info({ 'title': lighthouse_network_server_latency_title, 'description': lighthouse_network_server_latency_description, 'url': url }) # offscreen_images metric lighthouse_offscreen_images_score = audits_results.offscreen_images['score'] offscreen_images.labels(url).set(lighthouse_offscreen_images_score) lighthouse_offscreen_images_overall = audits_results.offscreen_images['details']['overallSavingsMs'] offscreen_images_overall.labels(url, 'overall', 'offscreen_images').set(lighthouse_offscreen_images_overall) try: lighthouse_offscreen_images_display = audits_results.offscreen_images['displayValue'] display_value = lighthouse_offscreen_images_display offscreen_images_displayvalue.labels(url, display_value) except Exception as err: logging.error(f'Offscreen_images error: {str(err)}') offscreen_images_displayvalue.labels(url, '0') pass lighthouse_offscreen_images_title = audits_results.offscreen_images['title'] lighthouse_offscreen_images_description = audits_results.offscreen_images['description'] offscreen_images_info.info({ 'title': lighthouse_offscreen_images_title, 'description': lighthouse_offscreen_images_description, 'url': url }) # uses_responsive_images metric lighthouse_uses_responsive_images_score = audits_results.uses_responsive_images['score'] uses_responsive_images.labels(url).set(lighthouse_uses_responsive_images_score) lighthouse_uses_responsive_images_overall = audits_results.uses_responsive_images['details']['overallSavingsMs'] uses_responsive_images_overall.labels(url, 'overall', 'uses_responsive_images').set(lighthouse_uses_responsive_images_overall) # lighthouse_offscreen_images_display = audits_results.offscreen_images['displayValue'] # display_value = lighthouse_offscreen_images_display # offscreen_images_displayvalue.labels(url, display_value) # no metric lighthouse_uses_responsive_images_title = audits_results.uses_responsive_images['title'] lighthouse_uses_responsive_images_description = audits_results.uses_responsive_images['description'] uses_responsive_images_info.info({ 'title': lighthouse_uses_responsive_images_title, 'description': lighthouse_uses_responsive_images_description, 'url': url }) # unused_css_rules metric lighthouse_unused_css_rules_score = audits_results.unused_css_rules['score'] unused_css_rules.labels(url).set(lighthouse_unused_css_rules_score) lighthouse_unused_css_rules_display = audits_results.unused_css_rules['displayValue'] display_value = lighthouse_unused_css_rules_display unused_css_rules_displayvalue.labels(url, display_value) lighthouse_unused_css_rules_overall = audits_results.unused_css_rules['details']['overallSavingsMs'] unused_css_rules_overall.labels(url, 'overall', 'unused_css_rules').set(lighthouse_unused_css_rules_overall) lighthouse_unused_css_rules_title = audits_results.unused_css_rules['title'] lighthouse_unused_css_rules_description = audits_results.unused_css_rules['description'] unused_css_rules_info.info({ 'title': lighthouse_unused_css_rules_title, 'description': lighthouse_unused_css_rules_description, 'url': url }) # Total byte weight metric lighthouse_total_byte_weight_score = audits_results.total_byte_weight['score'] total_byte_weight_score.labels(url).set(lighthouse_total_byte_weight_score) lighthouse_total_byte_weight_display = audits_results.total_byte_weight['displayValue'] display_value = lighthouse_total_byte_weight_display total_byte_weight_displayvalue.labels(url, display_value) lighthouse_total_byte_weight_title = audits_results.total_byte_weight['title'] lighthouse_total_byte_weight_description = audits_results.total_byte_weight['description'] total_byte_weight_info.info({ 'title': lighthouse_total_byte_weight_title, 'description': lighthouse_total_byte_weight_description, 'url': url }) # Uses webp images metric lighthouse_uses_webp_images_score = audits_results.uses_webp_images['score'] uses_webp_images.labels(url).set(lighthouse_uses_webp_images_score) # lighthouse_uses_webp_images_display = audits_results.uses_webp_images['displayValue'] # display_value = float(lighthouse_uses_webp_images_display[:3]) # uses_webp_images_displayvalue.labels(url).set(display_value) lighthouse_uses_webp_images_overall = audits_results.uses_webp_images['details']['overallSavingsMs'] uses_webp_images_overall.labels(url, 'overall', 'uses_webp_images').set(lighthouse_uses_webp_images_overall) lighthouse_uses_webp_images_title = audits_results.uses_webp_images['title'] lighthouse_uses_webp_images_description = audits_results.uses_webp_images['description'] uses_webp_images_info.info({ 'title': lighthouse_uses_webp_images_title, 'description': lighthouse_uses_webp_images_description, 'url': url }) # dom_size metric lighthouse_dom_size_score = audits_results.dom_size['score'] dom_size.labels(url).set(lighthouse_dom_size_score) try: lighthouse_dom_size_display = audits_results.dom_size['displayValue'] display_value = re.match(r"[0-9]+\.*\,*[0-9]*", lighthouse_dom_size_display) dom_size_displayvalue.labels(url).set(float(display_value.group(0).replace(',','.'))) except Exception as err: logging.error(f'dom_siz error: {str(err)}') offscreen_images_displayvalue.labels(url, '0') pass lighthouse_dom_size_title = audits_results.dom_size['title'] lighthouse_dom_size_description = audits_results.dom_size['description'] dom_size_info.info({ 'title': lighthouse_dom_size_title, 'description': lighthouse_dom_size_description, 'url': url }) # uses_rel_preload metric lighthouse_uses_rel_preload_score = audits_results.uses_rel_preload['score'] uses_rel_preload.labels(url).set(lighthouse_uses_rel_preload_score) # lighthouse_uses_rel_preload_display = audits_results.uses_rel_preload['displayValue'] # display_value = float(lighthouse_uses_rel_preload_display[:3].replace(',', '.')) # uses_rel_preload_displayvalue.labels(url).set(display_value) lighthouse_uses_rel_preload_overall = audits_results.uses_rel_preload['details']['overallSavingsMs'] uses_rel_preload_overall.labels(url, 'overall', 'uses_rel_preload').set(lighthouse_uses_rel_preload_overall) lighthouse_uses_rel_preload_title = audits_results.uses_rel_preload['title'] lighthouse_uses_rel_preload_description = audits_results.uses_rel_preload['description'] uses_rel_preload_info.info({ 'title': lighthouse_uses_rel_preload_title, 'description': lighthouse_uses_rel_preload_description, 'url': url }) # unminified_javascript metric lighthouse_unminified_javascript_score = audits_results.unminified_javascript['score'] unminified_javascript.labels(url).set(lighthouse_unminified_javascript_score) lighthouse_unminified_javascript_overall = audits_results.unminified_javascript['details']['overallSavingsMs'] unminified_javascript_overall.labels(url, 'overall', 'unminified_javascript').set(lighthouse_unminified_javascript_overall) # lighthouse_unminified_javascript_display = audits_results.unminified_javascript['displayValue'] # display_value = float(lighthouse_unminified_javascript_display[:3].replace(',', '.')) # unminified_javascript_displayvalue.labels(url).set(display_value) # no metric lighthouse_unminified_javascript_title = audits_results.unminified_javascript['title'] lighthouse_unminified_javascript_description = audits_results.unminified_javascript['description'] unminified_javascript_info.info({ 'title': lighthouse_unminified_javascript_title, 'description': lighthouse_unminified_javascript_description, 'url': url }) # redirects metric lighthouse_redirects_score = audits_results.redirects['score'] redirects.labels(url).set(lighthouse_redirects_score) lighthouse_redirects_overall = audits_results.redirects['details']['overallSavingsMs'] redirects_overall.labels(url, 'overall', 'redirects').set(lighthouse_redirects_overall) # lighthouse_unminified_javascript_display = audits_results.unminified_javascript['displayValue'] # display_value = float(lighthouse_unminified_javascript_display[:3].replace(',', '.')) # unminified_javascript_displayvalue.labels(url).set(display_value) # no metric lighthouse_redirects_title = audits_results.redirects['title'] lighthouse_redirects_description = audits_results.redirects['description'] redirects_info.info({ 'title': lighthouse_redirects_title, 'description': lighthouse_redirects_description, 'url': url }) logging.info('Done.')
[ "def run_parser(machine, output, report):\n dict_rows = csv.DictReader(report, delimiter='|')\n pattern = re.compile(r'^(http|https|ftp)://(aix.software.ibm.com|public.dhe.ibm.com)/(aix/ifixes/.*?/|aix/efixes/security/.*?.tar)$')\n rows = [row['Download URL'] for row in dict_rows]\n rows = [row for row in rows if pattern.match(row) is not None]\n rows = list(set(rows)) # remove duplicates\n logging.debug('{}: extract {} urls in the report'.format(machine, len(rows)))\n output.update({'1.parse': rows})", "def main_split_urls():\n\n all_urls_path = \"data/urls/collected/all.csv\"\n url_path = \"data/urls/to_collect/set0_6100_8100.txt\"\n out_path = \"data/urls/to_collect/finish_set0_6100_8100.txt\"\n remaining_urls(all_urls_path, url_path, out_path)", "def parseFeeds_from_url_in_file(self):\n status = False\n def generate_feeds_to_parse(database):\n #go through all the registered fedds url\n #print(\"[URLS]: \\n\")\n for key in database:\n url = database[key]['url']\n category = database[key]['category']\n etag = database[key]['etag']\n last_modified_date = database[key]['last_modified']\n pub_date = database[key]['pub_date']\n \n yield Feed(url, category, etag, last_modified_date, pub_date)\n ##\n \n #First preproccess\n if(not self.__preproccessing()):\n print(f\"\"\"PLEASE ADD THE FILE: {self.plain_feeds_data_path} AND RETRY AGAIN. \n OR TRY TO USE parseFeed METHOD BY GIVING A URL IN ARGUMENT\"\"\")\n else:\n new_item_hids = [] # will contain the hid of the new crawled item\n with shelve.open(self.monitored_feeds_data_path, writeback=True) as database:\n feeds_to_parse = generate_feeds_to_parse(database) # return a genertor\n # multi proccess area\n with tqdm(total=self.stats_monitored_feeds()) as pbar:\n with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:\n futures_new_items_hids = [executor.submit(self.parseFeed, feed) for feed in feeds_to_parse]\n \n for future_item_hid in as_completed(futures_new_items_hids):\n pbar.update(1)\n new_item_hids = np.append(new_item_hids, future_item_hid.result())\n \n # close database once all the thread joined\n #database.close\n status = True #important\n print(\"END OF PARSING RETURN...\")\n return status, new_item_hids", "def measure_cpu(url):\n print (url)\n os.system('echo %s >> ./cpu-usage' % url)\n cpu_list = []\n # Loop\n for i in range(90):\n cpu = os.popen(\"top -n 1 | grep /usr/lib/chromium/chrome | head -1 | awk '{print $8;}'\").read().strip()\n time.sleep(1)\n cpu_list.append(cpu)\n os.system('echo %s >> ./cpu-usage' % cpu_list)\n # os.system(\"ps -eo pcpu,pid,user,args | grep 'firefox-bin' | sort -k1 -r -n | head -1 | awk '{print $1;}'\")\n # os.system(\"ps -eo pcpu,pid,user,args | sort -k1 -r -n | head -1 | awk '{print $1;}'\")", "def target_urls_generator(input_csv):\n inputcsvWithoutExt = input_csv.replace(\".csv\", \"\")\n inputcsvWithoutExt = inputcsvWithoutExt.replace(\".CSV\", \"\")\n output_URLs_csv = \"%s_URLs.csv\" % inputcsvWithoutExt\n output_3cols_csv = \"%s_3cols.csv\" % inputcsvWithoutExt\n\n with open(output_URLs_csv, 'wb') as output_URLs_csvfile:\n output_URLs_csvwriter = csv.writer(output_URLs_csvfile, delimiter=',')\n with open(output_3cols_csv, 'wb') as output_3cols_csvfile:\n output_3cols_csvwriter = csv.writer(output_3cols_csvfile, delimiter=',')\n with open(input_csv, \"rb\") as input_csvfile:\n reader = csv.reader(input_csvfile, delimiter=\",\")\n for i, line in enumerate(reader):\n if DEBUG:\n print '{}: {}'.format(i, line)\n if len(line) > 3:\n if i > 0:\n DPCI = \"%s-%s-%s\" % (\n line[0].strip().zfill(3),\n line[1].strip().zfill(2),\n line[2].strip().zfill(4))\n else:\n continue\n else:\n DPCI = line[0].strip()\n\n # search_url = \"http://www.target.com/s?searchTerm=%s\" % DPCI\n s_json_url = \"http://tws.target.com/searchservice/item/\" \\\n \"search_results/v2/by_keyword?kwr=y&search_term=%s\" \\\n \"&alt=json&pageCount=24&response_group=Items&zone=mobile&offset=0\" % DPCI\n try:\n contents = requests.get(s_json_url).text\n res_json = json.loads(contents)\n URL = \"http://www.target.com/%s\" % \\\n res_json['searchResponse']['items']['Item'][0]['productDetailPageURL']\n reg_exp = re.findall(\"(.*)#\", URL)\n if len(reg_exp) > 0:\n URL = reg_exp[0]\n\n TCIN = \"\"\n reg_exp = re.findall(\"A-([0-9]+)\", URL)\n if len(reg_exp) > 0:\n TCIN = reg_exp[0]\n except:\n URL = \"\"\n TCIN = \"\"\n\n if len(URL) > 0:\n output_URLs_csvwriter.writerow([URL])\n output_3cols_csvwriter.writerow([DPCI, TCIN, URL])\n if DEBUG:\n print [DPCI, TCIN, URL]", "def parse_all(driver):\n url_lst = input(\"Enter name of file with .txt extension with list of urls: \")\n data = pd.read_csv(url_lst,header=None,names=['url']) #text file containing a list of the scraped urls (should be in same directory)\n file_name = input(\"Input the file name with .txt extension you wish to store abstracts in: \")\n file = open(file_name,'w')\n\n max_iters = len(data) #total number of scraped urls to be parsed\n print(\"The parser will parse: \" + str(max_iters) + \" urls.\")\n\n for i in range(0,max_iters):\n print('On url ',i)\n driver.refresh()\n time.sleep(2)\n urli = str(extractor(data.iloc[i,0],3))\n file.write(urli)\n file.write('\\n')\n driver.quit()\n\n return file_name", "def get_profiles(config):\n\n basepath = os.path.dirname(__file__)\n profiles_path = os.path.join(basepath,config['input_path'],'scrape_profiles.csv')\n log_output = os.path.join(basepath,config['log_path'],'outstanding_profiles.csv')\n output_dir = os.path.join(basepath,config['output_path'],'profiles')\n profiles_df = pd.read_csv(profiles_path)\n freq = 200\n max_rows = profiles_df.shape[0] + 1\n\n for start_row in range(0, max_rows, freq):\n end_row = min(start_row + freq, max_rows)\n\n output_path = output_dir + '/profiles_{time}_{s_row}_{e_row}.csv'\\\n .format(s_row=start_row, e_row=end_row, time=datetime.now().strftime(\"%H%M%S\"))\n\n cmd = 'scrapy runspider ' + basepath + '/spiders/amazon_profiles.py -o {output_path} '\\\n '-a config=\"{profiles_path},{log_file},{s_row},{e_row},main\"' \\\n .format(output_path=output_path, profiles_path=profiles_path, log_file=log_output, s_row=start_row, e_row=end_row, time=datetime.now().strftime(\"%H%M%S\"))\n call(cmd, shell=True)", "def url_main(self):\n log = self.logger\n st = time.time()\n print(\"Running...\\nCheck logs/threat_hub.log for detailed events\")\n log.info(\"URL Threat intell hub started\")\n log.info(\"database cleanup started\")\n self.process.flush_db()\n log.info(\"database flushed successfully\")\n try:\n for url in self.crawl.url_targets:\n response = self.crawl.send_request(url=url)\n if not response:\n continue\n else:\n dataset = self.process.shape_up(raw_data=response)\n # self.first_run(dataset, url)\n self.normal_run(dataset, url)\n log.info(f\"Total {self.process.db.get_total_url()} url records present.\")\n log.info(f\"Total {self.process.db.get_phishing_count()} phishing urls present\")\n log.info(f\"Total {self.process.db.get_malware_count()} malware urls present\")\n log.info(f\"Total {self.process.db.get_ransom_count()} ransomware urls present\")\n\n except Exception as err:\n log.exception(err, exc_info=False)\n finally:\n end = time.time()\n log.info(\"Finished executing threat intell hub in {} seconds\".format(end - st))\n print(\"Finished...\")", "def scrape_dep_sites():\n\n scrape_counter = 0\n\n #load urls in list\n db_name_user = 'dbname=romparl user=radu'\n table_command = 'SELECT dep_name, dep_url FROM dep_name_url'\n urls = ftt.get_list_from_table(db_name_user, table_command)\n\n cv_fldr = \"/media/radu/romparl/CD/htmls/politicians/cv_pages/\" \n smry_fldr = \"/media/radu/romparl/CD/htmls/politicians/summary_pages/\"\n err_fldr = \"/media/radu/romparl/CD/errors/\"\n\n #go thorugh urls and scrape, ignore 2016 session, no CVs yet\n for u in urls:\n if '2016' not in u[1]:\n session = u[1][-4:]\n scrape_counter += 1\n print(u[0], session, scrape_counter)\n cv_u = u[1] + '&pag=0'\n cv_file = str(u[0]) + '-' + session + '-cv.txt'\n smry_u = u[1] + '&pag=1'\n smry_file = str(u[0]) + '-' + session + '-summary.txt'\n\n try:\n cv_uht = sc.scrape(cv_u)\n cv_dictio = {'url':cv_uht[0], 'html':cv_uht[1], \n 'scrape_time_utc':cv_uht[2]}\n ftt.json_file_dump(cv_fldr, cv_file, cv_dictio)\n\n smry_uht = sc.scrape(smry_u)\n smry_dictio = {'url':smry_uht[0], 'html':smry_uht[1], \n 'scrape_time_utc':smry_uht[2]}\n ftt.json_file_dump(smry_fldr, smry_file, smry_dictio)\n\n except:\n err_file = str(u[0]) + '.txt'\n tb = traceback.format_stack()\n error = {'message':tb, 'error_index':scrape_counter, \n 'list_element':u[0]}\n ftt.json_file_dump(err_fldr, err_file, error)\n continue", "def run():\n\n kpi_paths = ['metric_0128.csv', 'metric_0129.csv', 'metric_0130.csv']\n kpi_data = pd.DataFrame()\n for path in kpi_paths:\n d = pd.read_csv(path, encoding='gb18030')\n kpi_data = kpi_data.append(d)\n\n cmdb_ids = list(set(kpi_data['cmdb_id']))\n for cmdb_id in cmdb_ids:\n peers = kpi_data[kpi_data['cmdb_id'] == cmdb_id]\n names = list(set(peers['kpi_name']))\n for name in names:\n v = {\"upper\": 6.0, \"lower\": 6.0, \"belt\": 1.0, \"bounder\": \"both\", \"dtype\": \"dynamic\", \"times\": 3}\n rule_obj = Rule(\n is_valid = True,\n tag = 'performance',\n instance = name,\n instance_type = cmdb_id,\n cmdb_id = cmdb_id,\n period = 60,\n alert_level = 'P1',\n values = json.dumps(v)\n )\n rule_obj.save()", "def load_urls(url_count=100_000):\n print(\"Loading URLs..\")\n with Path(\"alexatop1m.csv\").open(mode='r') as i:\n urls = ['http://'+r[1] for r in csv.reader(i)]\n print(f\"Returning {url_count} random urls.\")\n return sample(urls, url_count)", "def scrape_history(start_date, end_date, base_url, url_params, sleep_time, out_dir, log_path):\n # Start logger\n logging.basicConfig(filename=log_path, level=logging.DEBUG)\n logging.info(\"Start Scraping\")\n\n # Start scraping\n dr = daterange(start_date, end_date)\n for i, dt in enumerate(dr):\n ts = sleep_time\n # Following block will try to request the url at ever increasing sleep times.\n while True:\n try: # try to request url w/ default sleep time\n print 'Downloading file number %d' % i\n logging.info('attempt download file no. %d' % i)\n logging.info('time to sleep ' + str(ts))\n url = build_url(dt, base_url, url_params)\n r = requests.get(url)\n #TODO check if any data is in the returned page. Wunderground will serve up just the column names\n #TODO with no rows when no data exists.\n # Request has been served succesfully, so write it to a csv\n out_path = os.path.join(out_dir, dt.strftime('%Y_%m_%d.csv'))\n #TODO write a helper function to cleanup the output csv files. The current version includes a bunch of\n #TODO stupid blank lines. However, Pandas is perfectly capable of parsing these csvs into dataframes.\n with open(out_path, 'wb') as fo:\n fo.write(r.text.replace('<br>', '')) # remove the annoying <br> tags at the end of each line\n # Sleep for a random time centered on sleep_time\n time.sleep(numpy.random.random_integers(0.8*sleep_time, 1.2*sleep_time))\n except requests.ConnectionError:\n logging.warning('ConnectionError')\n ts = ts*2\n time.sleep(ts)\n continue\n break", "async def scrape_urls(\n urls: List[str],\n metadata: dict,\n sources: dict,\n parser: Callable[httpx.AsyncClient, str, dict, dict],\n):\n async with httpx.AsyncClient(timeout=None) as client:\n async with DOWNLOAD_LOCK:\n for task in tqdm.tqdm(\n asyncio.as_completed(\n list(parser(client, url, metadata, sources) for url in urls)\n ),\n total=len(urls),\n unit=\"page\",\n unit_scale=False,\n unit_divisor=1,\n ):\n await task", "def run_multiproccesing():\n\n print('--- Multiprocessing ---')\n with Pool(5) as executor:\n return list(executor.map(load_url, URLS))", "def get_metrics(urls, req_method=\"GET\", timeout=45, req_type='html', req_data=None):\n print('Collecting metrics from udp socket {0}:{1}'.format(LISTEN_HOST, LISTEN_PORT))\n udpsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n udpsock.settimeout(1)\n udpsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n udpsock.bind((LISTEN_HOST, LISTEN_PORT,))\n\n start_time = time.time()\n try:\n for url in urls:\n _make_call(url, req_method, req_data, req_type)\n except Exception as ex:\n print ('error on {0}'.format(urls))\n return None\n \n metrics = []\n keep_receiving = True\n first_ping = False\n timer_5s = 0\n \n while keep_receiving:\n if (time.time() - start_time > timeout):\n print('Failed to collect metrics after waiting for {0}'.format(timeout))\n keep_receiving = False\n else:\n if timer_5s > 0 and (time.time() - timer_5s > 5):\n keep_receiving = False\n try:\n ret = udpsock.recv(BUFFER_SIZE)\n if ret:\n bson_data = bson.BSON(ret)\n try:\n data = bson_data.to_dict(mdict)\n except AttributeError:\n data = bson_data.decode(codec_options=bson.CodecOptions(document_class=mdict))\n\n if \"measurements\" in data: #then it's a metrics message\n for m in data[\"measurements\"]:\n if \"tags\" in m or first_ping or \"IsCustom\" in m:\n metrics.append(data)\n data = None\n if first_ping:\n keep_receiving = False\n elif timer_5s == 0:\n timer_5s = time.time()\n break\n else:\n print('Failed to collect metrics from udp socket {0}:{1} gave empty response'.format(LISTEN_HOST, LISTEN_PORT))\n except socket.timeout:\n pass\n\n udpsock.close()\n return metrics", "def crawling():\n driver = login()\n wait = WebDriverWait(driver, delay)\n\n stopped_cik_file_index = 0\n stopped_cik_row_index = 0\n\n if Path(log_file).exists() and os.path.getsize(log_file) > 0:\n stopped_cik_file_index, stopped_cik_row_index = parse_log()\n\n print(f' file index {stopped_cik_file_index} row index {stopped_cik_row_index}')\n \"\"\" handle submit query\n loop cik-picked_file_list\n create three csv file and append extraction data\n \"\"\"\n log = open(log_file, 'w')\n\n for cik_idx, cik_file in enumerate(cik_file_list):\n if cik_idx >= stopped_cik_file_index:\n logging.info(f' cik idx: {cik_idx} stopped_cik_file_index: {stopped_cik_file_index}')\n with open(cik_file) as csv_file:\n csv_data = csv.reader(csv_file, delimiter=',')\n #### row_idx = 0\n\n \"\"\" create output file\n write output file's header\n header: 'COMPANY NAME' 'CIK' 'CUSIP' 'CUSIP_8D' 'CUSIP_9D' 'TICKER'\n \"\"\"\n with open(output_file_list[cik_idx], mode='a', newline='') as out_file:\n out_writer = csv.writer(out_file,\n delimiter=',',\n quotechar='\"',\n quoting=csv.QUOTE_MINIMAL)\n if not os.path.getsize(output_file_list[cik_idx]) > 0:\n head_writer = csv.DictWriter(out_file, fieldnames=output_format_fields)\n head_writer.writeheader()\n\n \"\"\" loop submit query with cik iterate\n download csv file per cik\n parse csv and export cusip from it\n \"\"\"\n for row_idx, row in enumerate(csv_data):\n if cik_idx != stopped_cik_file_index:\n stopped_cik_row_index = 0\n if row_idx != 0 and row_idx > stopped_cik_row_index:\n logging.info(f' cik row_idx: {row_idx} stopped_cik_row_index: {stopped_cik_row_index}')\n print(f' cik row_idx: {row_idx} stopped_cik_row_index: {stopped_cik_row_index}')\n \"\"\" log current cik_file_name, output_file_name, row index of cik_file_name\n \"\"\"\n log.write('%s\\n' % cik_file)\n log.write('%s\\n' % output_file_list[cik_idx])\n log.write('%d\\n' % row_idx)\n\n company_name = row[0]\n cik = row[1] # cik code from cik_picked_file\n ticker = row[2] # ticker code from cik_picked_file\n # print(f'Entered {cik}')\n\n driver.find_element_by_id('code_lookup_method1').clear()\n driver.find_element_by_id('code_lookup_method1').send_keys(cik)\n query_btn = wait.until(\n EC.element_to_be_clickable((By.ID, 'form_submit')))\n query_btn.click()\n driver.switch_to.window(driver.window_handles[1])\n try:\n wait.until(EC.visibility_of_element_located((By.XPATH, '//*[@id=\"subcol\"]')))\n try:\n WebDriverWait(driver, m_delay).until(EC.visibility_of_element_located(\n (By.XPATH, '//*[@id=\"main\"]/p[4]/b')))\n driver.find_element_by_xpath('//*[@id=\"main\"]/p[2]/a').click() # down click\n file_name = driver.find_element_by_xpath(\n '//*[@id=\"main\"]/p[2]/a'\n ).text # downloading csv file name\n downloaded_file = download_path + file_name # downloaded csv file's absolute\n # path\n sleep(2)\n\n # check whether downloading is success\n seconds = 0\n dl_wait = True\n while dl_wait and seconds < delay:\n sleep(1)\n dl_wait = False\n for fname in os.listdir(download_path):\n if fname.endswith('.crdownload'):\n dl_wait = True\n seconds += 1\n check_file = Path(downloaded_file)\n if check_file.is_file():\n print(f'file path : {downloaded_file}')\n\n \"\"\" parse downloaded csv file\n remove downloaded file after parsing\n \"\"\"\n with open(downloaded_file) as df:\n df_reader = csv.reader(df, delimiter=',')\n interesting_row = [row for idx, row in enumerate(df_reader) if idx == 1]\n cusip = interesting_row[0][8]\n ticker = interesting_row[0][7]\n out_writer.writerow([company_name, cik, cusip, '', '', ticker])\n print(f'company: {company_name} cik: {cik} cusip: {cusip} ticker: {ticker}')\n df.close()\n os.remove(downloaded_file)\n\n driver.close()\n driver.switch_to.window(driver.window_handles[0]) # switch in first tab\n else:\n logging.info(f'{cik}\\'s cusip is not parsed.'\n f' It\\'s exist. Manual CUSIP must'\n f' input on {output_file_list[cik_idx]}')\n out_writer.writerow([company_name, cik, '', '', '', ticker])\n except TimeoutException:\n out_writer.writerow([company_name, cik, '', '', '', ticker])\n print(f'Not Founded company: {company_name} cik: {cik} ticker: {ticker}')\n driver.close()\n driver.switch_to.window(driver.window_handles[0])\n except TimeoutException:\n out_writer.writerow([company_name, cik, '', '', '', ticker])\n print(f'Not Founded company: {company_name} cik: {cik} ticker: {ticker}')\n driver.close()\n driver.switch_to.window(driver.window_handles[0]) # switch in first tab\n ##### row_idx += 1\n # driver.close()", "def run_scrapping():\n logging.info(\"Starting the scrapping process...\")\n try:\n # Create an empty list variable.\n search_history = []\n # Run the for to scrap 2000 articles from wikipedia.\n for i in range(2000):\n\n # Send the request to wikipedia with the random url and get the response.\n response = requests.get(base_url)\n\n # Check if the current url is already exist in search_history list or not.\n if str(response.url) not in search_history:\n # if not exist then add it to the list.\n search_history.append(response.url)\n\n # Create the file with write mode and encoding format utf-8.\n f = open(module_directory + \"/DataSet/\" + str(i) + \".txt\", \"w\", encoding=\"utf-8\")\n # And write the response of get_body_content function.\n f.write(get_body_content(response.text))\n\n # Sleep for 2 second for not messing up with wikipedia server.\n sleep(2)\n\n # Save the search_history list which contains all the called urls into the file.\n f_ = open(module_directory + \"/DataSet/url_list.txt\", \"w\")\n f_.write(\"\\n\".join(search_history))\n\n return True\n\n except Exception as e:\n # log the error.\n traceback.print_exc()\n logging.error(\"Error: %s\", e)\n print(\"Error: %s\", e)\n return False", "def internal_url_scraper(url, set_of_urls, list_of_urls):\n\n for url in list_of_urls:\n\n try:\n page = extract_page_html(url)\n html_body = page.decode().split('head><body')[-1]\n\n except:\n pass\n\n for _url in re.findall('href=\".*?\"', html_body):\n\n _url = format_internal_url(_url)\n if _url not in set_of_urls:\n\n set_of_urls.add(_url)\n write_to_file('method1.txt', _url)\n\n if 'medium.com' in _url:\n list_of_urls.append(_url)\n\n # stopping condition\n if len(list_of_urls) > 1000:\n break", "def crawl(self):\n\n #Iteration tracker for checking when to regenerate driver\n iter_ = 0 \n\n #Set DB scan start\n now = datetime.now()\n self.db.set_start(now)\n failures = []\n status = {}\n with open(os.getcwd() + '/scan-status.txt', 'r') as f:\n for line in f.readlines():\n category = line.split(' ')[0]\n pagenum = line.split(' ')[1]\n try:\n pagenum.replace('\\n', '')\n except:\n pass\n status[category] = pagenum\n \n #Iterate through targets\n for target in self.targets:\n if status[target.split('/t5/')[1].split('/')[0]] == 'DONE\\n':\n continue\n if iter_ > 0:\n #Regenerate driver if necessary\n if '-p' not in sys.argv:\n print('Regenerating driver...... \\n')\n self.regenerate_driver()\n # time.sleep(2)\n\n #time.sleep(2)\n\n #Generate a category object from target URL\n category = self.parse_page(target, iter_ + 1)\n\n #If something went wrong with creating the object, throw relevant exception to \n #trigger restart\n if len(category.threadlist) == 0:\n raise DBError\n print(f'\\nCreated CATEGORY: {category.__str__()}')\n\n #Get threads remaining from old cache\n threads = []\n if category.name in self.db.pred.keys():\n for url, thread in self.db.pred[category.name].threads.items():\n if url not in category.threads.keys():\n threads.append(url)\n \n #Go through remaining threads and add parsed objects to category object\n if len(threads) > 0:\n with Bar(f'Finishing remaining threads in category {category.name}', max=len(threads)) as bar:\n for url in threads:\n thread = None\n if '-p' not in sys.argv:\n self.driver.get(url)\n #Attempt to parse thread page\n try:\n thread = self.scraper.parse(self.driver.page_source, url, target.split('/t5/')[1].split('/')[0], iter_)\n #This indicates a thread has been made inaccessible, add it to deleted threads\n except AttributeError:\n if target.split('/t5/')[1].split('/')[0] in self.db.stats.deleted_threads.keys():\n self.db.stats.deleted_threads[target.split('/t5/')[1].split('/')[0]].append(url)\n else:\n self.db.stats.deleted_threads[target.split('/t5/')[1].split('/')[0]] = [url]\n else:\n r = requests.get(url)\n try:\n thread = self.scraper.parse(r.text, url, target.split('/t5/')[1].split('/')[0], iter_)\n #This indicates a thread has been made inaccessible, add it to deleted threads\n except AttributeError:\n if target.split('/t5/')[1].split('/')[0] in self.db.stats.deleted_threads.keys():\n self.db.stats.deleted_threads[target.split('/t5/')[1].split('/')[0]].append(url)\n else:\n self.db.stats.deleted_threads[target.split('/t5/')[1].split('/')[0]] = [url]\n #time.sleep(2)\n category.add(thread)\n bar.next()\n iter_ += 1\n if '-full' not in sys.argv:\n self.db.add(category)\n for elem in failures:\n if elem not in self.db.stats.failures:\n self.db.stats.failures.append(elem)\n return self.db\n else:\n return" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Replace the property on with fxn. This allows you to change the behavior of an existing unrelated class.
def replace_property(cls, obj, target, replacement): Mock.__recall__[(obj,target)]=getattr(obj,target) obj.__dict__[target]=property(replacement)
[ "def prop_proxy(self, prop):\n return self", "def _override(self, name, obj):\n path = name.split('.')\n assert len(path) > 1, 'module name not provided'\n obj_name = path[-1]\n\n objs = self._resolvePath(path[:-1])\n container = objs[-1]\n try:\n original_class = getattr(container, obj_name, None)\n setattr(container, obj_name, obj)\n self._original.append((container, obj_name, original_class))\n except TypeError:\n # We have a static class; we will have to modify its container.\n # This works for global functions in gtk too because their\n # container is an ordinary python module (fake_gtk).\n name = container.__name__\n prev_container = objs[-2]\n subclass = type(name, (container, ), {obj_name: obj})\n setattr(prev_container, name, subclass)\n self._original.append((prev_container, name, container))", "def _replace_function(\n cls, obj: CommonTypes.MLRunInterfaceableType, function_name: str\n ):\n # Get the original function from the object:\n original_function = getattr(obj, function_name)\n\n # Set a backup attribute with for the original function:\n original_function_name = cls._ORIGINAL_ATTRIBUTE_NAME.format(function_name)\n setattr(obj, original_function_name, original_function)\n\n # Get the function to replace from the interface:\n replacing_function_name = cls._REPLACING_ATTRIBUTE_NAME.format(function_name)\n replacing_function = getattr(cls, replacing_function_name)\n\n # Check if the replacing function is a class method (returning a function to use as the replacing function):\n if inspect.ismethod(replacing_function):\n replacing_function = replacing_function()\n\n # Wrap the replacing function with 'functools.wraps' decorator so the properties of the original function will\n # be passed to the replacing function:\n replacing_function = functools.wraps(original_function)(replacing_function)\n\n # If the replacing function is a method and not a function (appears in the _REPLACED_METHODS and not\n # _REPLACED_FUNCTIONS), set the 'self' to the object:\n if function_name in cls._REPLACED_METHODS:\n replacing_function = MethodType(replacing_function, obj)\n\n # Replace the function:\n setattr(obj, function_name, replacing_function)", "def replace_method(the_class, name, replacement, ignore_missing=False):\n try:\n orig_method = getattr(the_class, name)\n except AttributeError:\n if ignore_missing:\n return\n raise\n if orig_method.__name__ == 'replacement_' + name:\n # replacement was done in parent class\n return\n setattr(the_class, name + '_c', orig_method)\n setattr(the_class, name, replacement)", "def _replace_property(\n cls,\n obj: CommonTypes.MLRunInterfaceableType,\n property_name: str,\n property_value: Any = None,\n include_none: bool = False,\n ):\n # Get the original property from the object:\n original_property = getattr(obj, property_name)\n\n # Set a backup attribute with for the original property:\n original_property_name = cls._ORIGINAL_ATTRIBUTE_NAME.format(property_name)\n setattr(obj, original_property_name, original_property)\n\n # Check if a value is provided, if not copy the default value in this interface if None should not be included:\n if not include_none and property_value is None:\n property_value = copy.copy(cls._REPLACED_PROPERTIES[property_name])\n\n # Replace the property:\n setattr(obj, property_name, property_value)", "def __set__(self, instance, value):\r\n setattr(instance, self.hidden_attribute, value)", "def update_properties(self, **props):\n properties = tvtk.Property(**props)\n self.actor.property = properties", "def example_property(self):", "def __set__(self, instance, value):\n instance.__dict__[self.name] = value", "def attr_replaced(original, replacement):\r\n\r\n def fget(self):\r\n manual_warn(\r\n f\"Accessing {original} is deprecated, use {replacement} instead\"\r\n )\r\n return getattr(self, replacement)\r\n\r\n def fset(self, val):\r\n manual_warn(\r\n f\"Accessing {original} is deprecated, use {replacement} instead\"\r\n )\r\n setattr(self, replacement, val)\r\n\r\n doc = f\"Deprecated name for `{replacement}`\"\r\n\r\n return property(fget=fget, fset=fset, doc=doc)", "def copyprops(original_fn, decorated_fn):\n if hasattr(original_fn, '_wsgiwapi_props'):\n decorated_fn._wsgiwapi_props = original_fn._wsgiwapi_props\n if hasattr(original_fn, '__doc__'):\n decorated_fn.__doc__ = original_fn.__doc__", "def _update_class_for_magic_builtins( self, obj, name):\r\n if not (name.startswith('__') and name.endswith('__') and len(name) > 4):\r\n return\r\n original = getattr(obj.__class__, name)\r\n def updated(self, *kargs, **kwargs):\r\n if (hasattr(self, '__dict__') and type(self.__dict__) is dict and\r\n name in self.__dict__):\r\n return self.__dict__[name](*kargs, **kwargs)\r\n else:\r\n return original(self, *kargs, **kwargs)\r\n setattr(obj.__class__, name, updated)\r\n if _get_code(updated) != _get_code(original):\r\n self._create_placeholder_mock_for_proper_teardown(\r\n obj.__class__, name, original)", "def inject(object, f):\n setattr(object, f.__name__, partial(f, object))\n return object", "def renameAttr():\n pass", "def onChanged(self, vp, prop):\n\n App.Console.PrintMessage(\"Change property: \" + str(prop) + \"\\n\")", "def set_property(self, entity, **kwargs):", "def eager_override(self, attribute_name, module_name):\n # By fetching the new attribute now, it has the opportunity to use an\n # existing facade attribute as a base class.\n new_attr = self._get_attr_within_module(attribute_name, module_name)\n # update the import map for good measure\n self.import_map[attribute_name] = module_name\n setattr(self, attribute_name, new_attr)", "def property_observer(self, name):\n\n def wrapper(fun):\n self.observe_property(name, fun)\n fun.unobserve_mpv_properties = lambda: self.unobserve_property(name, fun)\n return fun\n\n return wrapper", "def set_prop(prefix, properties, luxcore_name, property, value):\n key = '.'.join([prefix, luxcore_name, property])\n properties.Set(pyluxcore.Property(key, value))" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reset all back to original methods.
def reset_all(cls): for key in Mock.__recall__.keys(): cls.replace(key[0],key[1],Mock.__recall__[key]) Mock.__recall__ = {}
[ "def reset(self):\n\n for test in self._tests:\n test.reset()", "def _reset(self) -> None:\n self._reset_source()", "def reset_method(self, method_name, run):\n \n run_path = os.path.join(self.root_dir, \n str(run))\n method_path = os.path.join(run_path,\n method_name)\n shutil.rmtree(method_path)\n \n # re-add the same method\n self.add_method(method_name, run)", "def _revert_all(self):\n self._runtime.reset_nodes(self._analyzer.iterate_all_nodes(),\n state=None, intention=st.REVERT)", "def __reset__(self):\n self._values = {}\n self._errors = {}\n self._raw_values = {}\n (f.__reset__() for f in self.__subcontainers__)", "def reset(self, do_resets=None):\n pass", "def reset(self):\n with self.lock:\n self.hooks = dict()", "def reset(self):\n self.clear()\n dict.update(self, self.defaults)", "def reset_events(self):\n self.eventtype = None\n self.keypress = None\n self.mousebutton = 0", "def refiner_reset(self):\n self._refiner_reset = True", "def reset(self):\n for manager in self.managers:\n manager._reset()", "def reset_all(self):\n # sets self.attacks and self.potions to the starting default values of their respective dictionaries for a given entity\n self.attacks = copy.deepcopy(self.starting_attacks)\n self.potions = copy.deepcopy(self.starting_potions)", "def reset(self):\n tcl_name = _get_tcl_name(self.bitfile_name)\n self.gpio_dict = _get_gpio(tcl_name)\n self.ip_dict = _get_ip(tcl_name)\n self.interrupt_controllers, self.interrupt_pins = \\\n _get_interrupts(tcl_name)\n if self.is_loaded():\n PL.reset()", "def _reset_state_wrapper(self):\n self._reset_state_impl()\n self._is_adapted = False", "def reset(self):\n self.aliases = {}", "def reset(self) -> None:\n for (name, indicator) in self.indicators:\n indicator.reset()", "def reset(self):\r\n\r\n print(\"tController: Doing controller reset....\")\r\n # Cancel all timers\r\n for idx, timer in enumerate(self.timers):\r\n if timer != idx:\r\n timer.cancel()\r\n # Release all buttons\r\n for command in self.cmds.keys():\r\n self.__release(command)", "def ResetAllFlags(self):\n for flag in self.GetAllFlags():\n flag.TurnOff()", "def _reset_source(self):" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test record to see that points are applied to the right area. This only works for nonfree point tests.
def test_area_rec(self,rec,area,points): print "Testing %s" % rec.rule.name self.assertEqual(points,rec.points,"Error: Wrong number of points for %s. Should have been %s, was %s" % (rec.rule.name,points,rec.points))
[ "def test_property_points(self):\n self.assertEqual(self.tr1.points,((7, 1), (1, 9), (1, 1)), 'Property did not work')\n self.assertEqual(self.tr2.points,((3.0, 0.0), (0.0, 4.0), (0.0, 0.0)), 'Property did not work')\n self.assertEqual(self.floattest.points, ((3.3, 0.0), (0.2, 4.2), (0.0, 0.0)), 'Property did not work')", "def test_processed_points_calculation(self):\n\n assert self.test_shape.processed_points == [\n (49.937460888595446, 2.5, \"circle\"),\n (43.300748759659555, 25.000903120744287, \"circle\"),\n (27.1320420790315, 41.99824154201773, \"straight\"),\n (77.154447582418, 128.6358861991937, \"circle\"),\n (129.90375269002172, 75.00010024693078, \"circle\"),\n (149.97916521970643, 2.5, \"straight\"),\n (49.937460888595446, 2.5, \"circle\"),\n ]", "def test_pointbasedgrids_post(self):\n pass", "def test_corner_points(self):\n self.assertEqual(self.rectangle.top_left_point, geometry.Point2D(0, 10))\n self.assertEqual(self.rectangle.top_right_point, geometry.Point2D(5, 10))\n\n self.assertEqual(self.rectangle.bottom_left_point, geometry.Point2D(0, 0))\n self.assertEqual(self.rectangle.bottom_right_point, geometry.Point2D(5, 0))", "def test_correct_estimates(self):\n self.assertEqual(self.ajive.common.rank, 1)\n self.assertEqual(self.ajive.blocks['x'].individual.rank, 1)\n self.assertEqual(self.ajive.blocks['y'].individual.rank, 2)", "def check_points(self, points):\r\n for point in points:\r\n if (point > self.spec_lines.lines[0]\r\n or point < self.spec_lines.lines[-1]):\r\n print(\"Point {} out of zone 3\".format(self.x_pt))\r\n elif (point > self.spec_lines.lines[1]\r\n or point < self.spec_lines.lines[-2]):\r\n print(\"Point {} out of zone 2\".format(self.x_pt))\r\n elif (point > self.spec_lines.lines[2]\r\n or point < self.spec_lines.lines[-3]):\r\n# print(\"out of zone 1\")\r\n pass\r\n else:\r\n pass", "def validatePts(sample, pts):\n\t\tnewPts = []\n\t\tfor i, item in enumerate(pts):\n\t\t\tmat, sps = item\n\t\t\tnewItem = (mat, [])\n\t\t\tfor j, sp in enumerate(sps):\n\t\t\t\tprint \"%s\\tS\\t%d\\t%s\\t%d\\t%f\\t%f\" % (sample, i + 1, item[0], j + 1, sp.get(X_AXIS), sp.get(Y_AXIS))\n\t\t\t\t_stg.moveTo(sp)\n\t\t\t\tres = jop.showConfirmDialog(MainFrame, \"Is this point ok for %s?\" % item[0], \"Stage point validation\", jop.YES_NO_CANCEL_OPTION)\n\t\t\t\tif res == jop.YES_OPTION:\n\t\t\t\t\tnewItem[1].append(sp)\n\t\t\t\telif res == jop.NO_OPTION:\n\t\t\t\t\tres == jop.showConfirmDialog(MainFrame, \"Move to a better point and then select Ok to\\nreplace the point or Cancel to delete the point.\", \"Stage point validation\", jop.OK_CANCEL_OPTION)\n\t\t\t\t\tif res == jop.OK_OPTION:\n\t\t\t\t\t\tnewItem[1].append(_stg.getPosition())\n\t\t\t\telse:\n\t\t\t\t\treturn None\n\t\t\tnewPts.append(newItem)\n\t\treturn newPts", "def test_get_final_point():\n assert_true(type(v.final_point) is tuple)", "def test_trapezoidal_area(self):\n \n #simple square\n x1 = 0.0\n x2 = 2.0\n y1 = 2.0\n y2 = 2.0\n\n exp = 4.0\n obs = trapezoidal_area(x1,y1,x2,y2)\n self.assertFloatEqual(obs,exp)\n\n #triangle\n x1 = 1.0\n x2 = 3.0\n y1 = 0.0\n y2 = 2.0\n\n exp = 2.0\n obs = trapezoidal_area(x1,y1,x2,y2)\n self.assertFloatEqual(obs,exp)", "def test_points_from_polygon_and_line(pair):\n p, rp = pair\n centre = rp.args[0]\n assume(p != centre)\n line = Line(p, centre)\n assert len(EuclideanWorld([rp, line]).get_points()) == 2 + rp.args[2]", "def test_corner_points_shifted(self):\n self.rectangle.location = geometry.Point2D(10, 0)\n\n self.assertEqual(self.rectangle.top_left_point, geometry.Point2D(10, 10))\n self.assertEqual(self.rectangle.top_right_point, geometry.Point2D(15, 10))\n\n self.assertEqual(self.rectangle.bottom_left_point, geometry.Point2D(10, 0))\n self.assertEqual(self.rectangle.bottom_right_point, geometry.Point2D(15, 0))", "def testGetArea_trapezoidal_0truth(self):\n self.assertEquals(0, self.trapezoidal_mf.GetArea(0))", "def test_set_final_point():\n point = (42,)\n v.final_point = point\n assert_equal(v.final_point, point)", "def test_refpoints(self):\n self.ld.compute(self.box, self.pos)\n density = self.ld.density\n\n npt.assert_array_less(np.fabs(density - 10.0), 1.5)\n\n neighbors = self.ld.num_neighbors\n npt.assert_array_less(np.fabs(neighbors - 1130.973355292), 200)", "def testarea2(self):\n a = Square(4, 100, 20, 10)\n self.assertEqual(a.area(), 16)", "def test_roc_points(self):\n \n #The set up here is a bit elaborate since I generate the test datasets\n #based on the values we need in the confusion matrix.\n #I test the intermediate results though, so any errors should be due \n #to the actual function, not the test\n \n tn_obs = 0\n tn_exp = 0\n\n fp_obs = 1\n fp_exp = 0\n\n tp_obs = 1\n tp_exp = 1\n\n fn_obs = 0\n fn_exp = 1\n\n #point A\n obs = [tp_obs] * 63 + [fp_obs] *28 + [fn_obs] * 37 + [tn_obs]*72\n exp = [tp_exp] * 63 + [fp_exp] *28 + [fn_exp] * 37 + [tn_exp]*72\n trial_a_results = confusion_matrix_from_data(obs,exp)\n #Check that this is correct\n self.assertEqual(trial_a_results,(63,28,37,72))\n trial_a = (obs,exp)\n \n \n #point B\n obs = [tp_obs] * 77 + [fp_obs] *77 + [fn_obs] * 23 + [tn_obs]*23\n exp = [tp_exp] * 77 + [fp_exp] *77 + [fn_exp] * 23 + [tn_exp]*23\n trial_b_results = confusion_matrix_from_data(obs,exp)\n #Check that this is correct\n self.assertEqual(trial_b_results,(77,77,23,23))\n trial_b = (obs,exp)\n \n #point c\n obs = [tp_obs] * 24 + [fp_obs] *88 + [fn_obs] * 76 + [tn_obs]*12\n exp = [tp_exp] * 24 + [fp_exp] *88 + [fn_exp] * 76 + [tn_exp]*12\n trial_c_results = confusion_matrix_from_data(obs,exp)\n #Check that this is correct\n self.assertEqual(trial_c_results,(24,88,76,12))\n trial_c_results = calculate_accuracy_stats_from_observations(obs,exp)\n #Check that this is correct\n self.assertEqual(trial_c_results[\"false_positive_rate\"],0.88)\n\n trial_c = (obs,exp)\n\n trials = [trial_a, trial_b,trial_c]\n \n \n #Finally the actual test\n\n obs_points = roc_points(trials)\n exp_points = [(0.28,0.63),(0.77,0.77),(0.88,0.24)]\n self.assertFloatEqual(obs_points,exp_points)", "def test_point_validity( generator, x, y, expected ):\n if point_is_valid( generator, x, y ) == expected:\n print_(\"Point validity tested as expected.\")\n else:\n raise TestFailure(\"*** Point validity test gave wrong result.\")", "def checkpts(pts):\n\tnewPts = []\n\tfor i, sp in enumerate(pts):\n\t\tprint \"%d\\t%f\\t%f\\t%f\" % (i + 1, sp.get(X_AXIS), sp.get(Y_AXIS), sp.get(Z_AXIS))\n\t\t_stg.moveTo(sp)\n\t\tres = jop.showConfirmDialog(MainFrame, \"Update this point?\", \"Stage point validation\", jop.YES_NO_OPTION)\n\t\tif res == jop.YES_OPTION:\n\t\t\tnewPts.append(position())\n\t\telse:\n\t\t\tnewPts.append(sp)\n\treturn newPts", "def test_points_from_polygon(rp):\n assert EuclideanWorld([rp]).get_points() == set(rp.vertices)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
computes the evolution between the number of cluster initially and the error rate
def evolution_error_cluster(n_point, dimension, nb_rect_min, nb_rect_max, nb_rect_step): nbrs, fits1, fits2 = [], [], [] for nb_rect in range(nb_rect_min, nb_rect_max, nb_rect_step): print("calcul pour nb_rect = ", nb_rect) fit1, fit2 = experience_between_theoritical_and_learned_cluster(nb_rect, dimension, n_point, False) nbrs.append(nb_rect) fits1.append(fit1) fits2.append(fit2) print("sauvegare réussi pour nb_rect = ", nb_rect) print(' rate false positif ', fits2) print('rate false negatif', fits1) plt.plot(nbrs, fits2, color= 'blue', label = 'false positif ') plt.plot(nbrs, fits1, color = 'red', label = 'false negatif') plt.legend(loc = 'upper right') plt.xlabel('Number of Rectangle') plt.ylabel('Error Rate') plt.title("evolution of the error rate depending on the number of cluster used initially") plt.show()
[ "def calculate_errors(dataset,cluster_indices,predict_energies):\n \n print(\"Calculating errors for each cluster...\")\n\n \n #helping variables\n n_clusters=len(cluster_indices)\n R,F,E=dataset[\"R\"],dataset[\"F\"],dataset[\"E\"]\n mse=[]\n sample_errors=[]\n\n #loop through clusters\n #predict results for each cluster\n #calculate error, save in list\n sys.stdout.write( \"\\r[0/{}] done\".format(n_clusters) )\n sys.stdout.flush()\n for i in range(n_clusters):\n cind=cluster_indices[i] #cluster indices\n cr,cf,ce=R[cind],F[cind],E[cind] #cluster R \n shape=cr.shape\n n_samples,n_atoms,n_dim=shape[0],shape[1],False\n if len(shape)>2:\n n_dim=shape[2]\n \n if predict_energies:\n cf=np.array(ce)\n cf_pred=predict.predict_energies(cr)\n\n else:\n #reshaping\n if n_dim:\n cf=np.reshape(cf,(n_samples,n_atoms*n_dim)) \n else:\n cf=np.reshape(cf,(n_samples,n_atoms)) \n cf_pred=predict.predict(cr)\n\n err=(cf-cf_pred)**2\n sample_errors.append(err.mean(axis=1))\n mse.append(err.mean())\n\n #print out\n sys.stdout.write( \"\\r[{}/{}] done\".format(i+1,n_clusters) )\n sys.stdout.flush()\n \n print(\"\") \n #order the cluster_indices etc\n sorted_ind=np.argsort(mse)\n mse=np.array(mse)\n cluster_indices=np.array(cluster_indices)\n sample_errors=np.array(sample_errors)\n\n return mse[sorted_ind],cluster_indices[sorted_ind],sample_errors[sorted_ind]", "def clustered_error(demean, consist_col, category_col, cluster_col, n, k, k0, rank, nested=False, c_method='cgm', psdef=True):\n if len(cluster_col) == 1 and c_method == 'cgm2':\n raise NameError('cgm2 must be applied to multi-clusters')\n beta_list = []\n xpx = np.dot(demean[consist_col].values.T, demean[consist_col].values)\n # 2020/11/26\n xpx_inv = np.linalg.pinv(xpx)\n demeaned_df = demean.copy()\n G_array = np.array([])\n \n if nested: \n if (len(category_col) == 0 ):\n scale_df = (n - 1) / (n - k - rank)\n else: \n scale_df = (n - 1) / (n - k + k0 - rank ) \n else:\n if (len(category_col) == 0 ): \n scale_df = (n - 1) / (n - k - rank) \n else:\n scale_df = (n - 1) / (n - k + k0 - rank ) \n \n \n if len(cluster_col) == 1:\n G = np.unique(demeaned_df[cluster_col].values).shape[0]\n \n middle = middle_term(demeaned_df, consist_col, cluster_col)\n m = np.dot(xpx_inv, middle)\n beta = np.dot(m, xpx_inv)\n \n scale = scale_df * G / (G - 1)\n beta = scale * beta\n beta_list.append(beta)\n else:\n if c_method == 'cgm':\n for cluster in cluster_col:\n middle = middle_term(demeaned_df, consist_col, [cluster])\n G = np.unique(demeaned_df[cluster].values).shape[0]\n # print('G:',G)\n # print('middle:',middle)\n m = np.dot(xpx_inv, middle)\n beta = np.dot(m, xpx_inv)\n scale = scale_df * G / (G - 1)\n beta = scale * beta\n beta_list.append(beta)\n for j in range(2, len(cluster_col) + 1):\n for combine_name in list(combinations(cluster_col, j)):\n name_list = [e for e in combine_name]\n # print(name_list)\n # print(j)\n new_col_name = ''\n for i in name_list:\n new_col_name = new_col_name + '_' + i\n demeaned_df[new_col_name] = demeaned_df[name_list[0]].apply(str)\n # print('col_name:', new_col_name)\n for i in range(1, len(name_list)):\n # print('col_name:', new_col_name)\n demeaned_df[new_col_name] = demeaned_df[new_col_name] + '_' + demeaned_df[name_list[i]].apply(\n str)\n middle = np.power(-1, j - 1) * middle_term(demeaned_df, consist_col, [new_col_name])\n # print(middle)\n m = np.dot(xpx_inv, middle)\n beta = np.dot(m, xpx_inv)\n G = np.unique(demeaned_df[new_col_name].values).shape[0]\n scale = scale_df * G / (G - 1)\n # print('g:', G)\n beta = scale * beta\n beta_list.append(beta)\n\n elif c_method == 'cgm2':\n for cluster in cluster_col:\n middle = middle_term(demeaned_df, consist_col, [cluster])\n G = np.unique(demeaned_df[cluster].values).shape[0]\n G_array = np.append(G_array, G)\n # print('G:', G)\n m = np.dot(xpx_inv, middle)\n beta = np.dot(m, xpx_inv)\n beta_list.append(beta)\n for j in range(2, len(cluster_col) + 1):\n for combine_name in list(combinations(cluster_col, j)):\n name_list = [e for e in combine_name]\n new_col_name = ''\n for i in name_list:\n new_col_name = new_col_name + '_' + i\n demeaned_df[new_col_name] = demeaned_df[name_list[0]].apply(str)\n for i in range(1, len(name_list)):\n demeaned_df[new_col_name] = demeaned_df[new_col_name] + '_' + demeaned_df[name_list[i]].apply(\n str)\n middle = np.power(-1, j - 1) * middle_term(demeaned_df, consist_col, [new_col_name])\n m = np.dot(xpx_inv, middle)\n beta = np.dot(m, xpx_inv)\n G = np.unique(demeaned_df[new_col_name].values).shape[0]\n G_array = np.append(G_array, G)\n beta_list.append(beta)\n # print(G_array)\n m = np.zeros((k, k))\n if c_method == 'cgm':\n for i in beta_list:\n m += i\n elif c_method == 'cgm2':\n for i in beta_list:\n G_MIN = np.min(G_array)\n scale = scale_df * G_MIN / (G_MIN - 1)\n m += i * scale\n\n if psdef is True and len(cluster_col) > 1:\n m_eigen_value, m_eigen_vector = np.linalg.eig(m)\n m_new_eigen_value = np.maximum(m_eigen_value, 0)\n if (m_eigen_value != m_new_eigen_value).any():\n warnings.warn('Negative eigenvalues set to zero in multi-way clustered variance matrix.')\n m_new = np.dot(np.dot(m_eigen_vector, np.diag(m_new_eigen_value)), m_eigen_vector.T)\n # print('covariance matrix:')\n # print(m_new)\n return m_new\n else:\n # print('covariance matrix:')\n # print(m)\n return m", "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 EEG_surr(cluster1, cluster2, Desired_SNR_dB = 20):\n\tdt = 0.01\n\tn_time = 10000\n\n\tn_chns = 64\n\t\"\"\" C: matrix (n_chns, n_chns) the weight matrix for each pair of channel i and j\"\"\"\n\tC = np.zeros((64,64))\n\t# intra-connection in cluster 1\n\tfor i in range(len(cluster1)):\n\t\ti_chn = cluster1[i]\n\t\tfor j in range(i+1, len(cluster1)):\n\t\t\tj_chn = cluster1[j]\n\t\t\tweight = np.random.uniform(3,5) # weight in range [3 5]\n\t\t\tC[i_chn][j_chn], C[j_chn][i_chn] = weight, weight\n\t\t\tdel weight\n\t# intra-connection in cluster 2\n\tfor i in range(len(cluster2)):\n\t\ti_chn = cluster2[i]\n\t\tfor j in range(i+1, len(cluster2)):\n\t\t\tj_chn = cluster2[j]\n\t\t\tweight = np.random.uniform(3,5) # weight in range [3 5]\n\t\t\tC[i_chn][j_chn], C[j_chn][i_chn] = weight, weight\n\t\t\tdel weight\n\n\t# interconnection\n\tweight = np.random.uniform(1,3) # weight in range [1 3]\n\ti_chn, j_chn = cluster1[-1], cluster2[0]\n\tC[i_chn][j_chn], C[j_chn][i_chn] = weight, weight\n\n\t# Need one more for the initial values\n\tX1 = np.empty((n_chns, n_time + 1))\n\tX2 = np.empty((n_chns, n_time + 1))\n\tX3 = np.empty((n_chns, n_time + 1))\n\n\t# Setting initial values\n\tX1[:,0] = np.random.random((n_chns,))\n\tX2[:,0] = np.random.random((n_chns,))\n\tX3[:,0] = np.random.random((n_chns,))\n\n\t# g, Q, alpha values for each channel\n\tg = np.random.uniform(4.006,4.428,(n_chns,))\n\tQ = np.random.uniform(1.342,1.483,(n_chns,)) \n\talpha = np.random.uniform(0.949,0.999,(n_chns,)) \n\tk = 0.5\n\n\t# Stepping through \"time\".\n\tfor i in range(n_time):\n\t # Derivatives of the X, Y, Z state\n\t for i_chn in range(n_chns):\n\t \tx1, x2, x3 = X1[i_chn, i], X2[i_chn, i], X3[i_chn,i]\n\t \tX2_i = X2[:, i] # samples of all the channels in time i\n\t \tx1_dot, x2_dot, x3_dot = Colpitts(x1, x2, x3, C[i_chn], X2_i, g = g[i_chn], Q = Q[i_chn], alpha = alpha[i_chn], k = k)\n\n\t \tX1[i_chn, i+1] = x1 + (x1_dot * dt)\n\t \tX2[i_chn, i+1] = x2 + (x2_dot * dt)\n\t \tX3[i_chn, i+1] = x3 + (x3_dot * dt)\n\t \tdel x1, x2, x3, X2_i\n\t\n\teeg = X2[:,-501:-1:5] # the transients were dropped out and down-sampled, eeg: n_chns * 100\n\t# add gaussian noise\n\teeg_noisy = np.zeros(eeg.shape)\n\tfor i_chn in range(n_chns):\n\t\teeg_noisy[i_chn,:] = GaussianNoise_SNR(eeg[i_chn,:], Desired_SNR_dB)\n\n\treturn eeg_noisy # eeg_noisy: n_chns * n_times", "def initialize_training(self):\r\n flattened = flatten_image_matrix(self.image_matrix)\r\n count = 0\r\n k = self.num_components\r\n # M step, random prototype vector\r\n initial_means_idx = np.random.choice(flattened.shape[0], k, replace = False)\r\n mu_k = flattened[initial_means_idx]\r\n\r\n while count < 1:\r\n # E step - updating r_nk\r\n squared_dist = np.array([np.square(flattened - mu_k[i]).sum(axis = 1) for i in range(mu_k.shape[0])])\r\n r_nk = np.argmin(squared_dist, axis = 0)\r\n # M step - update mu_k\r\n clusters = np.array([flattened[r_nk == i] for i in range(k)])\r\n mu_k_prev = mu_k\r\n mu_k = np.array([clusters[i].mean(axis = 0) for i in range(k)])\r\n # Convergence test\r\n if np.array_equal(mu_k_prev, mu_k):\r\n count += 1\r\n #print(1/self.num_components)\r\n mixing_coefficient = 1.0/self.num_components\r\n self.means = mu_k.tolist()\r\n self.variances = [1]*self.num_components\r\n self.mixing_coefficients = [mixing_coefficient]*self.num_components", "def kmeans(centres, data, options):\n \n #centres = np.asmatrix(centres)\n #data = np.asmatrix(data)\n ndata, data_dim = data.shape\n ncentres, dim = centres.shape\n\n if dim != data_dim:\n raise Exception('Data dimension does not match dimension of centres')\n\n if ncentres > ndata:\n raise Exception('More centres than data')\n\n # Sort out the options\n if options[13]:\n niters = int(options[13])\n else:\n niters = 100\n\n store = True\n errlog = np.zeros(niters)\n # In netlab version you can have variable number of out\n # argmuments, and choose not to look at the error log\n #store = False\n #if nargout > 3:\n # store = 1\n # errlog = zeros(1, niters)\n\n # Check if centres and posteriors need to be initialised from data\n if options[4] == 1:\n # Do the initialisation\n perm = np.random.permutation(ndata)[0:ncentres]\n\n # Assign first ncentres (permuted) data points as centres\n centres = data[perm, :]\n\n # Matrix to make unit vectors easy to construct\n idy = np.eye(ncentres)\n\n # Main loop of algorithm\n for n in range(niters):\n\n # Save old centres to check for termination\n old_centres = centres\n \n # Calculate posteriors based on existing centres\n d2 = dist2(data, centres)\n # Assign each point to nearest centre\n index = np.argmin(d2, axis=1).flatten()\n minVals = np.min(d2, axis=1)\n post = idy[index, :]\n \n num_points = np.sum(post, axis=0)\n # Adjust the centres based on new posteriors\n for j in range(ncentres):\n if num_points[j] > 0:\n centres[j,:] = data[np.nonzero(post[:, j]), :].sum(1).reshape(-1, 1).T/num_points[j]\n\n # Error value is total squared distance from cluster centres\n e = minVals.sum()\n if store:\n errlog[n] = e\n if options[0] > 0:\n print 'Cycle ', n, ' Error ', e\n\n if n > 1:\n # Test for termination\n if np.abs(centres - old_centres).max() < options[1] and \\\n abs(old_e - e) < options[2]:\n \n options[7] = e\n return centres, post, errlog \n old_e = e\n\n # If we get here, then we haven't terminated in the given number of \n # iterations.\n options[7] = e\n if options[0] >= 0:\n print \"Maximum number of iterations has been exceeded\"\n # Netlab also returns options, but pass by reference\n # here means it is unecessary.\n return centres, post, errlog", "def varnewover(self, i):\n result=[]\n for j in range(int(self.N/(2**i))):\n result.append(np.var(self.clustertrain(i,j)))\n result=np.mean(np.array(result))\n return result", "def calculate_entropy_enthalpy(param_name,param_range,unique_paths,input_params):\n\n dt = float(input_params[0]['dt']);\n\n binding_size = [];\n volume_fraction = numpy.zeros((len(param_range),3))\n PE_all_traj ={};\n entropy_all_traj ={};\n entropy_mean = [];\n scaled_cs_mean = [];\n PE_store_mean = [];\n scaled_cluster_size_all_traj = {};\n count = 0;\n for param in numpy.arange(len(param_range)):\n mypath = unique_paths[param];\n\n (cl_mean,time,header,cl_all) = generate_average_plot(mypath,'cluster',1,return_ind_traj=True);\n (rg_mean,time,header,rg_all) = generate_average_plot(mypath,'cluster',2,return_ind_traj=True);\n (PE_mean,time,header,PE_all) = generate_average_plot(mypath,'PE',1,return_ind_traj=True);\n L_interest = int( numpy.floor(len(time)/1));\n\n (vol_A,vol_B,vol_C) = get_volume_fraction(input_params[param]);\n volume_fraction[param,0] = vol_A;\n volume_fraction[param,1] = vol_B;\n volume_fraction[param,2] = vol_C;\n if input_params[param]['N_A']:\n if input_params[param]['seq_A'].count('A'):\n binding_size.append(input_params[param]['N_A']*(float((input_params[param]['seq_A'].count('A'))))*(1+input_params[param]['N_bs_AB']+input_params[param]['N_bs_AC']));\n else:\n binding_size.append(1.0)\n size_A = int(len(input_params[param]['seq_A']))\n else:\n binding_size.append(1.0);\n size_A = 1;\n\n volume_rest = float(pow(input_params[count]['L'],3)) * (1-numpy.sum(volume_fraction[count,:])) ;\n\n entropy = numpy.multiply(cl_all[:,0:L_interest]-size_A+1,numpy.log(numpy.divide(4/3*numpy.pi*numpy.power(rg_all[:,0:L_interest],3),volume_rest)));\n entropy_mean.append(numpy.mean(entropy,0));\n scaled_cs_mean.append(numpy.mean(numpy.divide(cl_all[:,0:L_interest],binding_size[count]),axis=0));\n PE_store_mean.append(PE_mean)\n PE_all_traj[count] = PE_all;\n entropy_all_traj[count] = entropy;\n scaled_cluster_size_all_traj[count] = numpy.divide(cl_all[:,0:L_interest],binding_size[count])\n count =count+1;\n\n PE_store_mean = numpy.reshape(PE_store_mean,(len(param_range),len(time)))\n\n entropy_mean = numpy.reshape(entropy_mean,(len(param_range),len(time)))\n scaled_cs_mean = numpy.reshape(scaled_cs_mean,(len(param_range),len(time)))\n\n return(PE_all_traj,entropy_all_traj,scaled_cluster_size_all_traj,time*dt,entropy_mean,PE_store_mean,scaled_cs_mean)", "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 graphRemovedErr(points, kvals = [25, 50, 75, 100, 125, 150], cutoff = 0.1):\n # Partition your data set into a training and holdout set, \n # where the holdout set should be 20% of all the points.\n (training, holdout) = randomPartition(points, 0.8)\n # find the total error of the training set\n tot_error_training = []\n tot_error_holdout = []\n for k in kvals:\n tot_error = 0.0\n (clusters, maxDist) = kmeans(training, k, cutoff, County)\n for c in clusters:\n for p in c.getPoints():\n tot_error += (p.distance(c.getCentroid()))**2\n tot_error_training.append(tot_error)\n # Given the holdout set, find the error by calculating \n # the squared distance of each point in the holdout set\n # to its nearest cluster.\n holdout_error = 0.0\n for p in holdout:\n smallestDistance = p.distance(clusters[0].getCentroid())\n index = 0\n # find the closest cluster\n for i in range(len(clusters)):\n distance = p.distance(clusters[i].getCentroid())\n if distance < smallestDistance:\n smallestDistance = distance\n index = i\n holdout_error += smallestDistance**2\n tot_error_holdout.append(holdout_error)\n pylab.plot(kvals, tot_error_training, label=\"Training-set Error\")\n pylab.plot(kvals, tot_error_holdout, label=\"Holdout-set Error\")\n pylab.xlabel('Number of clusters [K value]')\n pylab.ylabel('Value of Total Error')\n pylab.title(\"Error vs K\")\n pylab.legend(loc='best')\n pylab.show()\n \n print tot_error_training\n print tot_error_holdout\n\n # also graph the ratio of the error of the holdout set\n # over the total error of the training set\n ratio_t_h = []\n for i in range(len(tot_error_training)):\n ratio_t_h.append(\n tot_error_holdout[i] / tot_error_training[i]\n )\n pylab.plot(kvals, ratio_t_h, label=\"Ratio of Holdout/Training Total Error\")\n pylab.xlabel('Number of clusters [K value]')\n pylab.ylabel('Ratio of holdout/training total error')\n pylab.title(\"Error Ratio vs K\")\n pylab.legend(loc='best')\n pylab.show()", "def kmeans_agglo(X, r, verbose = False):\n def kmeans_crit(X, r):\n \"\"\" Computes k-means criterion\n Input:\n X: (n x d) data\n r: assignment vector\n Output:\n value: scalar for sum of euclidean distances to cluster centers\n \"\"\"\n local_k= len(np.unique(r)) #number of different values i.e. clusters\n print('There are {} clusters'.format(local_k))\n local_mu = np.zeros((local_k, d))\n for i in range(local_k):\n local_mu[i] = np.mean(X[r == i], axis=0)\n return cdist(X, local_mu, 'euclidean').sum(-1)\n\n n, d = np.shape(X)\n labels = range(n)\n #plotting the data with labels\n if verbose:\n plt.figure(figsize=(6, 6))\n plt.scatter(X[:, 0], X[:, 1],)\n for label, x, y in zip(labels, X[:, 0], X[:, 1]):\n plt.annotate(label,xy=(x, y), xytext=(-3, 3),textcoords='offset points', ha='right', va='bottom')\n plt.show()\n\n if verbose:\n r = [i for i in range(X.shape[0])] #this is just for test, comment this line, to get the r from parameters\n print('r ',r)\n _k = len(np.unique(r)) # number of different values i.e. clusters\n if verbose:\n print('There are {} clusters'.format(_k))\n centroids = np.zeros((_k, d))\n r = np.array(r)\n R, kmloss, mergeidx = [], [], []\n R.append(r)\n for i in range(_k):\n centroids[i] = np.mean(X[r == i], axis=0)\n if verbose:\n print('centroids ', np.shape(centroids))\n kmloss.append(cdist(X, centroids, 'euclidean').sum())\n m = len(centroids)\n while (m > 1):\n if verbose:\n print('Before clustering {} clusters'.format(m))\n print('Centroids: ', np.shape(centroids))\n distance_matrix = cdist(centroids, centroids, 'euclidean')\n #print('distance_matrix ', np.shape(distance_matrix))\n np.fill_diagonal(distance_matrix, np.inf) #fill diagonal with infinity, in order to get the min value (before zero filling, diagonal is zero)\n min_idx = np.where(distance_matrix == distance_matrix.min())[0] #x index where min value\n if verbose:\n print('min_idx ', np.shape(min_idx))\n print('Indices that correspond to min value ',min_idx)\n u = np.unique(r)\n #for i in range(int(len(min_idx)/2)):\n i=0\n val1 = u[min_idx[int(2*i)]]\n val2 = u[min_idx[int(2 * i+1)]]\n r[np.where(r == val2)] = val1\n mergeidx.append([val1, val2]) #save merged indexes\n R.append(r) #save current assignment vector\n\n _k = len(np.unique(r)) # number of different values i.e. clusters\n if verbose:\n print('There are {} clusters'.format(_k))\n print('unique ',np.unique(r))\n centroids = np.zeros((_k, d))\n\n j=0\n for i in np.unique(r):\n centroids[j] = np.mean(X[r == i], axis=0)\n j+=1\n if verbose:\n print('Centroids: ', np.shape(centroids))\n kmloss.append(cdist(X, centroids, 'euclidean').sum()) # save distance loss\n m = len(centroids)\n if verbose:\n print('Current r: ', r)\n print('Current m: ', m)\n print('\\n')\n\n #this is just to check the scipy result\n '''import scipy.cluster.hierarchy as shc\n plt.figure(figsize=(8, 8))\n plt.title('Visualising the data')\n Z = shc.linkage(X, method='ward')\n print('Z shape is ', np.shape(Z))\n Dendrogram = dendrogram((Z))\n plt.show()'''\n\n if verbose:\n print('R ', np.shape(R))\n print('kmloss ',np.shape(kmloss))\n print('mergeidx ', np.shape(mergeidx))\n\n return R, kmloss, mergeidx", "def PerformRS(X,iterationsRS,iterationKmean,clusters):\n \n \n #/* initial solution */\n # option 1. select points ramdomly\n C = SelectRandomRepresentatives(X,clusters)\n P = OptimalPartition(C,X)\n \n #soption 2. elect points from centroid by k-means\n # kmeans = KMeans(n_clusters=clusters, random_state=0).fit(X)\n # P=kmeans.labels_\n # C=kmeans.cluster_centers_\n\n err=ObjectiveFunction(P,C,X)\n print(\"Initial MSE:\",err)\n it=0\n while it <iterationsRS:\n C_new,j= RandomSwap(copy.deepcopy(C),X,clusters)\n P_new= LocalRepartition(copy.deepcopy(P),C_new,X,j)\n P_new,C_new= K_means(P_new,C_new,X,iterationKmean)\n new_err=ObjectiveFunction(P_new,C_new,X)\n if new_err<err :\n P=copy.deepcopy(P_new)\n C=copy.deepcopy(C_new)\n print(\"Iteration:\",it,\"MSE=\",new_err)\n err=new_err\n it+=1\n #print(\"MSE:\",ObjectiveFunction(P,C,X))\n return P,C", "def _loss_function(self):\n\n def vae_loss(y_true, y_pred):\n #print(self.c_current)\n return K.mean(recon_loss(y_true, y_pred) + self.alpha *kl_loss(y_true, y_pred))\n\n def kl_loss(y_true, y_pred):\n return 0.5 * K.sum(K.exp(self.log_var) + K.square(self.mu) - 1. - self.log_var, axis=1)\n\n def kl_loss_monitor0(y_true, y_pred):\n klds = K.mean(K.exp(self.log_var) + K.square(self.mu) - 1. - self.log_var, axis=0)\n return klds[0]\n \n def kl_loss_monitor1(y_true, y_pred):\n klds = K.mean(K.exp(self.log_var) + K.square(self.mu) - 1. - self.log_var, axis=0)\n #K.print_tensor(klds)\n return klds[1]\n \n def kl_loss_monitor2(y_true, y_pred):\n klds = K.mean(K.exp(self.log_var) + K.square(self.mu) - 1. - self.log_var, axis=0)\n #K.print_tensor(klds)\n return klds[2]\n\n def kl_loss_monitor3(y_true, y_pred):\n klds = K.mean(K.exp(self.log_var) + K.square(self.mu) - 1. - self.log_var, axis=0)\n #K.print_tensor(klds)\n return klds[3]\n\n def kl_loss_monitor4(y_true, y_pred):\n klds = K.mean(K.exp(self.log_var) + K.square(self.mu) - 1. - self.log_var, axis=0)\n #K.print_tensor(klds)\n return klds[4]\n\n def recon_loss(y_true, y_pred):\n return 0.5 * K.sum(K.square((y_true - y_pred)), axis=1)\n\n self.vae_optimizer = keras.optimizers.Adam(lr=self.learning_rate)\n self.vae_model.compile(optimizer=self.vae_optimizer, loss=vae_loss, \n metrics=[kl_loss ,recon_loss,kl_loss_monitor0,kl_loss_monitor1,kl_loss_monitor2,kl_loss_monitor3,\n kl_loss_monitor4])", "def consumptionError(xlabel, centroids, compare='total'):\n \n rdlp = centroids.iloc[:,0:24]\n \n if compare == 'total':\n X_dd = pd.concat([xlabel.iloc[:,list(range(0,24))].sum(axis=1), xlabel.iloc[:,-2]], axis=1, keys=['DD','k'])\n rdlp_dd = rdlp.sum(axis=1).rename_axis('k',0).reset_index(name='DD')\n elif compare == 'peak':\n X_dd = pd.concat([xlabel.iloc[:,list(range(0,24))].max(axis=1), xlabel.iloc[:,-2]], axis=1, keys=['DD','k'])\n rdlp_dd = rdlp.max(axis=1).rename_axis('k',0).reset_index(name='DD')\n\n X_dd['ae'] = 0\n X_dd['logq'] = 0\n for y in rdlp_dd.itertuples(): \n X_dd.loc[X_dd.k==y[1],'ae'] = [abs(x-y[2]) for x in X_dd.loc[X_dd.k==y[1],'DD']]\n try:\n #Accommodate zero profiles...\n #X_dd.loc[X_dd.k==y[1],'logq'] = X_dd.loc[X_dd.k==y[1], 'DD'].apply(lambda x : log(y[2]/x) if x!=0 else np.NaN)\n X_dd.loc[X_dd.k==y[1],'logq'] = [log(y[2]/x) for x in X_dd.loc[X_dd.k==y[1],'DD']]\n except ZeroDivisionError:\n print('Zero values. Could not compute log(Q) for cluster', str(y[1]))\n X_dd.loc[X_dd.k==y[1],'logq'] = np.inf\n\n X_dd['ape'] = X_dd.ae/X_dd.DD#.replace(0, np.NaN) #metric is undefined for 0 values;\n X_dd['alogq'] = X_dd['logq'].map(lambda x: abs(x))\n \n mape = X_dd.groupby('k')['ape'].mean()*100\n mdape = X_dd.groupby('k')['ape'].agg(np.median)*100\n mdlq = X_dd.groupby('k')['logq'].agg(np.median)\n mdsyma = np.expm1(X_dd.groupby('k')['alogq'].agg(np.median))*100\n \n del X_dd\n\n #create data to write to file\n write_eval = pd.DataFrame([mape, mdape, mdlq, mdsyma], index=['mape', 'mdape', 'mdlq', 'mdsyma']).T\n write_eval['compare'] = compare\n write_eval['experiment'] = centroids['experiment'].unique()[0]\n write_eval['n_best'] = centroids['n_best'].unique()[0]\n \n cepath = os.path.join(data_dir, 'cluster_evaluation', 'consumption_error.csv')\n if os.path.isfile(cepath):\n write_eval.to_csv(cepath, mode='a', index=True, header=False)\n else:\n write_eval.to_csv(cepath, index=True)\n print('Consumption error output recorded.')\n \n return #mape, mdape, mdlq, mdsyma", "def _num_epochs(num_train):\n # return int(7000 / np.sqrt(num_train))\n return int(2500 / np.sqrt(num_train))", "def _estimate_epsilon(self,D):\n \n print(\"Optimizing epsilon.\"); sys.stdout.flush()\n\n epsilon_list = []\n num_clust_list = []\n noise_list = []\n\n # Go through a large number of values of epsilon \n for i in np.arange(0,np.max(D.dist_matrix),0.1):\n\n # generate clusters at this value of epsilon\n self.epsilon = i\n\n # This check is because dbscan throws an error if epsilon is too small...\n try:\n self.generate_clusters(D)\n except ValueError:\n continue\n\n # record the epsilon, number of clusters, and size of the noise cluster\n epsilon_list.append(i)\n num_clust_list.append(self.num_clusters)\n noise_list.append(len(self.cluster_labels[(self.cluster_labels['cluster'] == -1)].index))\n\n # spit out epsilon optimization if being verbose\n if self.verbose:\n print(epsilon_list[-1],num_clust_list[-1],noise_list[-1])\n sys.stdout.flush()\n \n if self.num_clusters > 1:\n count = self.cluster_labels.groupby(\"cluster\").count()\n count.to_pickle(os.path.join(self.out_path,\"episilon_{:.2e}.pickle\".format(i)))\n\n # If no clusters were found for *any* epsilon, complain\n if len(num_clust_list) < 1:\n err = \"No clusters found for any epsilon. Data set has too few sequences?\\n\"\n raise ValueError(err)\n\n # Normalize the number of clusters to the largest number seen\n clust_thresh = np.array(num_clust_list)/max(num_clust_list)\n\n # Get indices of each epsilon where the number of clusters is above\n # epsilon_size_cutoff.\n indices = np.where(clust_thresh > self.epsilon_size_cutoff)\n\n # Now find values of epsilon that maximize the size of the noise cluster\n max_noise = max([noise_list[i] for i in indices[0]])\n eps = [epsilon_list[i] for i in indices[0] if noise_list[i] == max_noise]\n \n # return the smallest epsilon compatible with this.\n return eps[0]", "def kmeans_loss(data, n_clusters):\r\n data = np.array(data)\r\n data = data.astype('float')\r\n\r\n print(data)\r\n \r\n centroids, mean_loss = kmeans(data, n_clusters)\r\n sum_loss = mean_loss*len(data) # sum loss\r\n idx,_ = vq(np.array(data), centroids)\r\n return sum_loss, mean_loss, centroids, idx", "def experiment(args):\n\n ####################################################################################################################\n # Define experiment parameters\n\n [seed, model_er, obs_un, sys_dim, obs_dim] = args\n\n # state dimension\n #sys_dim = 10\n #obs_dim = 10\n\n # forcing\n f = 8\n\n # number of analyses\n nanl = 100\n\n # analysis time\n tanl = .05\n\n # nonlinear step size\n h = .05\n\n # continous time of the spin period\n spin = 50\n\n # burn in period for the da routine\n burn = 10\n\n # initial value\n np.random.seed(seed)\n x = np.random.multivariate_normal(np.zeros(sys_dim), np.eye(sys_dim) * sys_dim)\n\n ####################################################################################################################\n # generate the truth\n\n # spin the model on to the attractor\n for i in range(int(spin / h)):\n x = l96_rk4_step(x, h, f)\n x += np.random.multivariate_normal(np.zeros(sys_dim), np.eye(sys_dim) * model_er)\n\n # the model and the truth will have the same initial condition\n x_init = x\n\n # generate the full length of the truth trajectory which we assimilate\n truth = np.zeros([sys_dim, nanl])\n\n for i in range(nanl):\n x = l96_rk4_step(x, h, f) + np.random.multivariate_normal(np.zeros(sys_dim), np.eye(sys_dim) * model_er)\n truth[:, i] = x\n\n ####################################################################################################################\n # we simulate EKF for the set observations\n H = alt_obs(sys_dim, obs_dim)\n obs_seed = seed + 10000\n obs = obs_seq(truth, obs_dim, obs_un, H, obs_seed)\n\n P = np.eye(sys_dim) * model_er\n R = np.eye(obs_dim) * obs_un\n Q = np.eye(sys_dim) * model_er\n I = np.eye(sys_dim)\n\n x_fore = np.zeros([sys_dim, nanl])\n x_anal = np.zeros([sys_dim, nanl])\n\n for i in range(nanl):\n # re-initialize the tangent linear model\n Y = np.eye(sys_dim)\n x = l96_rk4_step(x, h, f)\n Y = Y + h * l96_jacobian(x)\n\n # define the forecast state and uncertainty\n x_fore[:, i] = x\n P = ekf_fore(Y, P, Q, R, H, I)\n\n # define the kalman gain and perform analysis\n K = P @ H.T @ np.linalg.inv(H @ P @ H.T + R)\n x = x + K @ (obs[:, i] - H @ x)\n x_anal[:, i] = x\n\n # compute the rmse for the forecast and analysis\n fore = x_fore - truth\n fore = np.sqrt(np.mean(fore * fore, axis=0))\n\n anal = x_anal - truth\n anal = np.sqrt(np.mean(anal * anal, axis=0))\n\n f_rmse = []\n a_rmse = []\n\n for i in range(burn + 1, nanl):\n f_rmse.append(np.mean(fore[:i]))\n a_rmse.append(np.mean(anal[:i]))\n\n ####################################################################################################################\n # save results\n\n data = {'fore': f_rmse, 'anal': a_rmse}\n\n f_name = './data/ekf_bench_rmse_seed_'+ str(seed).zfill(3) + '_analint_' + str(tanl).zfill(3) + \\\n '_sys_dim_' + str(sys_dim).zfill(2) + '_obs_dim_' + str(obs_dim).zfill(2) + \\\n '_obs_un_' + str(obs_un).zfill(3) + '_model_err_' + str(model_er).zfill(3) + '.txt'\n f = open(f_name, 'wb')\n pickle.dump(data, f)\n f.close()", "def __compute_initial_learning_rate__(self):\n eigen_values = np.linalg.eigvalsh(np.cov(self.x_train.T))\n lipschitz = eigen_values[-1] + self.lambd\n initial_learning_rate = 1 / lipschitz\n return initial_learning_rate" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
shows the curse of dimension cad increasing time computation with dimension
def explosion_dimension(dim_mini, dim_max, nb_point, nb_carre): print('lacement calcul') tms, dims = [], [] for dim in range(dim_mini, dim_max): print('dimension de calcul : ', dim) set_point = creation_point_rectangles_2(nb_point, nb_carre, dim) t1 = clock() #ht = mv1_algo(set_point, 10 ) ht = mv1_algo_opti(set_point, nb_carre, distance, 0.2) t2 = clock() tms.append(t2 - t1) dims.append(dim) save = open('result_algo_2.txt', 'a') save.write('\n' + str(dim) + ' '+str(t2 - t1)) print('ecriture ok') save.close() print(tms, dims) plt.plot(dims, tms) plt.xlabel('Dimension') plt.ylabel(' Computing time') plt.title(' Evolution time and dimension for n = 5000 et eps = 0.2') plt.show()
[ "def timespans_dq():\n #date point gets colored value based on average standard deviation of scenes\n #using that date. NOTE: Mask out regions of know signal or else large timespan\n #scenes show high variance.\n print('Not Implemented')", "def show_covid(alpha, delta_t):\n real_t = np.arange(0, 5.01, 0.05)\n real_covid = math.e**(1*real_t)\n plt.plot(*est_covid_first_order(alpha, delta_t), 'r-',\n *est_covid_second_order(alpha, delta_t), 'b-',\n real_t, real_covid, 'k-')\n plt.figlegend(('First Order', 'Second Order', 'Actual'))\n plt.xlabel('Time (days)')\n plt.ylabel('Cases')\n plt.show()", "def get_c_axis(self):\n\n counter = 0\n while counter < len(self.gLineRefList)-1: # -1 because len([1,2,3])=3\n\n start_point = self.lineList[self.gLineRefList[counter]]\n end_point = self.lineList[self.gLineRefList[counter + 1]]\n print(start_point.text)\n if start_point.x == end_point.x and start_point.y == end_point.y: # todo : Dégueulasse , problème lorsque point double\n start_point.point[0] += 0.001\n\n\n start_point.ct = get_angle(get_vector(start_point.point, end_point.point), toolVector) * 180 / math.pi # calculation of ct\n start_point.ct = round(start_point.ct, 3)\n\n counter += 1\n\n if counter == len(self.gLineRefList) - 1:\n self.lineList[self.gLineRefList[counter]].ct = self.lineList[self.gLineRefList[counter-1]].ct\n # the following line apply c axis for G0 command", "def plot_ecc_vector_func_time(time, aei_functime):\n\n avg_ecc = []\n eccentricities = [x.e for x in aei_functime]\n for i in range(len(eccentricities)):\n total = np.sum(eccentricities[i])\n avg_ecc.append(total/float(len(eccentricities[i])) )\n\n\n ecc_vec = []\n\n for i in range(len(aei_functime)):\n sum_massweighted_eccvector_x = 0.\n sum_massweighted_eccvector_y = 0.\n sum_mass = 0.\n for j in range(len(aei_functime[i].mass)):\n sum_mass += aei_functime[i].mass[j] \n sum_massweighted_eccvector_x += aei_functime[i].mass[j] * aei_functime[i].e[j] * np.cos(np.deg2rad(aei_functime[i].pomega[j]))\n sum_massweighted_eccvector_y += aei_functime[i].mass[j] * aei_functime[i].e[j] * np.sin(np.deg2rad(aei_functime[i].pomega[j]))\n\n vector_magnitude = np.sqrt(sum_massweighted_eccvector_x * sum_massweighted_eccvector_x + \n sum_massweighted_eccvector_y * sum_massweighted_eccvector_y)\n ecc_vec.append(vector_magnitude/sum_mass)\n \n fig = pp.figure()\n ax = fig.add_subplot(111)\n ax2 = ax.twinx()\n\n line1 = ax.plot(time, ecc_vec, label = \"Mag ecc vec\")\n line2 = ax2.plot(time, avg_ecc, lw=.35, label = \"avg ecc\", color='red')\n ax.set_xlabel(\"Time (years)\")\n ax.set_ylabel(\"Ecc vector magnitude\")\n ax.set_xscale('log')\n\n ax2.set_ylim((0,2.2*np.max(avg_ecc)))\n ax2.set_ylabel(\"Average eccentricity\")\n ax2.set_xlim(right=3e5)\n\n lines_for_legend = line1 + line2\n fig.legend(lines_for_legend, [l.get_label() for l in lines_for_legend], loc='upper left')\n\n return fig", "def visualize(self):\n plt.figure()\n plt.plot(self.stats_time, self.num_cores)\n plt.ylabel('total num cores used')\n savefig('{fp}/cores_used.jpeg'.format(fp=self.final_path))\n plt.close()\n del self.stats_time\n del self.num_cores\n\n print \"25th Percentile of Delayed VMs: \", float(np.percentile(self.cdf, 25) / 47657184) * 100\n print \"50th Percentile of Delayed VMs: \", float(np.percentile(self.cdf, 50) / 47657184) * 100\n print \"75th Percentile of Delayed VMs: \", float(np.percentile(self.cdf, 75) / 47657184) * 100\n print \"90th Percentile of Delayed VMs: \", float(np.percentile(self.cdf, 90) / 47657184) * 100\n print \"95th Percentile of Delayed VMs: \", float(np.percentile(self.cdf, 95) / 47657184) * 100\n print \"99th Percentile of Delayed VMs: \", float(np.percentile(self.cdf, 99) / 47657184) * 100\n\n print \"Number of Delayed VMs: \", self.cdf[-1]-self.cdf[0]\n print \"Number of max delayed VMs: \", self.values[-1]\n print \"Max Delay Time of a VM: \", self.keys[-1]\n\n plt.figure()\n plt.plot(self.keys, self.cdf)\n plt.ylabel('CDF (in number of vms delayed)')\n plt.xlabel('Delay (in seconds)')\n savefig('{fp}/cdf_vms.png'.format(fp=self.final_path), dpi=1000)\n plt.close()\n\n plt.figure()\n plt.plot(self.keys, (self.cdf / float(self.cdf[-1])) * 100)\n plt.ylabel('CDF (in percentage)')\n plt.xlabel('Delay (in seconds)')\n savefig('{fp}/cdf_vms_percentage.png'.format(fp=self.final_path), dpi=1000)\n plt.close()\n\n # plt.bar not working with large inputs.\n \"\"\"plt.figure()\n plt.bar(keys,values,width=1.0, color='g')\n plt.ylabel('Number of Vms')\n plt.xlabel('Delay in seconds')\n savefig('{fp}/histogram_vms.png'.format(fp=self.final_path),dpi=1000)\n plt.close()\"\"\"\n\n #####\n \"\"\"\n plt.figure()\n plt.plot(self.data_obj.stats_time, self.data_obj.amount_ram)\n plt.ylabel('total amount of ram used')\n savefig('{fp}/ram_used.jpeg'.format(fp=self.final_path))\n plt.close()\n plt.figure()\n \n plt.plot(self.data_obj.creation_stats_time, self.data_obj.cores_creation_lst)\n plt.ylabel('Cores Requested')\n savefig('{fp}/cores_requested.jpeg'.format(fp=self.final_path))\n plt.close()\n plt.figure()\n plt.plot(self.data_obj.creation_stats_time, self.data_obj.ram_creation_lst)\n plt.ylabel('RAM Requested')\n savefig('{fp}/ram_requested.jpeg'.format(fp=self.final_path))\n plt.close()\n plt.figure()\n plt.plot(self.data_obj.deletion_stats_time, self.data_obj.cores_deletion_lst)\n plt.ylabel('Cores Deleted')\n savefig('{fp}/cores_deletion.jpeg'.format(fp=self.final_path))\n plt.close()\n plt.figure()\n plt.plot(self.data_obj.deletion_stats_time, self.data_obj.ram_deletion_lst)\n plt.ylabel('RAM Deleted')\n savefig('{fp}/ram_deletion.jpeg'.format(fp=self.final_path))\n plt.close()\n\n del self.data_obj.creation_stats_time[0]\n del self.data_obj.cores_creation_lst[0]\n del self.data_obj.ram_creation_lst[0]\n plt.figure()\n plt.plot(self.data_obj.creation_stats_time, self.data_obj.cores_creation_lst)\n plt.ylabel('Cores Requested')\n savefig('{fp}/cores_requested_new.jpeg'.format(fp=self.final_path))\n plt.close()\n plt.figure()\n plt.plot(self.data_obj.creation_stats_time, self.data_obj.ram_creation_lst)\n plt.ylabel('RAM Requested')\n savefig('{fp}/ram_requested_new.jpeg'.format(fp=self.final_path))\n plt.close()\n\n del self.data_obj.deletion_stats_time[-1]\n del self.data_obj.cores_deletion_lst[-1]\n del self.data_obj.ram_deletion_lst[-1]\n plt.figure()\n plt.plot(self.data_obj.deletion_stats_time, self.data_obj.cores_deletion_lst)\n plt.ylabel('Cores Deleted')\n savefig('{fp}/cores_deletion_new.jpeg'.format(fp=self.final_path))\n plt.close()\n plt.figure()\n plt.plot(self.data_obj.deletion_stats_time, self.data_obj.ram_deletion_lst)\n plt.ylabel('RAM Deleted')\n savefig('{fp}/ram_deletion_new.jpeg'.format(fp=self.final_path))\n plt.close()\n \"\"\"\n ######", "def timescale(self):\n raise NotImplementedError", "def plotCostVsIterations(JVals):\n plt.figure()\n # plt.xkcd()\n plt.plot(JVals)\n plt.xlabel('iterations')\n plt.ylabel('cost')\n plt.title('gradient descent performance')\n plt.show()", "def vizualize_accumulation():\n\n global b,V,I,w,dt,f,t\n n = 10\n b = 2.2\n V = 2\n I = 1\n w = 2.*np.pi\n dt = 0.05\n eps_array = np.zeros(n) #store deviation\n num_periods = 5\n P = 2.*np.pi/w # one period\n T = np.linspace(1,P*num_periods,n)\n\n f = ode_source_term(f_numerical(b, V, I, t)) \n f_ = sym.lambdify(t,f)\n\n for i in range(0,n):\n u_num, t_num = solver(I=I, w=w, dt=dt, T=T[i], V=V, f=f_)\n\n u_analytic = f_numerical(b, V, I, t_num)\n eps_array[i] = np.abs(u_num - u_analytic(t_num)).max()\n\n plt.plot(T,eps_array)\n plt.xlabel('dt')\n plt.ylabel('deviation')\n plt.title('Accumulation of error with increase in T')\n umin = 1.2*eps_array.min(); umax = 1.2*eps_array.max()\n plt.axis([T[0], T[-1], umin, umax])\n plt.show()", "def curriculum(i):\n if i < EPOCH:\n # return 4+2*complexity*i/EPOCH\n return 2+2*i/10\n else:\n return 99999", "def timeFlow(self):", "def granularity():", "def viscous_timescale(r):\n \n t_viscous = (2 * np.pi) * r ** (3.0 / 2.0) / ((H_over_R ** 2.0) * alpha)\n return t_viscous", "def PlotIdealCellGrowth():\n\n # Make vectors:\n def MakeVectors(cells_start, doubling_time):\n movie_time = 80\n cell_list = [cells_start]\n time_list = [0]\n\n while time_list[-1] < movie_time:\n cell_list.append(cell_list[-1] * 2)\n time_list.append(time_list[-1] + doubling_time)\n\n return (cell_list, time_list)\n\n # Initiate the figure:\n fig = plt.figure()\n plt.xlabel(\"Time [hours]\")\n plt.ylabel(\"Cell count\")\n plt.title(\"Ideal Cell Growth per movie\")\n\n # Plot the dependencies:\n cells_start = [120, 140, 160, 180, 200]\n doubling_time = [16, 18, 20, 22, 24]\n\n for i in cells_start:\n for j in doubling_time:\n cell_list, time_list = MakeVectors(cells_start=i, doubling_time=j)\n plt.plot(time_list, cell_list, \"-o\", label=\"{} cells; {} hrs\".format(i, j))\n plt.legend(loc=\"upper left\")\n plt.show()\n plt.close()", "def moth_demo(dt=0.01, t_max = 15, draw_iter_interval=20):\n \n \n # define simulation region\n wind_region = models.Rectangle(0., -2., 10., 2.)\n sim_region = models.Rectangle(0., -1., 4., 1.)\n #call moth model, set simulation region and starting position \n moth_model = mothpy_models.MothModular(sim_region, 450.0, 750.0,2, 'carde2',1)\n \"\"\"\n nav,cast,wait\n benelli - 2,3,1\n Liberzon - 'alex',2,1\n large sweeps - 1, 'carde2',1\n\n \"\"\"\n #moth_model.speed = moth_model.speed*0.5\n #moth_model.lamda =0.7\n \n # set up wind model\n wind_model = models.WindModel(wind_region, 21, 11,noise_gain=0, u_av=1.,char_time =6,amplitude=0.3)\n # set up plume model\n plume_model = models.PlumeModel(sim_region, (0.1, 0., 0.), wind_model,\n centre_rel_diff_scale=0.3,\n puff_release_rate=100,\n puff_init_rad=0.001,puff_spread_rate=0.0001)\n\n # set up figure\n fig, time_text = _set_up_figure('Moth flying in Concentration field')\n # display initial concentration field as image\n #set concetration array generator\n array_gen = processors.ConcentrationArrayGenerator(sim_region, 0.01, 500,\n 1000, 1.)\n # display initial concentration field as image\n conc_array = array_gen.generate_single_array(plume_model.puff_array)\n im_extents = (sim_region.x_min, sim_region.x_max,\n sim_region.y_min, sim_region.y_max)\n #conc_im is the displayed image of conc_array\n conc_im = plt.imshow(conc_array.T, extent=im_extents, vmin=0, vmax=3e4,\n cmap=cm.binary_r)\n conc_im.axes.set_xlabel('x / m')\n conc_im.axes.set_ylabel('y / m')\n\n # define update and draw functions\n\n def update_func(dt, t):\n wind_model.update(dt)\n plume_model.update(dt)\n #moth_model.update(dt) moth model should have an update method, even if just for syntax sake\n moth_model.update(array_gen.generate_single_array(plume_model.puff_array),wind_model.velocity_at_pos(moth_model.x,moth_model.y),0.01)\n #calculate proximity between moth and source\n if np.sqrt(moth_model.x**2+(moth_model.y-250)**2)<20:\n print \"And they lived happily ever after\"\n \"\"\"\n #allow semi-infinite borders\n if moth_model.x<0:\n moth_model.x = 499 - moth_model.x\n if moth_model.x>499:\n moth_model.x = moth_model.x - 499\n if moth_model.y<0:\n moth_model.y = 499 - moth_model.y\n if moth_model.y>499:\n moth_model.y = moth_model.y - 499\n \"\"\"\n \n #moth_model.moth_array takes both models as input, calculates moth position and adds that poisition(matrix addition) to the input\n #set _data then updates the plot image using the new matrix \n draw_func = lambda: conc_im.set_data(\n moth_model.moth_array(array_gen.generate_single_array(plume_model.puff_array),wind_model))\n # start simulation loop\n _simulation_loop(dt, t_max, time_text, draw_iter_interval, update_func,\n draw_func)\n return fig", "def curve_convergence(self):\n fig, ax = plt.subplots(1, 1, figsize=(20,15)) \n\n title = r'%d iterations ' % max(self.adjoint.iterations)\n title += 'at learning rate $\\gamma = %.1f$' % self.adjoint.lr\n self.subplot_solution_descent(ax, title)\n ax.legend(loc='upper center', ncol=2)\n\n plt.show()\n plt.close()", "def time_update(self):\r\n self.time = []\r\n t = [0] + self.time_final_all_section()\r\n for i in range(self.number_of_section):\r\n self.time.append((t[i+1] - t[i]) / 2.0 * self.tau[i]\r\n + (t[i+1] + t[i]) / 2.0)\r\n return np.concatenate([i for i in self.time])", "def _cfl_time_step(self):\n max_water_depth = np.amax(self._depth, initial=_MICRO_DEPTH)\n max_diffusivity = self._vel_coef * max_water_depth**_SEVEN_THIRDS\n return self._cfl_param / max_diffusivity", "def oneD_graph(S,N,t,Time_,i):\n \n oscillators = np.arange(0,N,1)\n \n plt.figure()\n \n for x in Time_:\n \n plt.figure()\n \n for i in oscillators:\n plt.scatter(i,S[i][x])\n plt.title(\"t_index={}\".format(x))\n plt.xlabel(\"i\")\n plt.ylabel(\"$S_{i}^{q,n}(t)$\") \n \n \n plt.figure()\n\n plt.plot(t,S[i,:])\n plt.title(\"Shannon entropy\")\n plt.xlabel(\"t\")\n plt.ylabel(\"$S_{i}^{q,n}(t)$\")", "def plot_average_ecc_func_time(time_values_to_use,ecc_values_to_use,num_body_func_time,second_time=None,ce_to_plot=None):\n\n avg_ecc = []\n max_ecc = []\n for i in range(len(ecc_values_to_use)):\n max_ecc.append(max(ecc_values_to_use[i]) )\n total = np.sum(ecc_values_to_use[i])\n avg_ecc.append(total/float(len(ecc_values_to_use[i])) )\n\n\n fig = pp.figure()\n\n ax = fig.add_subplot(111)\n ax2 = ax.twinx()\n\n line1 = ax.plot(time_values_to_use,avg_ecc,label='<e>',lw=0.5,color='red')\n line2 = ax.plot(time_values_to_use,max_ecc,label='max e',lw=0.5,color='cyan')\n\n if second_time == None:\n second_time = time_values_to_use\n line3 = ax2.step(second_time,num_body_func_time,where='post',lw=2.2,label='numbodies',color='blue')\n ax.set_xscale('log')\n ax.set_xlabel('Time (years)')\n ax.set_ylabel('ecc. of final planets')\n ax2.set_ylabel('Num bodies outside Roche')\n\n lines_for_legend = line1 + line2 + line3\n fig.legend(lines_for_legend, [l.get_label() for l in lines_for_legend], loc='best')\n\n if ce_to_plot != None:\n ax.scatter( ce_to_plot, [0.002]*len(ce_to_plot), marker=markers.CARETUP,color='red')\n\n #ax.plot((1.5e4,1.5e4),(0,0.05))\n ax.set_ylim(bottom=0)\n return fig" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
shows the evolution of the cost depending on the numbered of merged rectangle in the cluster at each step
def evolution_nb_rectangle_cost(nb_point, nb_rectangle, dimension): set_point = creation_point_rectangles(nb_point, nb_rectangle, dimension) Y, X = evolution_cost(set_point, 0.05) plt.plot(X, Y) plt.xlabel('number of learned rectangles') plt.ylabel('cost function') plt.title('evolution of a cost function depending on number of learned rectangles') plt.show()
[ "def evolution_error_cluster(n_point, dimension, nb_rect_min, nb_rect_max, nb_rect_step):\n \n nbrs, fits1, fits2 = [], [], []\n for nb_rect in range(nb_rect_min, nb_rect_max, nb_rect_step):\n print(\"calcul pour nb_rect = \", nb_rect)\n fit1, fit2 = experience_between_theoritical_and_learned_cluster(nb_rect, dimension, n_point, False)\n nbrs.append(nb_rect)\n fits1.append(fit1)\n fits2.append(fit2)\n print(\"sauvegare réussi pour nb_rect = \", nb_rect) \n print(' rate false positif ', fits2)\n print('rate false negatif', fits1)\n plt.plot(nbrs, fits2, color= 'blue', label = 'false positif ')\n plt.plot(nbrs, fits1, color = 'red', label = 'false negatif')\n plt.legend(loc = 'upper right')\n plt.xlabel('Number of Rectangle')\n plt.ylabel('Error Rate')\n plt.title(\"evolution of the error rate depending on the number of cluster used initially\")\n plt.show()", "def evolution_cost(set_point, eta):\n #find the perfect hash table\n hash_table = epsilon_variation_algo(set_point, len(set_point))\n \n #define the minimal number of rectangle\n min_nb_rectangle = sqrt(len(set_point))\n couts = []\n valeur_nb_rectangle = []\n\n #convert the hash table in a set of rectangles\n set_rectangle = [minimum_rect(hash_table[key]) for key in hash_table.keys()]\n #apply the NN algorithm while the condition is not False\n i = 0 \n while True:\n #find the NN\n #afficher_plsr_pts_rect_1(set_rectangle, None, i)\n nearest_neighboor = naive_nearest_neighboor(set_rectangle)\n #if the merge of the NN is better than heta or there is enough rectangle\n #if merge_bonus(nearest_neighboor) > heta or len(set_rectangle) > min_nb_rectangle:\n i+=1\n couts.append(cost_rectangle(set_rectangle))\n valeur_nb_rectangle.append(len(set_rectangle))\n\n if len(set_rectangle) > 2:\n #merge the NN\n set_rectangle = merge_rectangle(nearest_neighboor, set_rectangle)\n #stop the algorithm\n else:\n return couts, valeur_nb_rectangle", "def unionfind_cluster_editing(filename, output_path, missing_weight, n, x):\n n_merges = 1\n merge_filter = 0.1\n repair_filter = 0.9\n union_threshold = 0.05\n big_border = 0.3\n graph_file = open(filename, mode=\"r\")\n\n\n### Preprocessing ###\n# Knotengrade berechnen je Knoten (Scan über alle Kanten)\n node_dgr = np.zeros(n, dtype=np.int64)\n\n for line in graph_file:\n # Kommentar-Zeilen überspringen\n if line[0] == \"#\":\n continue\n splitted = line.split()\n nodes = np.array(splitted[:-1], dtype=np.int64)\n weight = np.float64(splitted[2])\n\n # Falls Kante 'existiert' nach Threshold:\n if weight > 0:\n node_dgr[nodes[0]] += 1\n node_dgr[nodes[1]] += 1\n\n# Sequentiell für alle Lösungen (alle UF-Strukturen gleichzeitig, oder zumindest so viele wie passen):\n# Größe einer Lösung: Array mit n Einträgen aus je 64bit\n### Generate Solutions ###\n parents = np.full((x,n), np.arange(n, dtype=np.int64))\n sizes = np.zeros((x,n), dtype=np.int64)\n # Modellparameter einlesen:\n parameters_b = load_model_flexible_v2('params_below_100.csv')\n parameters_a = load_model_flexible_v2('params_above_100.csv')\n #cluster_count = np.full(x, n, dtype=np.int64)\n # Alle Parameter für die Modelle festlegen:\n cluster_model = np.full(x,17)\n def generate_solutions(first, c_opt):\n if first:\n k = int(x/37)\n j = 0\n c = 0\n\n for i in range(0,x):\n cluster_model[i] = c\n j += 1\n if j == k and c < 36:\n c += 1\n j = 0\n if not first:\n # Überschreibe Lösungen mit nicht-optimalem Parameter um danach neue zu generieren\n for i in range(0,x):\n if cluster_model[i] != c_opt:\n parents[i] = np.arange(n, dtype=np.int64)\n\n # 2. Scan über alle Kanten: Je Kante samplen in UF-Strukturen\n graph_file = open(filename, mode=\"r\")\n\n for line in graph_file:\n # Kommentar-Zeilen überspringen\n if line[0] == \"#\":\n continue\n splitted = line.split()\n nodes = np.array(splitted[:-1], dtype=np.int64)\n weight = np.float64(splitted[2])\n\n guess_n = (node_dgr[nodes[0]] + node_dgr[nodes[1]]) / 2\n\n decision_values = rand.rand(x)\n for i in range(0, x):\n if not first:\n if cluster_model[i] == c_opt:\n # Ändere in 2. Lauf nichts an den Lösungen, die bereits gut sind!\n continue\n # Samplingrate ermitteln\n sampling_rate = model_flexible_v2(parameters_b, parameters_a, guess_n, cluster_model[i])\n # Falls Kante gesamplet...\n if decision_values[i] < sampling_rate:\n # ...füge Kante ein in UF-Struktur\n rem_union(nodes[0], nodes[1], parents[i])\n\n generate_solutions(True, 0)\n\n\n\n### Solution Assessment ###\n# Nachbearbeitung aller Lösungen: Flache Struktur (= Knoten in selbem Cluster haben selben Eintrag im Array)\n# Und Berechnung benötigter Kanten je Cluster (n_c * (n_c-1) / 2) pro UF\n\n def calculate_costs(solutions_parents, x, merged):\n\n solution_costs = np.zeros(x, dtype=np.float64)\n vertex_costs = np.zeros((x,n), dtype=np.float64)\n c_edge_counter = np.zeros((x,n), dtype=np.int64)\n inner_sizes = np.zeros((x,n), dtype=np.int64)\n\n for i in range(x):\n for j in range(n):\n root = flattening_find(j,solutions_parents[i])\n inner_sizes[i, root] += 1\n for j in range(n):\n root = solutions_parents[i, j]\n n_c = inner_sizes[i, root]\n c_edge_counter[i, j] = n_c - 1\n\n # 3. Scan über alle Kanten: Kostenberechnung für alle Lösungen (Gesamtkosten und Clusterkosten)\n graph_file = open(filename, mode=\"r\")\n\n for line in graph_file:\n # Kommentar-Zeilen überspringen\n if line[0] == \"#\":\n continue\n splitted = line.split()\n nodes = np.array(splitted[:-1], dtype=np.int64)\n weight = np.float64(splitted[2])\n\n for i in range(0,x):\n if not merged:\n root1 = find(nodes[0],solutions_parents[i])\n root2 = find(nodes[1],solutions_parents[i])\n else:\n root1 = solutions_parents[i, nodes[0]]\n root2 = solutions_parents[i, nodes[1]]\n # Kante zwischen zwei Clustern\n if root1 != root2:\n # mit positivem Gewicht (zu viel)\n if weight > 0:\n vertex_costs[i, nodes[0]] += weight / 2\n vertex_costs[i, nodes[1]] += weight / 2\n solution_costs[i] += weight\n # Kante innerhalb von Cluster\n else:\n # mit negativem Gewicht (fehlt)\n if weight < 0:\n vertex_costs[i, nodes[0]] -= weight / 2\n vertex_costs[i, nodes[1]] -= weight / 2\n solution_costs[i] -= weight\n c_edge_counter[i, nodes[0]] -= 1\n c_edge_counter[i, nodes[1]] -= 1\n #print(\"missing edges for now: \", c_edge_counter[i][root1])\n\n for i in range(0,x):\n # über Cluster(-Repräsentanten, Keys) iterieren:\n for j in range(n):\n missing_edges = c_edge_counter[i, j]\n if missing_edges > 0:\n # Kosten für komplett fehlende Kanten zur Lösung addieren\n vertex_costs[i, j] += missing_edges * (-missing_weight) * 0.5\n solution_costs[i] += missing_edges * (-missing_weight) * 0.5 # Zwei Knoten innerhalb eines Clusters vermissen die selbe Kante, daher *0.5 bei Berechnung über die Knoten\n return (vertex_costs, solution_costs, inner_sizes)\n costs = calculate_costs(parents, x, False)\n vertex_costs = costs[0]\n solution_costs = costs[1]\n sizes = costs[2]\n\n### Solution Merge ###\n\n# Mithilfe der Bewertungen/Kosten Lösungen sinnvoll mergen/reparieren\n# Platzhalter: Beste Lösung direkt übernehmen\n\n mean_costs_c = np.zeros(37, dtype=np.float64)\n c_count = np.zeros(37, dtype= np.int64)\n # Summierte Kosten für selben Parameter\n for i in range(x):\n c = cluster_model[i]\n mean_costs_c[c] = mean_costs_c[c] + solution_costs[i]\n c_count[c] += 1\n # Teilen durch Anzahl Lösungen mit dem Parameter\n for i in range(37):\n mean_costs_c[i] = mean_costs_c[i]/c_count[i]\n # c_opt ist Parameter mit geringsten Durchschnittskosten der Lösungen\n c_opt = np.argsort(mean_costs_c)[0]\n\n generate_solutions(False, c_opt)\n costs = calculate_costs(parents, x, False)\n vertex_costs = costs[0]\n solution_costs = costs[1]\n print_solution_costs(solution_costs, output_path)\n # Optimierung: Filtern der \"besten\" Lösungen, um eine solidere Basis für den Merge zu schaffen.\n # best_costs_i = np.argmin(solution_costs)\n # best_costs = solution_costs[best_costs_i]\n # good_costs_i = np.where(solution_costs <= best_costs * 1.7)\n # Variante 2: Beste 10% verwenden\n top_percent = range(np.int64(x*merge_filter))\n mid_percent = range(np.int64(x*repair_filter))\n cost_sorted_i = np.argsort(solution_costs)\n good_costs_i = cost_sorted_i[top_percent]\n mid_costs_i = cost_sorted_i[mid_percent]\n # Artefakt aus Zeit mit n_merges > 1; sonst inkompatibel mit calculate_costs.\n merged_solutions = np.full((n_merges,n), np.arange(n, dtype=np.int64))\n final_solutions = np.full((n_merges,n), np.arange(n, dtype=np.int64))\n merged_sizes = np.zeros((n_merges,n), dtype=np.int64)\n for i in range(0,n_merges):\n merged = merged_solution_scan(solution_costs[good_costs_i], vertex_costs[good_costs_i], parents[good_costs_i], sizes[good_costs_i], missing_weight, n, filename, union_threshold)\n merged_save = np.copy(merged)\n merged_solutions[i] = merged\n merged_c = calculate_costs(merged_solutions, n_merges, True)\n merged_costs = merged_c[1]\n merged_vc = merged_c[0]\n #merged_to_file(merged_solutions, merged_costs, filename, missing_weight, n, len(good_costs_i), n_merges)\n # Glätten der Lösung + Berechnung der korrekten merged_sizes (vorher 0, innerhalb calculate_costs berechnet aber nicht verändert)\n print_result(output_path, \"merged_costs_v5.txt\", merged_costs[0])\n for j in range(0,n):\n r = flattening_find(j, merged_solutions[i])\n merged_sizes[i, r] += 1\n rep = repair_merged_v4_nd_rem(merged_solutions[i], merged_sizes[i], solution_costs[mid_costs_i], vertex_costs[mid_costs_i], parents[mid_costs_i], sizes[mid_costs_i], n, node_dgr, big_border, filename)\n merged_solutions[i] = rep\n merged_c = calculate_costs(merged_solutions, n_merges, True)\n merged_costs = merged_c[1]\n rep_vc = merged_c[0]\n print_result(output_path, \"rep_v5.txt\", merged_costs[0])\n final_solutions[0] = undo_merge_repair(merged_save, rep, merged_vc[0], rep_vc[0])\n final_costs = calculate_costs(final_solutions, 1, True)[1]\n print_result(output_path, \"final_v5.txt\", final_costs[0])\n # Da Merge auf x2 Lösungen basiert, nur diese angeben:\n x2 = len(mid_costs_i)\n #merged_to_file(merged_solutions, merged_costs, filename, missing_weight, n, x2, n_merges)\n merged_to_file(final_solutions, final_costs, filename, missing_weight, n, x2, n_merges, output_path)\n #all_solutions(solution_costs[good_costs_i], parents[good_costs_i], filename, missing_weight, n)\n #print_solution_costs(solution_costs[good_costs_i], filename)\n #merged_short_print(merged_solutions, merged_costs, filename, missing_weight, n, x2, n_merges)", "def compose_cl_view(glyphs, clusters, labels, width, margins_tblr, hs, vs):\n\n counts = Counter()\n for cl in clusters:\n counts[cl] += 1\n cl_by_size = counts.most_common(None)\n\n # image interior width\n iw = width - margins_tblr[2] - margins_tblr[3]\n lmarg = margins_tblr[2]\n tmarg = margins_tblr[0]\n\n # glyph width and height\n gw = glyphs[0].shape[0]\n gh = glyphs[0].shape[1]\n\n ###gc = [None]*len(glyphs) # which cluster each glyph assigned to\n\n def advance(x, y):\n x += gw+hs\n if x >= iw:\n x = hs\n y += gh+vs\n return (x, y)\n \n # pre-allocate positions of glyphs within clusters\n # ranked by descending cluster size\n cl_render_positions = [None]*(len(cl_by_size)+1)\n red_markers = [None]*len(cl_by_size)\n y = vs\n x = hs\n for i, (cl, count) in enumerate(cl_by_size):\n cl_rp = [None]*count\n for j in range(count):\n cl_rp[j] = (x,y)\n x, y = advance(x, y)\n x, y = advance(x, y) \n red_markers[i] = (x,y)\n x, y = advance(x, y)\n cl_render_positions[cl] = cl_rp\n \n height = y+vs+gh+margins_tblr[0] + margins_tblr[1]\n img = np.zeros((height, width, 3), dtype=np.uint8)\n\n # fill the image\n\n # first the glyphs, via the clusters\n cl_used = [0]*(1+len(cl_by_size)) # indexes through each cluster\n for glyph_index, cl in enumerate(clusters):\n # for each glyph, which cluster (origin-1 indexing!!) it's in\n try:\n (x, y) = cl_render_positions[cl][cl_used[cl]]\n except IndexError:\n print \"*ouch(%d)*\" % cl\n continue\n x += lmarg\n y += tmarg\n cl_used[cl] += 1\n gl = glyphs[glyph_index]\n if gl is None:\n continue\n if labels[glyph_index] is None:\n colors = [0,1,2]\n else:\n colors = [2] # labeled glyphs rendered blue\n print \"gli %d in cl %d at (%d,%d) %s\" % (glyph_index, cl, y, x, \"blue\" if labels[glyph_index] else \"white\")\n for i in range(gw):\n for j in range(gh):\n try:\n img[y+j, x+i, colors] = gl[j,i]*128\n except IndexError:\n print \"*yikes(%d,%d)*\" % (y+j, x+i)\n except ValueError:\n print \"missing glyph at %d\" % (glyph_index)\n \n\n # now the red lines separating the clusters\n for rm in red_markers:\n (x,y) = rm\n x += lmarg\n y += tmarg\n for i in range(gw/2-1, gw/2+1):\n for j in range(gh):\n try:\n img[y+j, x+i, 0] = 128\n except IndexError:\n print \"*yikes(%d,%d)*\" % (y+j, x+i)\n return img", "def linecosts(self,candidates,image,cseg_guess=None,transcript_guess=None):\n threshold = scipy.stats.scoreatpercentile([bestcost(x) for x in candidates],per=25)\n print \"threshold\",threshold\n best = [x for x in candidates if bestcost(x)<threshold]\n if len(best)<4: best = candidates\n base = median([x.bbox.y0 for x in best])\n scale = estimate_xheight(best)\n print \"base\",base,\"scale\",scale\n for x in candidates:\n x0,y0,x1,y1 = x.bbox.tuple()\n aspect = (y1-y0)*1.0/(x1-x0)\n costs = {}\n for cls,cost in x.outputs:\n costs[cls] = cost\n for a in costs:\n if a==\"~\": continue\n ac = ncost(aspect,self.aspects[a])\n if costs[a]<2 and ac>1.0:\n print \"adjusting\",a,costs[a],ac,\"aspect\"\n costs[cls] += ac\n for a,b in loc_confusions:\n if abs(costs[a]-costs[b])>1.0: continue\n ac = ncost((y0-base)/scale,self.ys[a])\n bc = ncost((y0-base)/scale,self.ys[b])\n if costs[a]<10:\n print \"adjusting\",a,b,costs[a],costs[b],\"loc\"\n if ac<bc: costs[b] += 2.0\n else: costs[a] += 2.0\n for a,b in size_confusions:\n if abs(costs[a]-costs[b])>1.0: continue\n ac = ncost((y1-y0)/scale,self.heights[a])\n bc = ncost((y1-y0)/scale,self.heights[b])\n if costs[a]<10:\n print \"adjusting\",a,b,costs[a],costs[b],\"size\"\n if ac<bc: costs[b] += 2.0\n else: costs[a] += 2.0\n for a in small_height:\n ac = ncost((y1-y0)/scale,self.heights[a])\n if ac<1.0: continue\n if costs[a]<10:\n print \"penalizing\",a,costs[a],ac,\"small\"\n costs[a] += ac\n x.outputs = [(cls,cost) for cls,cost in costs.items()]", "def plot_dist(class_I_dist, org):\n fig, ax = plt.subplots(figsize=[len(class_I_dist)-1, len(class_I_dist)-2])\n xmin = 0\n xmax = 1\n ymax = len(class_I_dist) * 2.5\n ax.get_yaxis().set_visible(False)\n ax.get_xaxis().set_visible(False)\n ax.set_frame_on(False)\n y = 1\n total = 0\n for contig in sorted(class_I_dist, reverse=True):\n\n if contig == \"DDB0232429\": # Add indication of chr 2 duplication in Ddi\n rep1 = [(2263132.0/class_I_dist[contig][\"length\"]) * class_I_dist[contig][\"norm_length\"],\n (3015703.0/class_I_dist[contig][\"length\"]) * class_I_dist[contig][\"norm_length\"]]\n rep2 = [(3016083.0/class_I_dist[contig][\"length\"]) * class_I_dist[contig][\"norm_length\"], \n (3768654.0/class_I_dist[contig][\"length\"]) * class_I_dist[contig][\"norm_length\"]]\n rec1 = mpatch.Rectangle((rep1[0], y-0.1), rep1[1]-rep1[0], 0.2, fc =\"lightgray\", ec = \"black\", hatch=r\"////\", alpha=100.0)\n rec2 = mpatch.Rectangle((rep2[0], y-0.1), rep2[1]-rep2[0], 0.2, fc =\"lightgray\", ec = \"black\", hatch=r\"\\\\\\\\\", alpha=100.0)\n ax.add_patch(rec1)\n ax.add_patch(rec2)\n ax.plot([0, rep1[0]], [y, y], lw = 0.5, color=\"black\")\n ax.plot([rep2[1], class_I_dist[contig][\"norm_length\"]], [y, y], lw = 0.5, color=\"black\")\n for i in range(0, class_I_dist[contig][\"length\"], 500000):\n xtick = (float(i)/class_I_dist[contig][\"length\"]) * class_I_dist[contig][\"norm_length\"]\n if xtick > rep1[0] and xtick < rep2[1]: continue\n ax.plot([xtick, xtick], [y+0.05, y-0.05], lw=0.5, color=\"black\")\n else:\n ax.plot([0, class_I_dist[contig][\"norm_length\"]], [y, y], lw = 0.5, color = \"black\")\n for i in range(0, class_I_dist[contig][\"length\"], 500000):\n xtick = (float(i)/class_I_dist[contig][\"length\"]) * class_I_dist[contig][\"norm_length\"]\n ax.plot([xtick, xtick], [y+0.05, y-0.05], lw=0.5, color=\"black\")\n total += len(class_I_dist[contig][\"class_I\"])\n ax.text(-0.01, y, contig, ha=\"right\", va=\"center\")\n ax.text(1.1, y, str(len(class_I_dist[contig][\"class_I\"])), ha=\"left\", va=\"center\")\n ax.plot([0,0], [y+0.1, y-0.1], lw=0.5, color=\"black\")\n ax.plot([class_I_dist[contig][\"norm_length\"], class_I_dist[contig][\"norm_length\"]], [y+0.1, y-0.1], lw=0.5, color=\"black\")\n ax.text(0, y+0.12, \"0\", ha=\"right\", va=\"bottom\", size=7)\n ax.text(class_I_dist[contig][\"norm_length\"], y+0.12, str(class_I_dist[contig][\"length\"]), ha=\"left\", va=\"bottom\", size=7)\n if contig == \"DDB0232429\":\n rep1 = [(2263132.0/class_I_dist[contig][\"length\"]) * class_I_dist[contig][\"norm_length\"],\n (3015703.0/class_I_dist[contig][\"length\"]) * class_I_dist[contig][\"norm_length\"]]\n rep2 = [(3016083.0/class_I_dist[contig][\"length\"]) * class_I_dist[contig][\"norm_length\"], \n (3768654.0/class_I_dist[contig][\"length\"]) * class_I_dist[contig][\"norm_length\"]]\n rec1 = mpatch.Rectangle((rep1[0], y-0.1), rep1[1]-rep1[0], 0.2, fc =\"lightgray\", ec = \"black\", hatch=r\"////\", alpha=100.0)\n rec2 = mpatch.Rectangle((rep2[0], y-0.1), rep2[1]-rep2[0], 0.2, fc =\"lightgray\", ec = \"black\", hatch=r\"\\\\\\\\\", alpha=100.0)\n ax.add_patch(rec1)\n ax.add_patch(rec2)\n sorted_starts = {class_I_dist[contig][\"start_stop\"][i][0]: {\"stop\": class_I_dist[contig][\"start_stop\"][i][1], \n \"strand\": class_I_dist[contig][\"strand\"][i], \"name\": class_I_dist[contig][\"class_I\"][i]} for i in range(len(class_I_dist[contig][\"start_stop\"]))}\n latest_start = 0.0\n arrow_y = y\n duplicated = {\"dpu_can_597\": \"blue\", \"dpu_can_598\": \"blue\", \"dpu_can_240\": \"green\", \"dpu_can_241\": \"green\", \"dpu_can_305\": \"red\", \"dpu_can_304\": \"red\", \n \"pvi_can_12\": \"blue\", \"pvi_can_13\": \"blue\", \"pvi_can_29\": \"blue\", \"ppa_can_6\": \"blue\", \"ppa_can_96\": \"blue\", \"r24A\": \"blue\", \n \"r24B\": \"blue\", \"r23A\": \"green\", \"r23B\": \"green\", \"r23C\": \"green\", \"dpc_can_18\": \"blue\", \"dpc_can_16\": \"blue\",\n \"dpc_can_17\": \"blue\", \"dpc_can_8\": \"green\", \"dpc_can_7\": \"green\"}\n for i in sorted(sorted_starts.keys()):\n start = i\n stop = sorted_starts[i][\"stop\"]\n \n if latest_start == 0 and latest_start + 0.01 > start:\n arrow_y = y - 0.25\n latest_start = start\n elif latest_start != 0 and latest_start + 0.01 > start:\n arrow_y -= 0.2\n latest_start = start\n else:\n arrow_y = y - 0.25\n latest_start = start\n if sorted_starts[i][\"strand\"] == \"-\":\n a_start = (stop, arrow_y)\n a_stop = (start, arrow_y)\n else:\n a_start = (start, arrow_y)\n a_stop = (stop, arrow_y)\n facecol = \"black\"\n if sorted_starts[i][\"name\"] in duplicated:\n facecol = duplicated[sorted_starts[i][\"name\"]]\n arrow = mpatch.FancyArrowPatch(a_start, a_stop, fc=facecol, ec=facecol, mutation_scale=10)\n ax.add_patch(arrow)\n y += 1.7\n plt.title(\"{} Class I RNAs (n={})\".format(org, total))\n plt.tight_layout()\n plt.savefig(org + \"_genomic_dist.pdf\", dpi=300, format=\"pdf\")", "def test_single_scenario(self):\r\n self.set_lib(True)\r\n\r\n # res_dual = self.run_dual_clustering_on_node_range(None, None, 3)\r\n # n_data = len(self.data[0])\r\n n_data = 81\r\n n_clusters = 3\r\n # n_clusters_for_nodes = 80\r\n n_clusters_for_nodes = None\r\n\r\n print(\"n_data: \", n_data)\r\n print(\"n_clusters_for_nodes: \", n_clusters_for_nodes)\r\n res_dual1 = run_dual_clustering_on_node_range(self.data, None, n_clusters_for_nodes, n_clusters)\r\n res_single1 = run_clustering_for_all_nodes_at_once(self.data, None, n_clusters, n_data)\r\n res_all1 = np.concatenate((res_dual1, res_single1), axis=0)\r\n comp, ca, rd = get_comp(res_dual1, res_single1)\r\n print(\"comp_avg: \" + str(ca))\r\n\r\n res_all = copy.copy(res_all1)\r\n res_dual = copy.copy(res_dual1)\r\n res_single = copy.copy(res_single1)\r\n comp_avg = ca\r\n res_diff = rd\r\n\r\n colors = ['b'] * n_clusters\r\n colors2 = ['g:'] * n_clusters\r\n cluster_labels1 = [\"cd\" + str(i + 1) for i in range(n_clusters)]\r\n cluster_labels2 = [\"cs\" + str(i + 1) for i in range(n_clusters)]\r\n\r\n plot_from_matrix(res_all, colors + colors2)\r\n plt.legend(cluster_labels1 + cluster_labels2)\r\n\r\n if n_clusters_for_nodes is None:\r\n n_clusters_for_nodes = \"auto\"\r\n\r\n plt.title(\"number of clusters for nodes: \" + str(n_clusters_for_nodes) + \", average deviation: \" + str(int(comp_avg)))\r\n plt.xlabel(\"Time of day (hours)\")\r\n plt.ylabel(\"Value of cluster centroids ($m^3 / s$)\")\r\n plt.show()", "def plot_cluster_composition(self,scaled=False,no_legend=False,ind_plot=False):\n\n colors = list(cm.afmhot(numpy.linspace(0, 0.5, len(self.param_range))));\n\n if ~ind_plot:\n fig, axes = plt.subplots(1,1,sharex=True)\n make_nice_axis(axes);\n else:\n fig, axes = plt.subplots(2,2,sharex=True)\n make_nice_axis(axes[0]) ;\n make_nice_axis(axes[1]);\n make_nice_axis(axes[2]);\n make_nice_axis(axes[3]);\n\n files = list(self.cluster_distribution.keys());\n count_file = 0;\n binding_size = [];\n store_all_means =[];\n self.N_tot = {};\n for file in files:\n if ((self.input_params[count_file]['N_A']) and (scaled)):\n if self.input_params[count_file]['seq_A'].count('A'):\n binding_size.append(self.input_params[count_file]['N_A']*(float((self.input_params[count_file]['seq_A'].count('A'))))*(self.input_params[count_file]['N_bs_AB']+self.input_params[count_file]['N_bs_AC']));\n else:\n binding_size.append(1.0)\n else:\n binding_size.append(1.0);\n\n self.N_tot[count_file] = {};\n traj = list(self.cluster_distribution[file].keys());\n\n size_of_traj = [];\n for tr in traj:\n size_of_traj.append((len(self.cluster_distribution[file][tr].keys())))\n longest_size = max(size_of_traj);\n\n Na = [];\n Nb = [];\n Nc = [];\n Ntot = [];\n count = 0;\n for tr in traj:\n if (len(self.cluster_distribution[file][tr].keys()) == longest_size):\n\n self.N_tot[count_file][count] = [];\n\n time_points = [int(x) for x in self.cluster_distribution[file][tr].keys()];\n\n for t in self.cluster_distribution[file][tr].keys():\n Nc.append([]);\n Nb.append([]);\n Na.append([]);\n Ntot.append([]);\n Nc[count].append((self.cluster_distribution[file][tr][t]['count_types']['C']))\n Nb[count].append((self.cluster_distribution[file][tr][t]['count_types']['B']))\n Na[count].append((self.cluster_distribution[file][tr][t]['count_types']['A']))\n Ntot[count].append(sum(self.cluster_distribution[file][tr][t]['count_types'].values()));\n\n if ~ind_plot:\n axes.plot(time_points,numpy.array(Ntot[count])/float(binding_size[count_file]),color='grey',lw=0.1);\n\n self.N_tot[count_file][count] = numpy.array(Ntot[count])/float(binding_size[count_file]);\n count = count+1;\n if ~ind_plot:\n N_tot_mean = numpy.array(Ntot[0]);\n for p in numpy.arange(1,len(self.N_tot[count_file])):\n N_tot_mean=N_tot_mean+numpy.array(Ntot[p]);\n N_tot_mean = (N_tot_mean)/float(len(self.N_tot[count_file]));\n store_all_means.append([]);\n store_all_means[count_file] = N_tot_mean/binding_size[count_file] ;\n axes.plot(time_points,N_tot_mean/binding_size[count_file],color=colors[count_file],lw=2);\n count_file = count_file +1;\n\n if ~ind_plot:\n if ~no_legend:\n axes.legend(bbox_to_anchor=(1.05,1.1));\n axes.set_xlabel('Time');\n axes.set_ylabel('Number of chains');\n return(N_tot_mean,time_points,axes,store_all_means)", "def entropy_overgame():\n\tPLOT_RANGE = 5000\n\tmode = input(\"color: 1 by cluster, 2 by lane\")\n\twinscale = int(input(\"wingraph: (1) for 0to1 scale, (2) for absolute scale\"))\n\n\tcluster_map, cluster_labels, champion_map = load_cluster_map()\n\thistories = fetch_all_user_history()\n\n\tcolors = ['b', 'g', 'r', 'c', 'm', 'y', 'k']\n\tmarkers = ['o', '+', '.', ',', '-']\n\t\n\tfor row in histories:\n\t\tmatches = row['matchlist']['matches']\n\t\tmatchlist_data = []\n\t\tcluster_histogram = [0] * len(cluster_labels)\n\t\tlane_histogram = {'TOP':0,'MID':0,'BOTTOM':0,'JUNGLE':0,}\n\t\tindex = 0\n\t\twins = []\n\t\tkdas = []\n\t\tnet_winloss_final = 0\n\t\tfor match_reference_dto in matches:\n\t\t\tqueue = match_reference_dto['queue']\n\t\t\tif queue != 4 and queue != 420 :\n\t\t\t\tcontinue\n\t\t\tif 'win' in match_reference_dto:\n\t\t\t\tif match_reference_dto['win'] == True:\n\t\t\t\t\tnet_winloss_final += 1\n\t\t\t\telse:\n\t\t\t\t\tnet_winloss_final -= 1\n\t\tprint('net winloss ', net_winloss_final)\n\t\tif winscale == 1:\n\t\t\tif net_winloss_final != 0:\n\t\t\t\twinloss_weight = 1.0/abs(net_winloss_final)\n\t\t\telse:\n\t\t\t\twinloss_weight = 0.02\n\t\telse:\n\t\t\twinloss_weight = 0.02\n\t\tnet_winloss = 0\n\t\tif net_winloss_final < 0:\n\t\t\tnet_winloss = -1 * net_winloss_final\n\t\tfor match_reference_dto in reversed(matches):\n\t\t\tqueue = match_reference_dto['queue']\n\t\t\tif queue != 4 and queue != 420 :\n\t\t\t\tcontinue\n\t\t\tchampion_id = match_reference_dto['champion']\n\t\t\tcluster = cluster_map[champion_id]\n\t\t\tcluster_histogram[cluster] += 1\n\t\t\tlane = match_reference_dto['lane']\n\t\t\tlane_histogram[lane] += 1\n\t\t\t#win = is_winner(match_reference_dto['gameId'], row['aid'])\n\t\t\tif 'win' in match_reference_dto:\n\t\t\t\tif match_reference_dto['win'] == True:\n\t\t\t\t\twin = 1\n\t\t\t\telse:\n\t\t\t\t\twin = -1\n\t\t\t\tkills = match_reference_dto['kills']\n\t\t\t\tdeaths = match_reference_dto['deaths']\n\t\t\t\tassists = match_reference_dto['assists']\n\t\t\t\tkda = math.log2(max((kills + assists) / max(deaths, 1), 0.1))\n\t\t\telse:\n\t\t\t\tprint(\"no winloss info\")\n\t\t\t\twin = 0\n\t\t\t\tkda = 0\n\t\t\tnet_winloss += win\n\t\t\tkdas.append(kda)\n\t\t\tmatchlist_data.append([index, champion_id, \n\t\t\t\tcluster, entropy(cluster_histogram), \n\t\t\t\tlane, entropy([e[1] for e in lane_histogram.items()]),\n\t\t\t\tnet_winloss * winloss_weight, kda])\n\n\t\t\tindex += 1\n\t\tprint('final net winloss ', net_winloss)\n\t\tentropy_sequence = [m[5] for m in matchlist_data]\n\t\tentropy_change_sequence = []\n\t\tfor i in range(len(entropy_sequence) - 1):\n\t\t\tentropy_change_sequence.append(entropy_sequence[i+1] - entropy_sequence[i])\n\t\t#segments = change_point_analysis(entropy_change_sequence)\n\n\t\tplt.title(row['tier'])\n\t\tif mode == '1':\n\t\t\tfor label in cluster_labels:\n\t\t\t\tindex_sequence = [match_data[0] for match_data in matchlist_data if match_data[2] == label and match_data[0] in range(PLOT_RANGE)]\n\t\t\t\tentropy_sequence = [match_data[3] for match_data in matchlist_data if match_data[2] == label and match_data[0] in range(PLOT_RANGE)]\n\t\t\t\tkda_sequence = [match_data[7] for match_data in matchlist_data if match_data[4] == lane and match_data[0] in range(PLOT_RANGE)]\n\t\t\t\t#plt.plot(index_sequence, entropy_sequence, colors[label]+markers[2])\n\t\t\t\tplt.plot(index_sequence, kda_sequence, colors[label]+markers[2])\n\t\t\t#for match_data in matchlist_data:\n\t\t\t#\tif match_data[0] in range(PLOT_RANGE):\n\t\t\t#\t\tplt.text(match_data[0], match_data[3], champion_map[match_data[1]], rotation = 75, fontsize = 8)\n\t\telif mode == '2':\n\t\t\tcolorid = 0\n\t\t\tfor lane in lane_histogram:\n\t\t\t\tprint(colors[colorid], lane)\n\t\t\t\tindex_sequence = [match_data[0] for match_data in matchlist_data if match_data[4] == lane and match_data[0] in range(PLOT_RANGE)]\n\t\t\t\tentropy_sequence = [match_data[5] for match_data in matchlist_data if match_data[4] == lane and match_data[0] in range(PLOT_RANGE)]\n\t\t\t\tkda_sequence = [match_data[7] for match_data in matchlist_data if match_data[4] == lane and match_data[0] in range(PLOT_RANGE)]\n\t\t\t\t#averaged_kda_sequence = [np.mean(kda_sequence[max(i-recent,0):i]) for i in range(len(kda_sequence))]\n\t\t\t\tplt.plot(index_sequence, entropy_sequence, colors[colorid]+markers[2])\n\t\t\t\t#plt.plot(index_sequence, averaged_kda_sequence, colors[colorid]+markers[2])\n\t\t\t\tcolorid += 1\n\t\t\t#for match_data in matchlist_data:\n\t\t\t#\tif match_data[0] in range(PLOT_RANGE):\n\t\t\t#\t\tplt.text(match_data[0], match_data[5], champion_map[match_data[1]], rotation = 75, fontsize = 8)\n\n\t\tindex_sequence = [match_data[0] for match_data in matchlist_data if match_data[0] in range(PLOT_RANGE)]\n\t\twinrate_sequence = [match_data[6] for match_data in matchlist_data if match_data[0] in range(PLOT_RANGE)]\n\t\tkda_sequence = [match_data[7] for match_data in matchlist_data if match_data[0] in range(PLOT_RANGE)]\n\t\tplt.plot(index_sequence, winrate_sequence, 'k-')\n\t\t#plt.plot(index_sequence, kda_sequence)\n\n\t\t#segment_sequence = [segment[0] for segment in segments if segment[0] in range(PLOT_RANGE - 1)]\n\t\t#bar_height = [1 for i in segment_sequence]\n\t\t#plt.plot(segment_sequence, bar_height, 'mo')\n\n\t\tplt.show()", "def vis_cluster_tracklet_diff(par_results, agg_dict, t_ref, g_init=0.4, gdot_init=0.0,subdir='',save=True):\n a,adot,b,bdot,colors = [],[],[],[],[]\n arrows = []\n cluster_tracklet_level = []\n\n for k,v in agg_dict.items():\n if k in par_results.keys():\n cluster_tracklet_level.append(v)\n\n if len(par_results)!= len(cluster_tracklet_level):\n raise ValueError('the length of the cluster params {0} is different from the number of ids \\\n passed for agg_dict {1}'.format(len(par_results),len(cluster_tracklet_level)))\n for k,v in par_results.items():\n # k represents cluster id and v represents the related a adot,b,bdot,g,g_dot\n arrows.append(list(v[:4])+[1000])\n\n for clust_trkls,cparams in zip(cluster_tracklet_level,par_results.values()):\n g_cl,gdot_cl = cparams[-2:]\n for trkl in clust_trkls:\n obs_in_trkl = [i[1:] for i in trkl]\n arrows.append(list(fit_tracklet(t_ref, g_cl, gdot_cl, obs_in_trkl)[:4])+[500])\n\n for clust_trkls in cluster_tracklet_level:\n for trkl in clust_trkls:\n obs_in_trkl = [i[1:] for i in trkl]\n arrows.append(list(fit_tracklet(t_ref, g_init, gdot_init, obs_in_trkl)[:4])+[100])\n\n a,adot,b,bdot,colors = np.split(np.array(arrows),5,axis=1)\n\n colormap = cm.cool\n fig,ax=plt.subplots(figsize=(18, 16))\n\n Q = ax.quiver(a, b, adot, bdot, colors, cmap=colormap,scale=0.3, width=0.0003)\n\n plt.colorbar(Q,ax=ax)\n plt.xlim(-0.1, 0.1)\n plt.ylim(-0.1, 0.1)\n plt.xlabel('alpha')\n plt.ylabel('beta')\n plt.title('Arrows with orbit fit. Darker colors represent fitted clusters, and lighter clusters represent individual tracklets.')\n if save:\n plt.savefig('{}cluster_tracklet_diff.pdf'.format(subdir))", "def draw_clusters(self):\n\t\tfor i in range(self.mesh.nnodes(ELEMENT)):\n\t\t\tif self.ci_neg[i]:\n\t\t\t\tself.draw_cluster(i)", "def draw_clusters(clusters):\n bjp_pos = read_file(collect.BJP_POS_USER_FILE)['results']\n set_bjp_pos = set(bjp_pos)\n bjp_neg = read_file(collect.BJP_NEG_USER_FILE)['results']\n set_bjp_neg = set(bjp_neg)\n con_pos = read_file(collect.CON_POS_USER_FILE)['results']\n set_con_pos = set(con_pos)\n con_neg = read_file(collect.CON_NEG_USER_FILE)['results']\n set_con_neg = set(con_neg)\n count = 2\n for cluster in clusters:\n cluster_bjp_pos = set()\n cluster_bjp_neg = set()\n cluster_con_pos = set()\n cluster_con_neg = set()\n cluster_neutral = set()\n for n in cluster.nodes():\n if n in set_bjp_pos:\n cluster_bjp_pos.add(n)\n elif n in set_bjp_neg:\n cluster_bjp_neg.add(n)\n elif n in set_con_pos:\n cluster_con_pos.add(n)\n elif n in set_con_neg:\n cluster_con_neg.add(n)\n else:\n cluster_neutral.add(n)\n draw_graph(cluster, cluster_bjp_neg, cluster_bjp_pos, cluster_con_neg, cluster_con_pos, cluster_neutral, count,\n 'cluster_' + str(count - 1), 'community detection - cluster '+ str(count - 1) + '\\n Neutral Users - Purple | '\n 'Positive for BJP - Green | '\n 'Negative for BJP - Red | \\n '\n 'Positive for Congress - Blue | '\n 'Negative for Congress - Yellow ')\n count += 1", "def investigate_diagnostic_clusters(self):\n # To start with we will do a 1 up one down plot where we have the\n # hierarchical on top of the 99 ITS2 sequences that have the host data associated with them\n # on bottom we will plot an annotation of the host group. We will hope to see clustering.\n # We will need to do this for each of the C and D clades. Start with C as this is the most abundant\n if self.coral == 'Pocillopora':\n fig = plt.figure(figsize=(11, 6))\n # 4 down 1 across\n gs = gridspec.GridSpec(11, 2)\n axes = []\n plot_tyes = ['hier', 'anot']\n hier_ax = plt.subplot(gs[0:4,:])\n seq_bars_ax = plt.subplot(gs[4:6, :])\n seq_leg_ax = plt.subplot(gs[6:7, :])\n anot_ax = plt.subplot(gs[7:8,:])\n anot_leg_ax = plt.subplot(gs[8:9, :])\n island_ax = plt.subplot(gs[9:10, :])\n island_leg_ax = plt.subplot(gs[10:11, :])\n elif self.coral == \"Porites\":\n fig = plt.figure(figsize=(11, 6))\n # 4 down 1 across\n gs = gridspec.GridSpec(13, 2)\n axes = []\n plot_tyes = ['hier', 'anot']\n hier_ax = plt.subplot(gs[0:4, :])\n seq_bars_ax = plt.subplot(gs[4:6, :])\n seq_leg_ax = plt.subplot(gs[6:7, :])\n anot_ax = plt.subplot(gs[7:8, :])\n anot_leg_ax = plt.subplot(gs[8:9, :])\n anot_sub_ax = plt.subplot(gs[9:10, :])\n anot_sub_leg_ax = plt.subplot(gs[10:11, :])\n island_ax = plt.subplot(gs[11:12, :])\n island_leg_ax = plt.subplot(gs[12:13, :])\n if self.genus == 'Cladocopium':\n if self.dist_method == 'braycurtis':\n dist_df_path = os.path.join(self.input_dir, \"2020-05-19_01-11-37.777185.braycurtis_sample_distances_C_sqrt.dist\")\n elif self.dist_method == 'unifrac':\n dist_df_path = os.path.join(self.input_dir,\n \"2020-05-19_01-11-37.777185_unifrac_btwn_sample_distances_C_sqrt.dist\")\n elif self.genus == 'Durusdinium':\n if self.dist_method == 'braycurtis':\n dist_df_path = os.path.join(self.input_dir, \"2020-05-19_01-11-37.777185.braycurtis_sample_distances_D_sqrt.dist\")\n elif self.dist_method == 'unifrac':\n dist_df_path = os.path.join(self.input_dir,\n \"2020-05-19_01-11-37.777185_unifrac_btwn_sample_distances_D_sqrt.dist\")\n sph_plot = SPHierarchical(dist_output_path=dist_df_path, no_plotting=True)\n sample_names_in_current_dist = [sph_plot.obj_uid_to_obj_name_dict[_] for _ in sph_plot.dist_df.index.values]\n samples_to_keep = [_ for _ in sample_names_in_current_dist if _ in self.counts_df_with_host.index.values]\n sph_plot = SPHierarchical(\n dist_output_path=dist_df_path, ax=hier_ax,\n sample_names_included=samples_to_keep)\n sph_plot.plot()\n hier_ax.spines['right'].set_visible(False)\n hier_ax.spines['top'].set_visible(False)\n hier_ax.set_ylabel('Dissimilarity')\n hier_ax.set_title(f'{self.coral} - {self.genus} - {self.dist_method}')\n\n spb_plot = SPBars(\n seq_count_table_path=os.path.join(self.input_dir, \"98_20200331_DBV_2020-05-19_01-11-37.777185.seqs.absolute.abund_and_meta.txt\"),\n profile_count_table_path=os.path.join(self.input_dir, \"98_20200331_DBV_2020-05-19_01-11-37.777185.profiles.absolute.abund_and_meta.txt\"),\n plot_type='seq_only', legend=True, relative_abundance=True, sample_uids_included=sph_plot.dendrogram_sample_order_uid, bar_ax=seq_bars_ax, seq_leg_ax=seq_leg_ax, limit_genera=[f'{self.genus[0]}']\n )\n spb_plot.plot()\n self._turn_off_spine_and_ticks(seq_bars_ax)\n seq_bars_ax.set_ylabel(\"ITS2\\nseqs\")\n\n # Finally we want to plot up some rectanles that will be the host_group annotations\n # And the island annotations\n # Problem TARA_CO-0000697 anot_sub_ax\n if self.coral == 'Porites':\n self._plot_annotations_and_legends(anot_ax=anot_ax, color_map_name='Dark2', leg_ax=anot_leg_ax,\n sample_to_annotation_dict={s: g[0] for s, g in self.sample_to_host_group_dict.items()}, sph_plot=sph_plot)\n anot_ax.set_ylabel(\"HostGroup\")\n self._plot_annotations_and_legends(anot_ax=anot_sub_ax, color_map_name='Set1', leg_ax=anot_sub_leg_ax, sample_to_annotation_dict=self.sample_to_host_group_dict, sph_plot=sph_plot)\n anot_sub_ax.set_ylabel(\"HostGroup\\nsub\")\n elif self.coral == 'Pocillopora':\n self._plot_annotations_and_legends(anot_ax=anot_ax, color_map_name='Set1', leg_ax=anot_leg_ax,\n sample_to_annotation_dict=self.sample_to_host_group_dict,\n sph_plot=sph_plot)\n anot_ax.set_ylabel(\"Host group\")\n self._plot_annotations_and_legends(anot_ax=island_ax, color_map_name='Set3', leg_ax=island_leg_ax,\n sample_to_annotation_dict=self.sample_to_island_dict, sph_plot=sph_plot)\n island_ax.set_ylabel(\"Island\")\n plt.savefig(os.path.join(self.figure_dir, f\"host_diagnostic_{self.coral}_{self.genus}_{self.dist_method}.png\"), dpi=600)\n plt.savefig(\n os.path.join(self.figure_dir, f\"host_diagnostic_{self.coral}_{self.genus}_{self.dist_method}.svg\"),\n dpi=600)\n foo = 'bar'", "def runCoClustering(self):\n return 0", "def create_cluster_colors(self, merged_csv_path, tol=5):\r\n #Load data containing cluster populations and classification:\r\n df = pd.read_csv(merged_csv_path)\r\n df = df.drop(['X','Y','pxlX','pxlY'],axis=1)\r\n #Find the mean cluster populations within each classification:\r\n farm_m = df.loc[(df['classification']=='farmland')].mean().values\r\n sett_m = df.loc[(df['classification']=='settlement')].mean().values\r\n wild_m = df.loc[(df['classification']=='wilderness')].mean().values\r\n\r\n \"\"\"\r\n Assign a color to each cluster based on its relation to the 3 classes:\r\n b : blue. = settlement\r\n g : green. = wilderness\r\n r : red. = farmland\r\n c : cyan. = b+g\r\n m : magenta. = r+b\r\n y : yellow. = r+g\r\n k : black. = 0\r\n w : white. = all classes\r\n \"\"\"\r\n colors = np.zeros(farm_m.size,dtype=object)\r\n for c in range(farm_m.size):\r\n if farm_m[c] > tol*np.max([sett_m[c],wild_m[c]]):\r\n colors[c] = 'r'\r\n elif sett_m[c] > tol*np.max([farm_m[c],wild_m[c]]):\r\n colors[c] = 'b'\r\n elif wild_m[c] > tol*np.max([sett_m[c],farm_m[c]]):\r\n colors[c] = 'g'\r\n elif farm_m[c]*tol < np.min([sett_m[c],wild_m[c]]):\r\n colors[c] = 'c'\r\n elif sett_m[c]*tol < np.min([farm_m[c],wild_m[c]]):\r\n colors[c] = 'y'\r\n elif wild_m[c]*tol < np.min([farm_m[c],sett_m[c]]):\r\n colors[c] = 'm'\r\n else:\r\n colors[c] = 'w'\r\n self.cluster_colors = np.append(['k'],colors) #adds an entry for the 0th cluster (i.e. unprocessed pixels)\r", "def display_vertex_segmentation(self):\n # group vertices by label (it's faster then coloring one-by-one)\n vertex_select_lists = dict.fromkeys(self.panel_order() + ['stitch', 'Other'])\n for key in vertex_select_lists:\n vertex_select_lists[key] = []\n\n for vert_idx in range(len(self.current_verts)):\n str_label = self.vertex_labels[vert_idx]\n if str_label not in self.panel_order() and str_label != 'stitch':\n str_label = 'Other'\n\n vert_addr = '{}.vtx[{}]'.format(self.get_qlcloth_geomentry(), vert_idx)\n vertex_select_lists[str_label].append(vert_addr)\n\n # Contrasting Panel Coloring for visualization\n # https://www.schemecolor.com/bright-rainbow-colors.php\n color_hex = ['FF0900', 'FF7F00', 'FFEF00', '00F11D', '0079FF', 'A800FF']\n color_list = np.empty((len(color_hex), 3))\n for idx in range(len(color_hex)):\n color_list[idx] = np.array([int(color_hex[idx][i:i + 2], 16) for i in (0, 2, 4)]) / 255.0\n\n start_time = time.time()\n for label, str_label in enumerate(vertex_select_lists.keys()):\n if len(vertex_select_lists[str_label]) > 0: # 'Other' may not be present at all\n if str_label == 'Other': # non-segmented becomes white\n color = np.ones(3)\n elif str_label == 'stitch': # stitches are black\n color = np.zeros(3)\n else: \n # color selection with expansion if the list is too small\n factor, color_id = (label // len(color_list)) + 1, label % len(color_list)\n color = color_list[color_id] / factor # gets darker the more labels there are\n\n # color corresponding vertices\n cmds.select(clear=True)\n cmds.select(vertex_select_lists[str_label])\n cmds.polyColorPerVertex(rgb=color.tolist())\n\n cmds.select(clear=True)\n\n cmds.setAttr(self.get_qlcloth_geomentry() + '.displayColors', 1)\n cmds.refresh()", "def display_segment_to_correct(vol, label_map, segment):\n\n\n\t#x,y,z = zip(*segment.list_of_voxel_tuples)\t\n\n\t#zsum = reduce(lambda a,b: a[2] + b[2], self.list_of_voxel_tuples)\t\t\n\n\tbox_bounds = segment.bounding_box\n\n\tz_mean = (box_bounds.zmax - box_bounds.zmin)/2 + box_bounds.zmin\n\n\t#z_mean = int(zsum / len(segment.list_of_voxel_tuples))\n\t\n\t\n\tpattern = np.zeros( (box_bounds.xmax - box_bounds.xmin, box_bounds.ymax - box_bounds.ymin, box_bounds.zmax - box_bounds.zmin))\t\n\tpattern[::2,::2,:] = 1\n\tpattern[1::2, 1::2, :] = 1\n\t\n\tcropped_label_map = label_map[ box_bounds.xmin: box_bounds.xmax, box_bounds.ymin: box_bounds.ymax, box_bounds.zmin:box_bounds.zmax] \n\tcropped_label_map_copy = copy.deepcopy(cropped_label_map)\n\n\tcropped_label_map = np.double(cropped_label_map == segment.label) * pattern * (segment.label+50) + np.double(cropped_label_map != segment.label) * cropped_label_map\n\n\tlabel_map[ box_bounds.xmin: box_bounds.xmax, box_bounds.ymin: box_bounds.ymax, box_bounds.zmin:box_bounds.zmax] = cropped_label_map\n\n\tsplit_mouse_event, merge_mouse_event1, merge_mouse_event2 = display_volume_two_get_clicks(vol, label_map, z_default = z_mean)\n\n\tlabel_map[ box_bounds.xmin: box_bounds.xmax, box_bounds.ymin: box_bounds.ymax, box_bounds.zmin:box_bounds.zmax] = cropped_label_map_copy\n\treturn split_mouse_event, merge_mouse_event1, merge_mouse_event2", "def plotlogg(all,names,cluster='M67',hard=None,field=None,suffix='',zindex=0,mh=None) :\n\n if zindex == 0 : zr=[3500,5500]\n elif zindex == 3 : zr=[-1, 0.5]\n else : zr=None\n\n # get indices of cluster stars for each input data set, and indices of MULTIPLES\n inds=[]\n mult=[]\n for a in all :\n if cluster == '' :\n j=np.arange(len(a))\n elif cluster == 'solar' :\n j=np.where((a['GAIA_PARALLAX_ERROR']/abs(a['GAIA_PARALLAX']) < 0.1) )[0]\n distance = 1000./a['GAIA_PARALLAX'][j]\n x,y,z,r=lbd2xyz(a['GLON'][j],a['GLAT'][j],distance/1000.)\n gd = np.where((abs(z) < 0.5) & (r>8) & (r<9) ) [0]\n j=j[gd]\n else :\n #pdb.set_trace()\n #stars=list(set(ascii.read(os.environ['APOGEE_REDUX']+'/dr17/stars/clusters/'+cluster+'.txt',names=['ID'])['ID']))\n #apogee_id = np.array(np.core.defchararray.split(a['APOGEE_ID'],'.').tolist())[:,0]\n #j,j2=match.match(apogee_id.astype(str),stars)\n j=np.array(apselect.clustmember(a,cluster,raw=True,logg=[-1,6],te=[3000,6000]))\n if len(j) == 0 : return None, None\n gd=apselect.select(a[j],sn=[75,100000],field=field,mh=mh,raw=True)\n if len(gd) == 0 : return None, None\n inds.append(j[gd])\n try :bd=np.where(np.core.defchararray.find(a[j[gd]]['STARFLAGS'],'MULTIPLE'.encode()) >=0 )[0]\n except :bd=np.where(np.core.defchararray.find(a[j[gd]]['STARFLAGS'],'MULTIPLE') >=0 )[0]\n mult.append(j[gd[bd]])\n\n # HR\n fig,ax=plots.multi(len(all),1,wspace=0.001)\n ax=np.atleast_1d(ax)\n clust=apselect.clustdata()\n for i,(a,n,j,m) in enumerate(zip(all,names,inds,mult)) :\n ax[i].cla()\n plots.plotc(ax[i],a['FPARAM'][j,0],a['FPARAM'][j,1],a['FPARAM'][j,3],\n xr=[6000,3000],yr=[6,-1],xt='Teff',yt='log g',zr=[-2,0.5],size=25,label=(0.05,0.9,n))\n plots.plotp(ax[i],a['FPARAM'][m,0],a['FPARAM'][m,1],color='k',size=25)\n jc=np.where(clust.name == cluster)[0][0]\n if clust.mh[jc] <-0.1 : isofile= 'zm{:02d}.dat'.format(round(np.abs(np.max([-2.1,clust.mh[jc]])*10)))\n else :isofile= 'zp{:02d}.dat'.format(round(np.abs(clust.mh[jc]*10)))\n age=np.round(np.log10(clust.age[jc]*1.e9)*10)/10.\n print(cluster,clust.mh[jc],clust.age[jc],isofile,age)\n iso=isochrones.read(isofile,agerange=[age,age])\n isochrones.plot(ax[i],iso,'te','logg')\n fig.suptitle('{:s}, isochrone [M/H]: {:.1f} age: {:.1f}'.format(cluster,clust.mh[jc], clust.age[jc]))\n if hard is not None:\n fig.savefig(hard+cluster+suffix+'_'+'hr'+'.png')\n plt.close()\n\n # CHI2\n fig,ax=plots.multi(1,len(all),hspace=0.001)\n ax=np.atleast_1d(ax)\n for i,(a,n,j,m) in enumerate(zip(all,names,inds,mult)) :\n ax[i].cla()\n plots.plotc(ax[i],a['FPARAM'][j,1],a['ASPCAP_CHI2'][j],a['FPARAM'][j,zindex],yt='CHI2',\n xr=[0,5],yr=[0,30],xt='log g',zr=zr,size=25,label=(0.05,0.9,n))\n plots.plotp(ax[i],a['FPARAM'][m,1],a['ASPCAP_CHI2'][m],color='k',size=25)\n fig.suptitle(cluster)\n if hard is not None:\n fig.savefig(hard+cluster+suffix+'_'+'chi2'+'.png')\n else : pdb.set_trace() \n\n # Parameters\n els = aspcap.elems()[0]\n rms=np.zeros([len(all),6+len(els),3])\n irms=0\n for iparam,param in zip([3,4,5,6],['M','Cpar','Npar','alpha']) :\n for i,(a,n,j,m) in enumerate(zip(all,names,inds,mult)) :\n giants=np.where(a['FPARAM'][j,1] < 3.8)[0]\n dwarfs=np.where(a['FPARAM'][j,1] > 3.8)[0]\n ax[i].cla()\n ymed=np.median(a['FPARAM'][j,iparam])\n print(param,ymed)\n plots.plotc(ax[i],a['FPARAM'][j,1],a['FPARAM'][j,iparam],a['FPARAM'][j,zindex],yt=param,\n xr=[0,5],yr=[ymed-0.3,ymed+0.3],xt='log g',zr=zr,size=25,label=(0.05,0.9,n))\n plots.plotp(ax[i],a['FPARAM'][m,1],a['FPARAM'][m,iparam],color='k',size=25)\n out=stats(a['FPARAM'][j,iparam],subsets=[giants,dwarfs])\n ax[i].text(0.99,0.8,'{:8.3f}, {:8.3f}'.format(out[0][0],out[0][1]),transform=ax[i].transAxes,ha='right')\n ax[i].text(0.99,0.7,'{:8.3f}, {:8.3f}'.format(out[1][0],out[1][1]),transform=ax[i].transAxes,ha='right',color='r')\n ax[i].text(0.99,0.6,'{:8.3f}, {:8.3f}'.format(out[2][0],out[2][1]),transform=ax[i].transAxes,ha='right',color='g')\n rms[i,irms,0] = a['FPARAM'][j,iparam].std()\n rms[i,irms,1] = a['FPARAM'][j[giants],iparam].std()\n rms[i,irms,2] = a['FPARAM'][j[dwarfs],iparam].std()\n if i == 0 : y0 = ymed\n ax[i].plot([0,5],[y0,y0],ls=':')\n fig.suptitle(cluster)\n irms+=1\n if hard is not None:\n fig.savefig(hard+cluster+suffix+'_'+param+'.png')\n else : pdb.set_trace() \n\n # parameter [C/N]\n for i,(a,n,j,m) in enumerate(zip(all,names,inds,mult)) :\n giants=np.where(a['FPARAM'][j,1] < 3.8)[0]\n dwarfs=np.where(a['FPARAM'][j,1] > 3.8)[0]\n ax[i].cla()\n cn=a['FPARAM'][:,4]-a['FPARAM'][:,5]\n ymed=np.median(a['FPARAM'][j,4]-a['FPARAM'][j,5])\n plots.plotc(ax[i],a['FPARAM'][j,1],a['FPARAM'][j,4]-a['FPARAM'][j,5],a['FPARAM'][j,zindex],yt='[Cpar/Npar]',\n xr=[0,5],yr=[ymed-0.3,ymed+0.3],xt='log g',zr=zr,size=25,label=(0.05,0.9,n))\n plots.plotp(ax[i],a['FPARAM'][m,1],a['FPARAM'][m,4]-a['FPARAM'][m,5],color='k',size=25)\n ax[i].text(0.9,0.8,'{:8.3f}'.format(cn[j].std()),transform=ax[i].transAxes)\n ax[i].text(0.9,0.7,'{:8.3f}'.format(cn[j[giants]].std()),transform=ax[i].transAxes,color='r')\n ax[i].text(0.9,0.6,'{:8.3f}'.format(cn[j[dwarfs]].std()),transform=ax[i].transAxes,color='g')\n rms[i,irms,0] = cn[j].std()\n rms[i,irms,1] = cn[j[giants]].std()\n rms[i,irms,2] = cn[j[dwarfs]].std()\n if i == 0 : y0=ymed\n ax[i].plot([0,5],[y0,y0],ls=':')\n fig.suptitle(cluster)\n irms+=1\n if hard is not None:\n fig.savefig(hard+cluster+suffix+'_'+'Cpar_Npar'+'.png')\n else : pdb.set_trace() \n\n # element [C/N]\n for i,(a,n,j,m) in enumerate(zip(all,names,inds,mult)) :\n giants=np.where(a['FPARAM'][j,1] < 3.8)[0]\n dwarfs=np.where(a['FPARAM'][j,1] > 3.8)[0]\n ax[i].cla()\n try :\n cn=a['FELEM'][:,0]-a['FELEM'][:,2]\n except:\n cn=a['FELEM'][:,0,0]-a['FELEM'][:,0,2]\n\n ymed=np.median(a['FELEM'][j,0]-a['FELEM'][j,2])\n plots.plotc(ax[i],a['FPARAM'][j,1],cn[j],a['FPARAM'][j,zindex],yt='[C/N]',\n xr=[0,5],yr=[ymed-0.3,ymed+0.3],xt='log g',zr=zr,size=25,label=(0.05,0.9,n))\n plots.plotp(ax[i],a['FPARAM'][m,1],a['FELEM'][m,0]-a['FELEM'][m,2],color='k',size=25)\n ax[i].text(0.9,0.8,'{:8.3f}'.format(cn[j].std()),transform=ax[i].transAxes)\n ax[i].text(0.9,0.7,'{:8.3f}'.format(cn[j[giants]].std()),transform=ax[i].transAxes,color='r')\n ax[i].text(0.9,0.6,'{:8.3f}'.format(cn[j[dwarfs]].std()),transform=ax[i].transAxes,color='g')\n rms[i,irms,0] = cn[j].std()\n rms[i,irms,1] = cn[j[giants]].std()\n rms[i,irms,2] = cn[j[dwarfs]].std()\n if i == 0 : y0=ymed\n ax[i].plot([0,5],[y0,y0],ls=':')\n fig.suptitle(cluster)\n irms+=1\n if hard is not None:\n fig.savefig(hard+cluster+suffix+'_'+'C_N'+'.png')\n else : pdb.set_trace() \n\n # elements\n els = aspcap.elems()[0]\n for iel,el in enumerate(els) :\n for i,(a,n,j,m) in enumerate(zip(all,names,inds,mult)) :\n ax[i].cla()\n try:\n gd=np.where(a['FELEM'][j,iel]>-999)[0]\n if len(gd) == 0 : continue\n ymed=np.median(a['FELEM'][j[gd],iel])\n plots.plotc(ax[i],a['FPARAM'][j[gd],1],a['FELEM'][j[gd],iel],a['FPARAM'][j[gd],zindex],yt=el,\n xr=[0,5],yr=[ymed-0.3,ymed+0.3],xt='log g',zr=zr,size=25,label=(0.05,0.9,n))\n plots.plotp(ax[i],a['FPARAM'][m,1],a['FELEM'][m,iel],color='k',size=25)\n except:\n gd=np.where(a['FELEM'][j,0,iel]>-999)[0]\n ymed=np.median(a['FELEM'][j,0,iel])\n plots.plotc(ax[i],a['FPARAM'][j[gd],1],a['FELEM'][j[gd],0,iel],a['FPARAM'][j[gd],zindex],yt=el,\n xr=[0,5],yr=[ymed-0.3,ymed+0.3],xt='log g',zr=zr,size=25)\n giants=np.where(a['FPARAM'][j[gd],1] < 3.8)[0]\n dwarfs=np.where(a['FPARAM'][j[gd],1] > 3.8)[0]\n out=stats(a['FELEM'][j[gd],iel],subsets=[giants,dwarfs])\n ax[i].text(0.99,0.8,'{:8.3f}, {:8.3f}'.format(out[0][0],out[0][1]),transform=ax[i].transAxes,ha='right')\n ax[i].text(0.99,0.7,'{:8.3f}, {:8.3f}'.format(out[1][0],out[1][1]),transform=ax[i].transAxes,ha='right',color='r')\n ax[i].text(0.99,0.6,'{:8.3f}, {:8.3f}'.format(out[2][0],out[2][1]),transform=ax[i].transAxes,ha='right',color='g')\n rms[i,irms,0] = a['FELEM'][j[gd],iel].std()\n rms[i,irms,1] = a['FELEM'][j[gd[giants]],iel].std()\n rms[i,irms,2] = a['FELEM'][j[gd[dwarfs]],iel].std()\n if i == 0 : y0=ymed\n ax[i].plot([0,5],[y0,y0],ls=':')\n fig.suptitle(cluster)\n irms+=1\n if hard is not None:\n fig.savefig(hard+cluster+suffix+'_'+el+'.png')\n else : pdb.set_trace() \n plt.close()\n fig,ax=plots.multi(1,3,hspace=0.001)\n colors=['r','g','b']\n for i in range(rms.shape[0]) :\n ax[0].plot(rms[i,:,0],colors[i]+'o-',label='all {:s}'.format(names[i]))\n ax[1].plot(rms[i,:,1],colors[i]+'o-',label='rgb {:s}'.format(names[i]))\n ax[2].plot(rms[i,:,2],colors[i]+'o-',label='ms {:s}'.format(names[i]))\n for i in range(3) :\n ax[i].legend()\n ax[i].set_ylim(0,0.2)\n ax[i].set_ylabel('rms')\n labs=['M','Cp','Np','al','CNp','CN']\n labs.extend(els)\n ax[2].set_xlim(ax[0].get_xlim())\n ax[2].set_xticks(np.arange(rms.shape[1]))\n ax[2].set_xticklabels(labs)\n if hard is not None :\n fig.savefig(hard+cluster+suffix+'_rms.png')\n plt.close()\n else: pdb.set_trace()\n plt.close()\n\n grid=[[cluster+suffix+'_rms.png']]\n for param in ['hr','chi2','M','Cpar','Npar','alpha','Cpar_Npar','C_N'] :\n fig=cluster+suffix+'_'+param+'.png'\n grid.append([fig])\n for el in aspcap.elems()[0] :\n fig=cluster+suffix+'_'+el+'.png'\n grid.append([fig])\n if hard is not None: html.htmltab(grid,file=hard+cluster+suffix+'.html')\n\n return inds, rms", "def plot_entropy_enthalpy(param_name,param_range,unique_paths,input_params):\n dt = float(input_params[0]['dt']);\n\n cluster_mean = [];\n binding_size = [];\n\n rg_mean = [];\n PE_mean = [];\n volume_fraction = numpy.zeros((len(param_range),3))\n for param in numpy.arange(len(param_range)):\n mypath = unique_paths[param];\n (cl_mean,time,header) = generate_average_plot(mypath,'cluster',1);\n cluster_mean.append(cl_mean);\n (rg,time,header) = generate_average_plot(mypath,'cluster',2);\n rg_mean.append(rg);\n (PE,time,header) = generate_average_plot(mypath,'PE',1);\n PE_mean.append(PE)\n (vol_A,vol_B,vol_C) = get_volume_fraction(input_params[param]);\n volume_fraction[param,0] = vol_A;\n volume_fraction[param,1] = vol_B;\n volume_fraction[param,2] = vol_C;\n if input_params[param]['N_A']:\n if input_params[param]['seq_A'].count('A'):\n binding_size.append(input_params[param]['N_A']*(float((input_params[param]['seq_A'].count('A'))))*(1+input_params[param]['N_bs_AB']+input_params[param]['N_bs_AC']));\n else:\n binding_size.append(1.0)\n size_A = int(len(input_params[param]['seq_A']))\n else:\n binding_size.append(1.0);\n size_A = 1;\n cluster_mean = numpy.reshape(cluster_mean,(len(param_range),len(time)))\n rg_mean = numpy.reshape(rg_mean,(len(param_range),len(time)))\n PE_mean = numpy.reshape(PE_mean,(len(param_range),len(time)))\n\n L_interest = int( numpy.floor(len(time)/1));\n fig, axes = plt.subplots(len(param_range),2,sharex=True,figsize=(12*len(param_range),9*len(param_range)))\n legend_labels = [];\n entropy_store = [];\n for count in numpy.arange(len(param_range)):\n make_nice_axis(axes[count,1]);\n make_nice_axis(axes[count,0]);\n\n axes[count,1].plot(dt*time[0:L_interest],PE_mean[count,0:L_interest],color='black',lw=4,label = 'H');\n\n volume_rest = float(pow(input_params[count]['L'],3)) * (1-numpy.sum(volume_fraction[count,:])) ;\n entropy = numpy.multiply(cluster_mean[count,0:L_interest],numpy.log(numpy.divide(4/3*numpy.pi*numpy.power(rg_mean[count,0:L_interest],3),volume_rest)));\n entropy_store.append(entropy)\n axes[count,1].plot(dt*time[0:L_interest],entropy,color='green',lw=4, label = ' $\\delta$S, ');\n if param_name.find('seq') == -1:\n legend_labels.append( param_name + ' = '+ str(round(param_range[count],2)));\n else:\n legend_labels.append( param_name + ' $ _{l} $ = '+ str(len(param_range[count])));\n\n axes[count,1].legend(fontsize =20)\n\n\n\n axes[count,0].plot(dt*time[0:L_interest],cluster_mean[count,0:L_interest]/binding_size[count],color='black',lw=4,label = 'Scaled cluster size');\n axes[count,0].set_ylabel('Scaled size')\n axes[count,0].set_ylim(0,max(cluster_mean[count,0:L_interest]/binding_size[count]))\n axes[count,0].hlines(1,0,max(dt*time[0:L_interest]),lw=2,linestyle='--',color=\"Grey\")\n axes[count,0].legend([legend_labels[count],'Stoich'],fontsize =20)\n\n axes[count,1].set_ylabel('Energy (kT)')\n\n\n axes[count,1].set_xlabel('Time')\n axes[count,0].set_xlabel('Time')\n\n entropy_store = numpy.reshape(entropy_store,(len(param_range),len(time)))\n\n return(cluster_mean,rg_mean,PE_mean,entropy_store,axes)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
test if two ractangles merge well
def test_merge(): R = ([0.29, 0.17], [0.38, 0.41]) S = ([0.51, 0.00], [0.96, 0.47]) RUS = merge_rectangle((R,S), [R, S]) #print(RUS) afficher_plsr_pts_rect([R, S, RUS[0] ], None)
[ "def are_comparable(r1: OriginRectangle, r2: OriginRectangle) -> bool:\n for a in [r1, r1.rot90()]:\n for b in [r2, r2.rot90()]:\n if is_inside(a, b) or is_inside(b, a):\n return True", "def check_overlap(l1_x, l1_y, r1_x, r1_y, l2_x, l2_y, r2_x, r2_y):\r\n# If one rectangle is on total left side of other\r\n if bool(l1_x > r2_x) ^ bool(l2_x > r1_x):\r\n return False\r\n# If one rectangle is above other\r\n if bool(l1_y < r2_y) ^ bool(l2_y < r1_y):\r\n return False\r\n return True", "def isoverlap(r1, r2):\n y1 = r1[1]\n x1 = r1[0]\n h1 = r1[3]\n w1 = r1[2]\n \n y2 = r2[1]\n x2 = r2[0]\n h2 = r2[3]\n w2 = r2[2]\n \n if ((x1+w1)<x2 or (x2+w2)<x1 or (y1+h1)<y2 or (y2+h2)<y1):\n return False\n else:\n return True", "def check_rotation(raster_one, raster_two):\n test = (raster_one.rotone == raster_two.rotone) and \\\n (raster_one.rottwo == raster_two.rottwo)\n return test", "def match(raster_in1,raster_in2):\n # Read rasterdata\n raster1 = gdal.Open(raster_in1)\n raster2 = gdal.Open(raster_in2)\n \n # load data\n band1 = raster1.GetRasterBand(1)\n band2 = raster2.GetRasterBand(1)\n gt1 = raster1.GetGeoTransform()\n gt2 = raster2.GetGeoTransform()\n \n # find each image's bounding box\n # r1 has left, top, right, bottom of dataset's bounds in geospatial coordinates.\n r1 = [gt1[0], gt1[3], gt1[0] + (gt1[1] * raster1.RasterXSize), gt1[3] + (gt1[5] * raster1.RasterYSize)]\n r2 = [gt2[0], gt2[3], gt2[0] + (gt2[1] * raster2.RasterXSize), gt2[3] + (gt2[5] * raster2.RasterYSize)]\n print('\\t1 bounding box: %s' % str(r1))\n print('\\t2 bounding box: %s' % str(r2))\n \n # find intersection between bounding boxes\n intersection = [max(r1[0], r2[0]), min(r1[1], r2[1]), min(r1[2], r2[2]), max(r1[3], r2[3])]\n if r1 != r2:\n print('\\t** different bounding boxes **')\n # check for any overlap at all...\n if (intersection[2] < intersection[0]) or (intersection[1] < intersection[3]):\n intersection = None\n print('\\t***no overlap***')\n return\n else:\n print('\\tintersection:',intersection)\n left1 = int(round((intersection[0]-r1[0])/gt1[1])) # difference divided by pixel dimension\n top1 = int(round((intersection[1]-r1[1])/gt1[5]))\n col1 = int(round((intersection[2]-r1[0])/gt1[1])) - left1 # difference minus offset left\n row1 = int(round((intersection[3]-r1[1])/gt1[5])) - top1\n \n left2 = int(round((intersection[0]-r2[0])/gt2[1])) # difference divided by pixel dimension\n top2 = int(round((intersection[1]-r2[1])/gt2[5]))\n col2 = int(round((intersection[2]-r2[0])/gt2[1])) - left2 # difference minus new left offset\n row2 = int(round((intersection[3]-r2[1])/gt2[5])) - top2\n \n #print '\\tcol1:',col1,'row1:',row1,'col2:',col2,'row2:',row2\n if col1 != col2 or row1 != row2:\n print(\"ERROR: Columns and rows still do not match! ***\")\n # these arrays should now have the same spatial geometry though NaNs may differ\n array1 = band1.ReadAsArray(left1,top1,col1,row1)\n array2 = band2.ReadAsArray(left2,top2,col2,row2)\n\n else: # same dimensions from the get go\n col1 = raster1.RasterXSize # = col2\n row1 = raster1.RasterYSize # = row2\n array1 = band1.ReadAsArray()\n array2 = band2.ReadAsArray()\n \n return array1, array2, intersection", "def roi_overlap(ROIs1, ROIs2, param1, param2, im1_shape, im2_shape, thr_ovlp=0.5, pplot=False, im1=None):\n\n ROIs1_trans = rottrans_rois(ROIs1, param1[0], param1[1], param1[2], im1_shape[0], im1_shape[1])\n ROIs2_trans = rottrans_rois(ROIs2, param2[0], param2[1], param2[2], im2_shape[0], im2_shape[1])\n\n # NOTE: for plotting the variable im1 is missing\n if pplot:\n plt.figure()\n axes = plt.subplot(111)\n axes.imshow(im1, cmap='gray')\n draw_rois(ROIs1, axes, 'red')\n draw_rois(ROIs2_trans, axes, 'green')\n plt.show(block=False)\n\n\n # test which ROIs overlap\n ri=0\n roi_map = {}\n for r in ROIs1_trans :\n (x0, y0) = (r[0][0], r[1][0])\n polyg1 = Polygon(list(zip(r[0], r[1])) + [(x0,y0)])\n\n si=0\n for s in ROIs2_trans :\n (x0, y0) = (s[0][0], s[1][0])\n polyg2 = Polygon(list(zip(s[0], s[1])) + [(x0,y0)])\n\n if polyg1.intersects(polyg2):\n p = polyg1.intersection(polyg2)\n if (p.area >= polyg1.area*thr_ovlp) or (p.area >= polyg2.area*thr_ovlp):\n #if roi_map.has_key(ri):\n if ri in roi_map:\n roi_map[ri].append(si)\n else :\n roi_map[ri] = [si]\n si=si+1\n \n ri=ri+1\n\n for r in list(roi_map.keys()):\n if len(roi_map[r]) > 1 :\n roi_map.pop(r, None)\n\n roi_map = [(k,roi_map[k][0]) for k in roi_map.keys()]\n \n return roi_map", "def test_no_overlap():\n random.seed(123)\n rectangles = [(random.randint(50, 100), random.randint(50, 100))\n for _ in range(40)]\n positions = rpack.pack(rectangles)\n for i, ((x1, y1), (w1, h1)) in enumerate(zip(positions, rectangles)):\n for j, ((x2, y2), (w2, h2)) in enumerate(zip(positions, rectangles)):\n if i != j:\n disjoint_in_x = (x1 + w1 <= x2 or x2 + w2 <= x1)\n disjoint_in_y = (y1 + h1 <= y2 or y2 + h2 <= y1)\n assert disjoint_in_x or disjoint_in_y", "def overlap(r1: Rule, r2: Rule):\n if max(r1.src[0], r2.src[0]) > min(r1.src[1], r2.src[1]):\n return False\n if max(r1.dst[0], r2.dst[0]) > min(r1.dst[1], r2.dst[1]):\n return False\n return True", "def merge(self, r1, r2) -> None:\n ...", "def shapeCompare(objectobject):\n pass", "def equal_hsmshapedata(res1, res2):\n if not isinstance(res1, galsim.hsm.ShapeData) or not isinstance(res2, galsim.hsm.ShapeData):\n raise TypeError(\"Objects that were passed in are not ShapeData objects\")\n\n if res1.corrected_e1 != res2.corrected_e1: return False\n if res1.corrected_e2 != res2.corrected_e2: return False\n if res1.corrected_g1 != res2.corrected_g1: return False\n if res1.corrected_g2 != res2.corrected_g2: return False\n if res1.corrected_shape_err != res2.corrected_shape_err: return False\n if res1.error_message != res2.error_message: return False\n if res1.image_bounds.xmin != res2.image_bounds.xmin: return False\n if res1.image_bounds.xmax != res2.image_bounds.xmax: return False\n if res1.image_bounds.ymin != res2.image_bounds.ymin: return False\n if res1.image_bounds.ymax != res2.image_bounds.ymax: return False\n if res1.meas_type != res2.meas_type: return False\n if res1.moments_amp != res2.moments_amp: return False\n if res1.moments_centroid != res2.moments_centroid: return False\n if res1.moments_n_iter != res2.moments_n_iter: return False\n if res1.moments_rho4 != res2.moments_rho4: return False\n if res1.moments_sigma != res2.moments_sigma: return False\n if res1.moments_status != res2.moments_status: return False\n if res1.observed_shape != res2.observed_shape: return False\n if res1.resolution_factor != res2.resolution_factor: return False\n return True", "def test_disjoint_union(self):\n a = bounding_box.BoundingBox(\n bounding_box.Point(5, 10), bounding_box.Size(5, 20)\n )\n b = bounding_box.BoundingBox(\n bounding_box.Point(15, 5), bounding_box.Size(15, 20)\n )\n self.assertEqual(bounding_box.calculate_union(a, b), 400)", "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 test_merge_rings_permutations():\n for i in range(16):\n # test each segment in both directions\n f1 = i & 1 == 0\n f2 = i & 2 == 0\n f3 = i & 4 == 0\n f4 = i & 8 == 0\n for i1, i2, i3, i4 in permutations([0, 1, 2, 3]):\n ways = [\n W(1, {}, [1, 2, 3, 4] if f1 else [4, 3, 2, 1]),\n W(2, {}, [4, 5, 6, 7] if f2 else [7, 6, 5, 4]),\n W(3, {}, [7, 8, 9, 10] if f3 else [10, 9, 8, 7]),\n W(4, {}, [10, 11, 12, 1] if f4 else [1, 12, 11, 10]),\n ]\n ways = [ways[i1], ways[i2], ways[i3], ways[i4]]\n rings = [Ring(w) for w in ways]\n \n merged_rings = merge_rings(rings)\n eq_(len(merged_rings), 1)\n r = merged_rings[0]\n eq_(r.is_closed(), True, (ways, r.refs))\n eq_(set(r.ways), set(ways))\n\n # check order of refs\n prev_x = r.refs[0]\n for x in r.refs[1:]:\n if not abs(prev_x - x) == 1:\n assert (\n (prev_x == 1 and x == 12) or \n (prev_x == 12 and x == 1)\n ), 'not in order %r' % r.refs\n prev_x = x", "def regions_overlap(r1,r2):\n x = False\n for loc in r1.locs:\n if loc in r2.locs:\n return True\n return False", "def make_rings(df, r1, r2=None):\n\n if r2 is None:\n r2 = np.sqrt(2)*r1\n \n buf_r1 = df.to_crs(3395).buffer(r1)\n buf_r2 = df.to_crs(3395).buffer(r2)\n\n ring = buf_r2.difference(buf_r1)\n \n # Check that relative difference is close to zero --> areas are equal\n rel_diff = ((buf_r1.area - ring.area)/buf_r1.area).round(8)\n #print('!!!!',rel_diff.sum(), r1, r2, buf_r1.area, ring.area)\n assert rel_diff.sum() == 0, (r1, r2, rel_diff.sum())\n \n return ring", "def _overlaps_vertically(self, r0: Rectangle, r1: Rectangle) -> bool:\n return (\n int(r0.get_y()) <= int(r1.get_y()) <= int(r0.get_y() + r0.get_height())\n ) or (int(r1.get_y()) <= int(r0.get_y()) <= int(r1.get_y() + r1.get_height()))", "def equals(first_img, second_img): \n\n if first_img is None or second_img is None: \n return False \n diff = ImageChops.difference(first_img, second_img)\n if diff.getbbox() != None: \n return False\n else: \n diff = None\n return True", "def testAreasTwoLevelComposite(self):\n\t\texpAreas = [self.areaA*2, self.areaB*2, self.areaC*2]\n\t\tself.compB.areas = expAreas\n\t\tactAreas = self.compB.areas\n\t\t[self.assertAlmostEqual(exp,act) for exp,act in it.zip_longest(expAreas,actAreas)]" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
find start of the code object
def find_start(lst): i=0 for i in range(len(lst)): if opcodes.m_type.get(lst[i])=='TYPE_CODE': return i
[ "def __find_block_start(self):\n try:\n return self.__find_token(self.__block_head)\n except RouteParserError:\n raise StartTokenNotFoundError(_('No match for entry block start'))", "def get_doc_start():\n start = \"*** START OF THIS PROJECT GUTENBERG EBOOK THE ADVENTURES OF SHERLOCK HOLMES ***\"\n with open(filename, \"r\") as f:\n for num, line in enumerate(f, 1):\n if start in line:\n x = num\n start_line = 1 + x\n f.close()\n return start_line\n else:\n return 0", "def match_start(self):\n raise NotImplementedError()", "def get_start_line(self):\n if self._start_line == 0 and self._ast_elem_list != []:\n self._start_line = self._ast_elem_list[0].coord.line\n\n return self._start_line", "def start_index(self):\n return self.stoi.get(self.start_symbol, -1)", "def _beginningOfContent(line: str) -> int:\n m = _INDENT_RE.match(line)\n if m and m.group(1) is not None:\n return m.start(1)\n else:\n return 0", "def beginning_of_code_block(node, full_contents):\n line_number = node.line\n delta = len(node.non_default_attributes())\n current_line_contents = full_contents.splitlines()[line_number:]\n blank_lines = next((i for (i, x) in enumerate(current_line_contents) if x),\n 0)\n return line_number + delta - 1 + blank_lines - 1 + SPHINX_CODE_BLOCK_DELTA", "def getStartStart(self):\n for ro in self.lstOfRows:\n if (ro.classification==\"start_codon\"):\n return(int(ro.start))", "def get_construct_start(self):\n return self.prepos", "def test_clang_format_parser_line_start():\n cfp = ClangFormatXMLParser()\n data = \"\"\n offset = 0\n assert cfp.find_index_of_line_start(data, offset) == 0", "def getInstructionStart(self,address):\n \"\"\"is in the middle of an instruction, Hopper will look back to find the first byte of this instruction.\"\"\"\n return HopperLowLevel.nearestBlock(self.__internal_segment_addr__,address)", "def find_insertion_line(self, code):\n match = re.search(r\"^(def|class)\\s+\", code)\n if match is not None:\n code = code[: match.start()]\n try:\n pymodule = libutils.get_string_module(self.project, code)\n except exceptions.ModuleSyntaxError:\n return 1\n testmodname = \"__rope_testmodule_rope\"\n importinfo = importutils.NormalImport(((testmodname, None),))\n module_imports = importutils.get_module_imports(self.project, pymodule)\n module_imports.add_import(importinfo)\n code = module_imports.get_changed_source()\n offset = code.index(testmodname)\n lineno = code.count(\"\\n\", 0, offset) + 1\n return lineno", "def _get_start(self):\n return self.Data.Start", "def begin_token(self) -> str:", "def isStart(self, line):\r\n return self.startsWithAttribute(line)", "def first(self):\n return int(self._start)", "def get_start_pos(self):\n num_bases = len(self.staple_bases)\n if num_bases == 0:\n return None \n staple_start_pos = self.staple_bases[0].p\n scaffold_start_pos = self.scaffold_bases[0].p\n start_pos = min(staple_start_pos, scaffold_start_pos)\n return start_pos", "def is_start_marker(line):\n assert False, \"Unimplemented!\"", "def _find_diff_start(lines):\n regex = re.compile('^E .+\\(\\d+ difference[s]?\\): [\\[{]$')\n for index, line in enumerate(lines):\n if regex.search(line) is not None:\n return index\n return None" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Uses stored client credentials to get oauth access token from Spotify Requires accepting app access via spotify browser redirect and user need to copy and paste redirect url into console
def get_oauth(): # Get Spotify client credentials from a .gitignore'd config file with open('config.json', 'r') as data_file: config = json.load(data_file) spotify_client_id = config['spotify_client_id'] spotify_client_secret = config['spotify_client_secret'] url_redirect = 'https://example.com' auth = spotipy.oauth2.SpotifyOAuth(client_id=spotify_client_id, client_secret=spotify_client_secret, redirect_uri=url_redirect, show_dialog=True, scope='playlist-modify-private', cache_path='token.txt') # it sometimes says .get_access_token() is being deprecated, but not always # not sure what is going on with spotipy access_tok = auth.get_access_token() return access_tok['access_token']
[ "def authSpotify():\n scopes = [\"streaming\", \"user-read-birthdate\", \"user-read-email\", \"user-read-private\"]\n scope_string = (\" \").join(scopes)\n params = {\n \"response_type\": \"code\",\n \"client_id\": SPOTIFY_CLIENT_ID,\n \"scope\": scope_string,\n \"redirect_uri\": url_for(\"spotifyCallback\", _external=True)\n }\n encoded_query_string = urllib.parse.urlencode(params)\n base_url = 'https://accounts.spotify.com/authorize'\n auth_request_url = base_url + \"?\" + encoded_query_string\n return jsonify(auth_url = auth_request_url)", "async def authorize():\n url = await authorize_spotify()\n return RedirectResponse(url.get('spotify'))", "def get_spotify_access_token():\n auth_url = \"https://accounts.spotify.com/api/token\"\n auth_data = {\n \"grant_type\": \"client_credentials\",\n \"client_id\": SPOTIFY_CLIENT_ID,\n \"client_secret\": SPOTIFY_CLIENT_SECRET,\n }\n response = requests.post(auth_url, data=auth_data)\n response_data = response.json()\n return response_data[\"access_token\"]", "def authorize_spotify(config):\n util.info('Authorizing Spotify...')\n util.info('You can find keys at https://developer.spotify.com/my-applications.')\n client_id = util.prompt('Input your Spotify Client ID')\n client_secret = util.prompt('Input your Spotify Client Secret')\n\n try:\n tokens = spotify.authorize(client_id, client_secret, config)\n if tokens:\n if not 'spotify' in config.token_data:\n config.token_data['spotify'] = {}\n\n refresh_time = int(time.time()) + tokens['expires_in']\n config.token_data['spotify']['refresh_time'] = refresh_time\n config.token_data['spotify']['access_token'] = tokens['access_token']\n config.token_data['spotify']['refresh_token'] = tokens['refresh_token']\n config.token_data.write()\n\n if config.verbose:\n util.debug('Spotify refresh time: {}'.format(refresh_time))\n util.debug('Spotify access token: {}'.format(tokens['access_token']))\n util.debug('Spotify refresh token: {}'.format(\n tokens['refresh_token'])\n )\n\n util.success('Spotify successfully authorized!')\n else:\n util.error('Some unknown error occured...')\n except service.AuthorizationError as err:\n util.error('Spotify did not authorize correctly: {}'.format(err))\n except spotify.SpotifyStateError as err:\n util.error('Spotify state mismatch between request and response...')", "def StravaAuthenticate(callback):\n client = stravalib.client.Client()\n\n access_token = None\n\n if os.path.exists(\"access_token\"):\n access_token = open(\"access_token\").read().strip()\n\n if access_token:\n log.info(\"re using access token from disk\")\n client.access_token = access_token\n callback(client)\n else:\n log.info(\"getting access token via web browser\")\n\n client_id, secret = open(\"client.secret\").read().strip().split(\",\")\n port = 1969\n\n url = \"http://localhost:%d/authorized\" % port\n\n authorize_url = client.authorization_url(client_id=client_id, redirect_uri=url, scope=\"view_private,write\")\n log.info(\"Opening: %s\", authorize_url)\n subprocess.call([\"open\", authorize_url])\n\n\n def UseCode(code):\n \"\"\"Turn the code from the oauth dance into an access token, store it and call the callback.\"\"\"\n access_token = client.exchange_code_for_token(client_id=client_id, client_secret=secret, code=code)\n client.access_token = access_token\n open(\"access_token\", \"w\").write(access_token)\n callback(client)\n\n class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):\n \"\"\"Simple http server to do the oauth dance.\"\"\"\n def do_GET(self): # pylint: disable=invalid-name\n \"\"\"handle a get reuqest method to parse out the code.\"\"\"\n if self.path.startswith(\"/authorized\"):\n self.wfile.write(\"<script>window.close();</script>\")\n code = urlparse.parse_qs(urlparse.urlparse(self.path).query)[\"code\"][0]\n global ALL_DONE_WITH_HTTPD # pylint: disable=global-statement\n ALL_DONE_WITH_HTTPD = True\n UseCode(code)\n\n httpd = BaseHTTPServer.HTTPServer((\"localhost\", port), MyHandler)\n while not ALL_DONE_WITH_HTTPD:\n httpd.handle_request()", "def getSP():\r\n\r\n client_credentials_manager = SpotifyClientCredentials(client_id=cid,\r\n client_secret=secret)\r\n\r\n sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)\r\n scope = 'playlist-modify-private playlist-modify-public playlist-read-private user-library-read user-top-read'\r\n token = util.prompt_for_user_token(username, scope, client_id=cid, client_secret=secret, redirect_uri='http://localhost/')\r\n if token:\r\n sp = spotipy.Spotify(auth=token)\r\n print(\"Success?\")\r\n\r\n else:\r\n print(\"Can't get token for\", username)\r\n return sp", "def authorize(ctx):\n debug = ctx.obj['DEBUG']\n music = Musicmanager(debug_logging=debug)\n music.perform_oauth(open_browser=True)", "def request_authorization(self, autoset=True):\n # set up data\n encoded_string = base64.b64encode(b\"8ba9f109a5804da896a4881feaf09776:b083e54626e24930a4020ad1bc05d9f0\")\n url = \"https://accounts.spotify.com/api/token\"\n body = {\n \"grant_type\": \"client_credentials\"\n }\n header = {\n \"Authorization\": b\"Basic \" + encoded_string\n }\n\n # make the actual request\n response = requests.post(url, body, headers=header)\n response_dict = response.json()\n\n if response.ok:\n print(\"Spotify authorization succedeed\")\n print(\"Valid for \" + str(response_dict[\"expires_in\"]))\n print(\"OAuth: \" + response_dict[\"access_token\"])\n if autoset:\n self.set_oauth(response_dict[\"access_token\"])\n self.__auth_time__ = time.time()\n self.__expires_in__ = int(response_dict[\"expires_in\"])\n\n else:\n print(\"Spotify authorization failed\")\n print(\"Error: \" + response.content)\n\n return response_dict", "def authenticate_user():\n # Prompt the user for their username\n username = input('\\nWhat is your Spotify username: ')\n\n try:\n # Get an auth token for this user\n token = sp_util.prompt_for_user_token(username, scope=scope)\n\n spotify = spotipy.Spotify(auth=token)\n return username, spotify\n except SpotifyException as e:\n print('API credentials not set. Please see README for instructions on setting credentials.')\n sys.exit(1)\n except SpotifyOauthError as e:\n redirect_uri = os.environ.get('SPOTIPY_REDIRECT_URI')\n if redirect_uri is not None:\n print(\"\"\"\n Uh oh! It doesn't look like that URI was registered as a redirect URI for your application.\n Please check to make sure that \"{}\" is listed as a Redirect URI and then Try again.'\n \"\"\".format(redirect_uri))\n else:\n print(\"\"\"\n Uh oh! It doesn't look like you set a redirect URI for your application. Please add\n export SPOTIPY_REDIRECT_URI='http://localhost/'\n to your `credentials.sh`, and then add \"http://localhost/\" as a Redirect URI in your Spotify Application page.\n Once that's done, try again.'\"\"\")\n sys.exit(1)", "def _authorise(self):\n redirect_uri = f'http://localhost:8080/callback'\n token_request_data = {\n 'grant_type': 'authorization_code',\n 'code': self._access_token,\n 'redirect_uri': redirect_uri\n }\n\n if self._access_token is None:\n data = {\n 'client_id': self._client_id,\n 'response_type': 'code',\n 'redirect_uri': redirect_uri,\n 'scope': 'user-library-read playlist-read-private playlist-modify-public playlist-modify-private'\n }\n query_string = urlencode(data, doseq=True)\n\n print('No existing authorisation code found, use the link below to authorise this application.')\n print(f'https://accounts.spotify.com/authorize?{query_string}')\n\n auth_server = AuthorisationServer()\n token_request_data['code'] = auth_server.start()\n\n token_request_response = requests.post('https://accounts.spotify.com/api/token',\n data=token_request_data,\n auth=(self._client_id, self._client_secret))\n\n if token_request_response.status_code == 200:\n response_data = token_request_response.json()\n self._db_client.set_value('access_token', response_data['access_token'])\n self._db_client.set_value('refresh_token', response_data['refresh_token'])\n self._access_token = response_data['access_token']", "def oauth_callback(request):\n oauth = request.session.get('oauth', {})\n sandbox = oauth.get('sandbox', None)\n \n sf = SalesforceOAuth2(settings.MPINSTALLER_CLIENT_ID, settings.MPINSTALLER_CLIENT_SECRET, settings.MPINSTALLER_CALLBACK_URL, sandbox=sandbox)\n\n code = request.GET.get('code',None)\n if not code:\n return HttpResponse('ERROR: No code provided')\n\n resp = sf.get_token(code)\n\n # Set the response in the session\n oauth.update(resp)\n request.session['oauth'] = oauth\n request.session.save()\n\n return HttpResponseRedirect(request.build_absolute_uri('/mpinstaller/oauth/post_login'))", "def auth():\n\n return redirect(f'https://api.twitch.tv/kraken/oauth2/authorize?response_type=code&client_id=g37b9kh93q0fiihc931e29gwihf2q9&redirect_uri={REDIRECT_URI}&scope=user_read')", "def gconnect():\r\n # Validation for the state token\r\n if request.args.get('state') != login_session['state']:\r\n response = make_response(json.dumps('Invalid state parameter.'), 401)\r\n response.headers['Content-Type'] = 'application/json'\r\n return response\r\n\r\n\t# Get Authorization code\r\n code = request.data\r\n\r\n try:\r\n # Storing Credential Objects\r\n oauth_flow = flow_from_clientsecrets('client_secret.json', scope='')\r\n oauth_flow.redirect_uri = 'postmessage'\r\n credentials = oauth_flow.step2_exchange(code)\r\n\r\n except FlowExchangeError:\r\n response = make_response(json.dumps('Failed to update the authorization code.'), 401)\r\n response.headers['Content-Type'] = 'application/json'\r\n return response\r\n\r\n # Access Token Validation\r\n access_token = credentials.access_token\r\n # login_session['credentials'] = credentials.access_token\r\n url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s' % access_token)\r\n h = httplib2.Http()\r\n result = json.loads(h.request(url, 'GET')[1])\r\n\r\n\t# If error occurs pass 500 as status and abort\r\n if result.get('error') is not None:\r\n response = make_response(json.dumps(result.get('error')), 500)\r\n response.headers['Content-Type'] = 'application/json'\r\n return response\r\n\r\n\t# Access Token Verification\r\n gplus_id = credentials.id_token['sub']\r\n if result['user_id'] != gplus_id:\r\n response = make_response(\r\n json.dumps(\"Given User ID doesn't match with the Token's User ID\"), 401)\r\n response.headers['Content-Type'] = 'application/json'\r\n return response\r\n\r\n\t# validates access token for this app\r\n if result['issued_to'] != CLIENT_ID:\r\n response = make_response(\r\n json.dumps(\"Client's token id doesn't match with App token id\"), 401)\r\n print \"Client's token id doesn't match with App token id\"\r\n response.headers['Content-Type'] = 'application/json'\r\n return response\r\n\r\n\t# To send status 200 for logged in user\r\n stored_access_token = login_session.get('access_token')\r\n stored_gplus_id = login_session.get('gplus_id')\r\n if stored_access_token is not None and gplus_id == stored_gplus_id:\r\n response = make_response(json.dumps('User is already logged in'), 200)\r\n response.headers['Content-Type'] = 'application/json'\r\n flash(\"You are now logged in as %s\" % login_session['user_id'])\r\n return response\r\n\r\n # To Store credentials of user for later use\r\n login_session['access_token'] = credentials.access_token\r\n login_session['gplus_id'] = gplus_id\r\n\r\n # Store user info\r\n userinfo_url = \"https://www.googleapis.com/oauth2/v1/userinfo\"\r\n params = {'access_token': credentials.access_token, 'alt': 'json'}\r\n answer = requests.get(userinfo_url, params=params)\r\n data = answer.json()\r\n login_session['username'] = data['name']\r\n login_session['picture'] = data['picture']\r\n login_session['email'] = data['email']\r\n # login_session['provider'] = 'google'\r\n\t# Check and store user info if user is not already in user database\r\n user_id=getUserID(data['email'])\r\n if not user_id:\r\n user_id=createUser(login_session)\r\n login_session['user_id']=user_id\r\n # return \"Login Successful\"\r\n # login_session['user_id']=useremail\r\n # For generating message for user and send status 200 code\r\n output = ''\r\n output += '<h1>Welcome, '\r\n output += login_session['username']\r\n output += '!</h1>'\r\n output += '<img src=\"'\r\n output += login_session['picture']\r\n output += ' \" style = \"width: 300px; height: 300px;border-radius: 150px;-webkit-border-radius: 150px;-moz-border-radius: 150px;\"> '\r\n flash(\"You are now logged in as %s\" % login_session['username'])\r\n print \"OK\"\r\n # response = make_response(json.dumps(output),200)\r\n # response.headers['Content-Type'] = 'application/json'\r\n #return response\r\n return output", "def login_with_token(username=USERNAME):\n import spotipy.util\n scope = 'user-library-read playlist-read-private user-read-private'\n token = spotipy.util.prompt_for_user_token(\n 'dbgoldberg01', scope,\n client_id=keys['CLIENT_ID'],\n client_secret=keys['CLIENT_SECRET'],\n redirect_uri='http://localhost:8888/callback')\n if token:\n global sp\n sp = spotipy.Spotify(auth=token)\n return sp\n else:\n raise SpotifyAPIException(\"Can't get token\")", "def echo():\n return redirect(\"https://api.imgur.com/oauth2/authorize?client_id=\" + request.form['client_id'] + \"&response_type=token&state=sssss\", code=302)", "def check_manual_token(spotify_handler):\n if request.headers.get('Authorization'):\n access_token = request.headers.get('Authorization').split()[1]\n spotify_handler.get_cache_handler().save_token_to_cache(\n {\n 'access_token': access_token,\n 'expires_in': 3600,\n 'scope': 'user-library-read playlist-modify-public playlist-read-collaborative',\n 'expires_at': int(time.time()) + 3600,\n }\n )", "def do_client_authentication(client_id, client_secret):\n client = globus_sdk.ConfidentialAppAuthClient(\n client_id,\n client_secret,\n )\n token_response = client.oauth2_client_credentials_tokens()\n return (token_response.by_resource_server\n ['transfer.api.globus.org']['access_token']\n )", "def flickr_session():\n if os.path.isfile(FLICKR_TOKEN_FILENAME):\n with open(FLICKR_TOKEN_FILENAME, 'rb') as f_open:\n access_token = pickle.load(f_open)\n return requests_oauthlib.OAuth1Session(\n client_key=KEY, client_secret=SECRET,\n resource_owner_key=access_token['oauth_token'],\n resource_owner_secret=access_token['oauth_token_secret']\n )\n else:\n flickr = requests_oauthlib.OAuth1Session(\n client_key=KEY, client_secret=SECRET,\n callback_uri='http://127.0.0.1/cb',\n )\n flickr.fetch_request_token(REQUEST_TOKEN_URL)\n authorization_url = flickr.authorization_url(AUTH_BASE_URL)\n print('Please go here and authorize,', authorization_url)\n flickr.parse_authorization_response(\n input('Paste the full redirect URL here: ')\n )\n with open(FLICKR_TOKEN_FILENAME, 'wb') as f_write:\n token = flickr.fetch_access_token(ACCESS_TOKEN_URL)\n pickle.dump(token, f_write)\n return flickr", "def connect_spotify():\r\n try:\r\n scope='playlist-read-private, playlist-modify-private, playlist-modify-public'\r\n sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope, cache_path=CACHE))\r\n return sp\r\n except SpotifyException as e:\r\n print(f\"{e}: Failed to connect to Spotify API.\")" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets bearer token through existing token.txt file or requests ones from Spotify through get_oauth function
def get_bearer(): try: # get existing bearer token and test it through bearer_test method with open('token.txt', 'r') as token_file: token_data = token_file.read() token_dict = json.loads(token_data) bearer_token_str = token_dict['access_token'] except FileNotFoundError: # Requests a new bearer bearer_token_str = get_oauth() finally: return bearer_token_str
[ "def get_oauth():\n\n # Get Spotify client credentials from a .gitignore'd config file\n with open('config.json', 'r') as data_file:\n config = json.load(data_file)\n spotify_client_id = config['spotify_client_id']\n spotify_client_secret = config['spotify_client_secret']\n url_redirect = 'https://example.com'\n\n auth = spotipy.oauth2.SpotifyOAuth(client_id=spotify_client_id,\n client_secret=spotify_client_secret,\n redirect_uri=url_redirect,\n show_dialog=True,\n scope='playlist-modify-private',\n cache_path='token.txt')\n\n # it sometimes says .get_access_token() is being deprecated, but not always\n # not sure what is going on with spotipy\n access_tok = auth.get_access_token()\n return access_tok['access_token']", "def request_authorization(self, autoset=True):\n # set up data\n encoded_string = base64.b64encode(b\"8ba9f109a5804da896a4881feaf09776:b083e54626e24930a4020ad1bc05d9f0\")\n url = \"https://accounts.spotify.com/api/token\"\n body = {\n \"grant_type\": \"client_credentials\"\n }\n header = {\n \"Authorization\": b\"Basic \" + encoded_string\n }\n\n # make the actual request\n response = requests.post(url, body, headers=header)\n response_dict = response.json()\n\n if response.ok:\n print(\"Spotify authorization succedeed\")\n print(\"Valid for \" + str(response_dict[\"expires_in\"]))\n print(\"OAuth: \" + response_dict[\"access_token\"])\n if autoset:\n self.set_oauth(response_dict[\"access_token\"])\n self.__auth_time__ = time.time()\n self.__expires_in__ = int(response_dict[\"expires_in\"])\n\n else:\n print(\"Spotify authorization failed\")\n print(\"Error: \" + response.content)\n\n return response_dict", "def check_manual_token(spotify_handler):\n if request.headers.get('Authorization'):\n access_token = request.headers.get('Authorization').split()[1]\n spotify_handler.get_cache_handler().save_token_to_cache(\n {\n 'access_token': access_token,\n 'expires_in': 3600,\n 'scope': 'user-library-read playlist-modify-public playlist-read-collaborative',\n 'expires_at': int(time.time()) + 3600,\n }\n )", "def get_spotify_access_token():\n auth_url = \"https://accounts.spotify.com/api/token\"\n auth_data = {\n \"grant_type\": \"client_credentials\",\n \"client_id\": SPOTIFY_CLIENT_ID,\n \"client_secret\": SPOTIFY_CLIENT_SECRET,\n }\n response = requests.post(auth_url, data=auth_data)\n response_data = response.json()\n return response_data[\"access_token\"]", "def _request_bearer_token(self):\n\n # Format and encode key, see Twitter API documentation.\n key_secret = '{}:{}'.format(\n OAuthToken.API_CONSUMER_KEY,\n OAuthToken.API_SECRET_KEY)\n b64_encoded_key = base64.b64encode(key_secret.encode('ascii'))\n b64_encoded_key = b64_encoded_key.decode('ascii')\n\n # Create header with encoded API key and send POST using requests\n # library.\n headers = {\n 'User-Agent':'TemperatureOfTheRoom',\n 'Authorization':'Basic ' + b64_encoded_key,\n 'Content-Type':'application/x-www-form-urlencoded;charset=UTF-8',\n 'Accept-Encoding':'gzip'} \n body = {'grant_type':'client_credentials'}\n request = requests.post(\n OAuthToken.API_OAUTH_ENDPOINT,\n data = body,\n headers = headers)\n\n bearer_token = request.json()['access_token']\n return bearer_token", "def _access_tokens(oauth):\n print \"\"\"\\nWe'll need to create access tokens specific to your bot. To\ndo that, please visit the following URL:\n\n%s\n\nOnce you have authorized the app with your bot account, you will receive a PIN.\n\"\"\" % oauth.get_authorization_url()\n check = \"n\"\n while check.lower() != \"y\":\n pin = raw_input(\"Enter your PIN here: \")\n check = raw_input(\"Was that correct? [y/n]: \")\n token = None\n try:\n token = oauth.get_access_token(verifier = pin)\n except tweepy.error.TweepError as e:\n print 'Unable to authenticate! Check your OAuth credentials and run this script again.'\n quit(e.reason)\n\n # Everything worked!\n print \"\"\"Authentication successful! Wait just a minute while the rest of your\nbot's internals are set up...\n\"\"\"\n return token", "def authenticate():\n try:\n with open('keys.txt', mode='r') as file:\n line = file.readline()\n consumer_key = line.strip().split('consumer_key=')[1]\n line = file.readline()\n consumer_secret = line.strip().split('consumer_secret=')[1]\n line = file.readline()\n auth_set_access_token = line.strip().split('auth_set_access_token=')[1]\n line = file.readline()\n access_token_secret = line.strip().split('access_token_secret=')[1]\n print(consumer_key, consumer_secret, auth_set_access_token, access_token_secret)\n except tweepy.TweepError as e:\n print(e.reason, '/n Please check keys.txt is present in current directory and try again.')\n\n auth = tweepy.OAuthHandler(consumer_key, consumer_secret)\n auth.set_access_token(auth_set_access_token, access_token_secret)\n api = tweepy.API(auth)\n return api", "def load_bearer_token():\n\n # To set your environment variables in your terminal execute a command\n # like the one that you see below.\n\n # Example:\n # export 'TWITTER_BEARER_TOKEN'='<your_twitter_bearer_token>'\n\n # Do this for all of your tokens, and then load them with the commands\n # below, matching the string in the .get(\"string\") to the name you've\n # chosen to the left of the equal sign above.\n\n # Set Twitter tokens/keys.\n # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n bearer_token = os.environ.get(\"TWITTER_BEARER_TOKEN\")\n\n return bearer_token", "def get_token(self) -> None:\n logging.info('QivivoAPI: Asking for token')\n send_data = urllib.parse.urlencode({'grant_type': 'client_credentials',\n 'client_id': self.client_id,\n 'client_secret': self.client_secret,\n })\n send_data = send_data.encode('ascii')\n try:\n r = json.load(urllib.request.urlopen(self.oauth_url, send_data))\n except urllib.error.HTTPError as e:\n logging.error(\"QivivoAPI: urllib error: \" + e.reason)\n logging.error(\"QivivoAPI; API error: \" + e.read())\n self.token = r['access_token']\n self.token_date = datetime.now()\n logging.info('QivivoAPI: token initialised with: ' + self.token)\n return", "def get_bearer():\n token_url = conf.token_url\n data = conf.bearer_data\n logging.info(\"Login to \" + token_url + \" to get token\")\n try:\n token_response = requests.post(url=token_url, data=data) # making post call to anypoint\n logging.info(token_response)\n token_response_json = token_response.json() # extracting response text\n bearer = token_response_json[\"access_token\"] # parsing bearer frm json\n return bearer\n except ValueError:\n logging.info(\"Parsing response as JSON failed\")\n except Exception as e:\n logging.info(str(e))", "def read_authorization_header(self):\n self.headers = {}\n filename = os.path.join(os.path.expanduser('~'), '.auth_tokens')\n if os.path.isfile(filename):\n try:\n with open(filename, 'r') as file_ptr:\n bearer_token = json.load(file_ptr)['id_token']\n self.headers['Authorization'] = 'Bearer %s' % bearer_token\n except Exception as e:\n sys.stderr.write(\n 'could not read token from %s: %s\\n' % (filename, e))\n sys.exit(1)", "def StravaAuthenticate(callback):\n client = stravalib.client.Client()\n\n access_token = None\n\n if os.path.exists(\"access_token\"):\n access_token = open(\"access_token\").read().strip()\n\n if access_token:\n log.info(\"re using access token from disk\")\n client.access_token = access_token\n callback(client)\n else:\n log.info(\"getting access token via web browser\")\n\n client_id, secret = open(\"client.secret\").read().strip().split(\",\")\n port = 1969\n\n url = \"http://localhost:%d/authorized\" % port\n\n authorize_url = client.authorization_url(client_id=client_id, redirect_uri=url, scope=\"view_private,write\")\n log.info(\"Opening: %s\", authorize_url)\n subprocess.call([\"open\", authorize_url])\n\n\n def UseCode(code):\n \"\"\"Turn the code from the oauth dance into an access token, store it and call the callback.\"\"\"\n access_token = client.exchange_code_for_token(client_id=client_id, client_secret=secret, code=code)\n client.access_token = access_token\n open(\"access_token\", \"w\").write(access_token)\n callback(client)\n\n class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):\n \"\"\"Simple http server to do the oauth dance.\"\"\"\n def do_GET(self): # pylint: disable=invalid-name\n \"\"\"handle a get reuqest method to parse out the code.\"\"\"\n if self.path.startswith(\"/authorized\"):\n self.wfile.write(\"<script>window.close();</script>\")\n code = urlparse.parse_qs(urlparse.urlparse(self.path).query)[\"code\"][0]\n global ALL_DONE_WITH_HTTPD # pylint: disable=global-statement\n ALL_DONE_WITH_HTTPD = True\n UseCode(code)\n\n httpd = BaseHTTPServer.HTTPServer((\"localhost\", port), MyHandler)\n while not ALL_DONE_WITH_HTTPD:\n httpd.handle_request()", "def _read_token(self):\n try:\n serialized_token = open(self.token_file).read()\n if serialized_token.startswith('oauth1:'):\n return serialized_token[len('oauth1:'):].split(':', 1)\n elif serialized_token.startswith('oauth2:'):\n return serialized_token[len('oauth2:'):]\n else:\n log.warning(\"Malformed access token in %r.\", self.token_file)\n except (IOError, OSError):\n pass # don't worry if it's not there or can't be read", "def tokenAuth(self):\n self.basicAuth()\n token_url = reverse('api-token')\n response = self.client.get(token_url, format='json', data={})\n\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertIn('token', response.data)\n\n token = response.data['token']\n self.token = token", "def getSP():\r\n\r\n client_credentials_manager = SpotifyClientCredentials(client_id=cid,\r\n client_secret=secret)\r\n\r\n sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)\r\n scope = 'playlist-modify-private playlist-modify-public playlist-read-private user-library-read user-top-read'\r\n token = util.prompt_for_user_token(username, scope, client_id=cid, client_secret=secret, redirect_uri='http://localhost/')\r\n if token:\r\n sp = spotipy.Spotify(auth=token)\r\n print(\"Success?\")\r\n\r\n else:\r\n print(\"Can't get token for\", username)\r\n return sp", "def _get_oauth_token(self):\n url = self.api_endpoint + '/auth/oauth2/token'\n headers = {\n 'Authorization': [\n 'client_id:' + self.client_id,\n 'client_secret:' + self.client_secret\n ]\n }\n\n # Flatten auth headers\n headers['Authorization'] = ','.join(headers['Authorization'])\n\n headers['Content-Type'] = 'application/json'\n payload = {'grant_type': 'client_credentials'}\n\n resp = self._post_call(self.session, url, headers, payload)\n for item in resp.json()['data']:\n if 'access_token' in item:\n access_token = item['access_token']\n return access_token", "def get_oauth_tokens(self):\n headers = {'Content-Type': 'application/x-www-form-urlencoded'}\n payload = {\n 'response_type': 'device_code',\n 'client_id': OAUTH_CLIENT_ID,\n }\n method = 'post'\n\n request = urllib2.Request(\n OAUTH_URL, headers=headers, data=urllib.urlencode(payload))\n request.get_method = lambda: method.upper()\n response = urllib2.urlopen(request)\n data = json.load(response)\n\n print '\\nThis script needs to be authenticated for future use.'\n print '\\nTo continue, please open the URL below in any browser and ' \\\n 'enter the following code: {}'.format(data['user_code'])\n print data['verification_uri']\n\n payload = {\n 'grant_type': 'device',\n 'client_id': OAUTH_CLIENT_ID,\n 'code': data['device_code']\n }\n\n print '\\nWaiting for authorization...'\n started = datetime.datetime.now()\n while 1:\n # sleep for the poll interval that the IdP recommends\n time.sleep(data['interval'])\n\n # the verification code remains active for 10 minutes only\n elapsed = (datetime.datetime.now() - started)\n if elapsed.total_seconds() > 600:\n raise Attach2CaseError(\n 'Authorization step was not completed in time',\n AUTHENTICATION_ERROR)\n\n request = urllib2.Request(\n OAUTH_URL, headers=headers, data=urllib.urlencode(payload))\n request.get_method = lambda: method.upper()\n\n try:\n response = urllib2.urlopen(request)\n data = json.load(response)\n if not os.path.exists(os.path.dirname(STATE_FILE)):\n os.makedirs(os.path.dirname(STATE_FILE))\n\n with open(STATE_FILE, 'wb') as fh:\n fh.write(data['refresh_token'])\n\n self._refresh_token = data['refresh_token']\n self._access_token = data['access_token']\n\n print '...done\\n'\n\n return\n except urllib2.HTTPError:\n # keep polling\n pass", "def flickr_session():\n if os.path.isfile(FLICKR_TOKEN_FILENAME):\n with open(FLICKR_TOKEN_FILENAME, 'rb') as f_open:\n access_token = pickle.load(f_open)\n return requests_oauthlib.OAuth1Session(\n client_key=KEY, client_secret=SECRET,\n resource_owner_key=access_token['oauth_token'],\n resource_owner_secret=access_token['oauth_token_secret']\n )\n else:\n flickr = requests_oauthlib.OAuth1Session(\n client_key=KEY, client_secret=SECRET,\n callback_uri='http://127.0.0.1/cb',\n )\n flickr.fetch_request_token(REQUEST_TOKEN_URL)\n authorization_url = flickr.authorization_url(AUTH_BASE_URL)\n print('Please go here and authorize,', authorization_url)\n flickr.parse_authorization_response(\n input('Paste the full redirect URL here: ')\n )\n with open(FLICKR_TOKEN_FILENAME, 'wb') as f_write:\n token = flickr.fetch_access_token(ACCESS_TOKEN_URL)\n pickle.dump(token, f_write)\n return flickr", "def token_generator():\n key = constants.CLIENT_ID + ':' + constants.SECRET_KEY\n key_base64 = encode(key)\n key_base64 = 'Basic ' + key_base64\n header = {\n 'authorization': key_base64,\n 'content-type': 'application/x-www-form-urlencoded'\n }\n body = \"grant_type=client_credentials&scope=urn:opc:resource:consumer::all\"\n response = requests.post(url=constants.AUTH_URL, headers=header, data=body)\n response_json = json.loads(response.content.decode('ascii'))\n return response_json['access_token']" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Search gnip for ``q``, return `results`__ directly from gnip.
def search(self, q, **kw): return self.gnip.search(q, **kw)
[ "def search():\n\n # parses querie into key word array\n q = request.args.get(\"q\")\n\n # parases query into an array\n q_array = q.split(\" \")\n\n # remove any commas (if any)\n query = []\n for item in q_array:\n if item[len(item) - 1] == \",\":\n item = item.replace(\",\", \"\")\n query.append(item)\n else:\n query.append(item)\n\n # Finds postal code, city and state that start within q\n results = db.execute(\n \"SELECT * FROM places WHERE country_code LIKE :q OR postal_code LIKE :q OR place_name LIKE :q OR admin_name1 LIKE :q OR admin_code1 LIKE :q OR admin_name2 LIKE :q OR admin_code2 LIKE :q OR latitude LIKE :q OR longitude LIKE :q\", q=query[0])\n\n # for each word in query, search whole database results and find overlapping search results from other word queries\n for i in range(1, len(query)):\n results_cmp = db.execute(\n \"SELECT * FROM places WHERE country_code LIKE :q OR postal_code LIKE :q OR place_name LIKE :q OR admin_name1 LIKE :q OR admin_code1 LIKE :q OR admin_name2 LIKE :q OR admin_code2 LIKE :q OR latitude LIKE :q OR longitude LIKE :q\", q=query[i])\n results = intersection(results, results_cmp)\n\n # returns results containing all word queries; if one keyword DNE in database, results will return empty set\n return jsonify(results)", "async def search(\n response: Response,\n q: str = Query(\n None,\n min_length=2,\n max_length=50,\n regex=\"^[a-zA-A0-9_]+$\",\n description=\"query string\",\n ),\n engines: str = Query(\n \"gitea\", description=\"comma-separated list of engines, e.g. `gitea,github`\"\n ),\n):\n\n engines_ = _parse_engines(engines)\n awaitables = [engine.search(q) for engine in engines_]\n results = await asyncio.gather(*awaitables, return_exceptions=True)\n repos, errors = _merge_search_results(results)\n return SearchResponse(repos=repos, errors=errors)", "def search(self, q):\n\n status, id_pairs = self.imap.uid('search', str(q))\n ids = []\n\n for id_pair in id_pairs:\n ids.extend((id_pair).decode().split())\n\n return ids", "async def search(query: str,\n ncbi: int = 0,\n level: int = None,\n skip: int = None,\n limit: int = 1000,\n universal: float = None,\n singlecopy: float = None) -> List[str]:\n\n res = await remote_call(base + 'search',\n True,\n query=query,\n ncbi=ncbi,\n level=level,\n skip=skip,\n limit=limit,\n universal=universal,\n singlecopy=singlecopy)\n\n return res['data']", "def find_by_solr(self, q):\r\n if settings.SOLR['running']:\r\n con = Solr(settings.SOLR_URL)\r\n solr_results = con.search(\"(%s) AND class: %s\" % (q, 'Item'))\r\n \r\n # Convert hits back into models and add to the results list\r\n results = []\r\n for doc in solr_results.docs:\r\n objects = eval(doc['class']).objects.filter(id = doc['id'])\r\n if objects.__len__() > 0: results.append(objects[0])\r\n \r\n return results\r\n else:\r\n return []", "def search(api_key, term, location):\n\n url_params = {\n 'name': term.replace(' ', '+'),\n 'address1': location.replace(' ', '+'),\n 'city': 'Long Beach',\n 'state': 'US',\n 'country': 'US',\n 'limit': SEARCH_LIMIT\n }\n return request(API_HOST, MATCH_PATH, api_key, url_params=url_params)", "def runSearch(app, query, cache):\n\n api = app.api\n S = api.S\n N = api.N\n sortKeyTuple = N.sortKeyTuple\n plainSearch = S.search\n\n cacheKey = (query, False)\n if cacheKey in cache:\n return cache[cacheKey]\n options = dict(_msgCache=[])\n if app.sets is not None:\n options[\"sets\"] = app.sets\n (queryResults, status, messages, exe) = plainSearch(query, here=False, **options)\n queryResults = tuple(sorted(queryResults, key=sortKeyTuple))\n nodeFeatures = ()\n edgeFeatures = set()\n\n if exe:\n (nodeFeatures, edgeFeatures) = getQueryFeatures(exe)\n\n (runStatus, runMessages) = wrapMessages(S._msgCache)\n cache[cacheKey] = (\n queryResults,\n (status, runStatus),\n (messages, runMessages),\n nodeFeatures,\n edgeFeatures,\n )\n return (\n queryResults,\n (status, runStatus),\n (messages, runMessages),\n nodeFeatures,\n edgeFeatures,\n )", "def search(search_string, offset=0):\n return giphy.search(search_string, offset)", "def google_search(search_term, num_results=1):\r\n results = []\r\n for url in googlesearch.search(search_term, start=1, stop=1+num_results, num=1):\r\n results.append(url)\r\n return results", "def search(self, query, model=None):\n raise NotImplementedError()", "def search(\n auth_token: AccessToken,\n query: str,\n search_type: List[SearchType],\n limit: int = 20,\n offset: int = 0,\n) -> List[Dict]:\n payload: Dict[str, Union[str, int]] = {\n \"q\": query.replace(\" \", \"%20\"),\n \"type\": reduce(\n lambda a, x: a + \"{},\".format(x), map(lambda x: x.value, search_type), \"\"\n )[:-1],\n \"limit\": limit,\n \"offset\": offset,\n }\n\n return get(\n \"https://api.spotify.com/v1/search/\",\n params=payload,\n headers={\n \"Authorization\": f\"Bearer {auth_token}\",\n },\n ).json()[\"items\"]", "def search(self, search_term: str) -> None:\n self._executeQuery(\"search/{}\".format(search_term))", "def search(self, **kw):\n request = self.service.SearchRequest(params=kw)\n\n self.log(f'Searching for {self.service.item.type}s with the following options:')\n self.log_t(request.options, prefix=' - ')\n\n data = request.send()\n\n lines = self._render_search(data, **kw)\n count = 0\n for line in lines:\n count += 1\n print(line[:const.COLUMNS])\n self.log(f\"{count} {self.service.item.type}{pluralism(count)} found.\")", "def search(query, base_url):\n query = query.split()\n query = '+'.join(query)\n header = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)'}\n url = base_url + query\n\n return get_soup(url, header)", "def search(request):\n\n query = request.GET.get(\"q\", \"\")\n results_list = []\n\n for ent in util.list_entries():\n if query.lower() == ent.lower():\n return entry(request, ent)\n elif query.lower() in ent.lower():\n results_list.append(ent)\n\n return render(request, \"encyclopedia/results.html\",{\n \"query\": query,\n \"results_list\": results_list\n })", "def search(query):\n\tlogging.debug(\"search(): searching names and snippets for query string\")\n\n\n\twith connection, connection.cursor() as cursor:\n\t\tcommand = \"SELECT * FROM snippets where keyword like \\'%%%s%%\\' or message like \\'%%%s%%\\'\" % (query, query)\n\t\tcursor.execute(command)\n\t\tfetchall = cursor.fetchall()\n\tif not fetchall:\n\t\tprint \"No queries found. Please try another search.\"\n\t\tlogging.debug(\"Search empty, returning None.\")\n\t\treturn None, None \n\telse:\n\t\tname, message = [x[0] for x in fetchall], [x[1] for x in fetchall]\n\t\tlogging.debug(\"Returning keywords in catalog database\")\n\t\treturn name, message", "def search(api_key, term, location, category, url_params):\n return request(API_HOST, SEARCH_PATH, api_key, url_params)", "async def google(self, ctx, *, search_term: commands.clean_content):\n\n try:\n results = await ctx.bot.google_api.search(\n search_term,\n safesearch=not ctx.channel.is_nsfw() if ctx.guild else False,\n )\n except async_cse.search.NoResults:\n return await ctx.send(\n \"No search results found. \"\n + (\n \"Perhaps, the results were nsfw, go to a nsfw channel and use this command again and see\"\n if (not ctx.channel.is_nsfw() if ctx.guild else False)\n else \"\"\n )\n )\n\n embeds = []\n for result in results:\n embed = discord.Embed(\n title=result.title,\n description=result.description,\n url=result.url,\n color=0x2F3136, # invisible color\n )\n # Sometimes the images are invalid so we are just validating that\n if re.match(r\"(http(s?):)(.)*\\.(?:jpg|gif|png)\", result.image_url):\n embed.set_thumbnail(url=result.image_url)\n embeds.append(embed)\n\n menu = Paginator(embeds)\n await menu.start(ctx)", "def lookup(q, tax):\n\n # add entrezID and synonyms fields to query (do this instead of using a\n # multifield parser so we can detect when a token didn't match any genes)\n query = Or((q, q.copy().accept(setfield_entrezID), q.copy().accept(setfield_synonyms)))\n \n # add the taxon constraint to the query\n if tax:\n query = And([query, Term('tax', str(tax))])\n\n genes = [g['entrezID'] for g in searcher.search(query, limit=None)]\n if genes:\n return genes\n else:\n print query\n raise LookupError()" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initializes a graph object with an empty dictionary. self.vert_dict > List of the edges self.num_verticies > List of verticies
def __init__(self): self.vert_dict = {} self.num_verticies = 0 self.num_edges = 0
[ "def __init__(self, number_of_vertices: int):\n super().__init__(number_of_vertices)\n\n self.__graph: Dict[int: List[int]] = {}\n\n for i in range(number_of_vertices):\n self.__graph[i] = []", "def __init__(self, vertex_num=0):\n self._adj_lists = [{} for i in range(vertex_num)]\n self._edge_num = 0", "def __init__(self, vertices = [], edges = [], is_directed = True):\n\n self.is_directed = is_directed\n\n self.adjacency_dict = {}\n\n for vertex in vertices:\n self.add_vertex(vertex)\n\n for vertex_from, vertex_to in edges:\n self.add_edge(vertex_from, vertex_to)", "def __init_graph(self) -> None:\n self.graph = Graph()", "def __init__(self):\r\n super().__init__()\r\n self._coords = dict()\r\n self._vertexLabels = dict()", "def __init__(self, v):\n if v < 0:\n raise ValueError('Number of vertices must be non-negative')\n self.V = v\n self.E = 0\n self._indegree = [0 for _ in range(v)]\n self.adj = defaultdict(Bag)\n for v in range(v):\n self.adj[v] = Bag()", "def __init__(self, graph_dict=None, directed_dict=None):\n if graph_dict is None:\n graph_dict = {}\n if directed_dict is None:\n directed_dict = {}\n self.__graph_dict = graph_dict\n self.__directed_dict = directed_dict", "def addVertice(self, vertice):\n if vertice not in self.graph:\n self.graph[vertice] = {}", "def __init__(self, vertex_id, edges=None):\n super().__init__(vertex_id, edges)\n self._explored = False\n self._finishing_time = 0\n self._leader = 0", "def __init__(self):\n self.G = nx.Graph()\n self.node_attr_dfs = dict()\n self.unique_relations = set()\n self.node_types = dict()\n self.normalized_node_id_map = dict()\n self.train_edges = list()\n self.valid_edges = list()\n self.test_edges = list()\n self.relation_to_id = dict()\n self.id_to_relation = dict()\n self.nodeid2rowid = dict()\n self.rowid2nodeid = dict()\n self.rowid2vocabid = dict()", "def __init__(self):\n self.graph_string = {'x1': [\"f1\"],\n \"x2\": [\"f2\"],\n \"x3\": [\"f1\", \"f2\"],\n \"x4\": [\"f3\"],\n \"x5\": [\"f1\", \"f3\"],\n \"x6\": [\"f2\", \"f3\"],\n \"x7\": [\"f1\", \"f2\", \"f3\"],\n \"f1\": [\"x1\", \"x3\", \"x5\", \"x7\"],\n \"f2\": [\"x2\", \"x3\", \"x6\", \"x7\"],\n \"f3\": [\"x4\", \"x5\", \"x6\", \"x7\"]}\n self.nodes = {}\n self.edges = {}\n for node, _ in self.graph_string.iteritems():\n n = None\n if node.startswith(\"x\"):\n n = Node(node, False)\n elif node.startswith(\"f\"):\n n = Node(node, True)\n self.nodes[n.id] = n\n for node, connections in self.graph_string.iteritems():\n n = self.nodes[node]\n for connection in connections:\n edge = None\n if self.nodes.get(connection):\n edge = Edge(n, self.nodes[connection])\n n.outgoing_edges.append(edge)\n self.nodes[connection].incoming_edges.append(edge)\n self.edges[str(edge)] = edge", "def __init__(self, n_vertices, n_loops, n_hairs, even_edges):\n self.n_vertices = n_vertices\n self.n_loops = n_loops\n self.n_hairs = n_hairs\n self.even_edges = even_edges\n self.sub_type = \"even_edges\" if even_edges else \"odd_edges\"\n\n # we count only the internal edges\n self.n_edges = self.n_loops + self.n_vertices - 1\n super(CHairyGraphVS, self).__init__()\n self.ogvs = OrdinaryGraphComplex.OrdinaryGVS(\n self.n_vertices + self.n_hairs, self.n_loops, even_edges)", "def construct_graph(self):\r\n\t\tedges = self.generate_edges()\r\n\t\tfor edge in edges:\r\n\t\t\tself.insert_edge(edge[0],edge[1],edge[2]) # adds all the edges to graph\r", "def __init__(self, graph_list: List[List[int]]):\n # initializing the graph structure\n self.graph: DefaultDict[int, List[int]] = defaultdict(list)\n\n for row in graph_list:\n self.graph[row[0]].extend(row[1:])", "def __init__(self, gfile):\n # open the file\n f = open(gfile, \"r\")\n # read the file\n file = f.readlines()\n\n line_count = 0\n for line in file:\n if line_count == 0:\n # initialise all vertices in graph\n num_vertices = int(line.strip())\n self.vertices = []\n for i in range(num_vertices):\n self.vertices.append(Vertex(i))\n else:\n # add edges\n edge = line.split()\n # convert to integers\n for i in range(len(edge)):\n edge[i] = int(edge[i])\n self.add_directed_edge(edge[0], edge[1], edge[2])\n self.add_directed_edge(edge[1], edge[0], edge[2])\n line_count += 1\n\n # close the file\n f.close()", "def __create_graph(self):\n self.clear() \n self.__ordered_network()\n self.__create_new_random_connections()", "def __init__(self):\n init_vertex_proto_input = Vertex_Protocol()\n init_vertex_proto_input.type = 'linear'\n init_vertex_proto_output = Vertex_Protocol()\n init_vertex_proto_output.type = 'linear'\n init_edge = Edge_Protocol()\n init_edge.type = 'identity'\n\n init_vertex_proto_input.output_mutable = True\n init_vertex_proto_output.input_mutable = True\n\n\n init_vertex_proto_input.edge_out.add(init_edge.ID)\n init_vertex_proto_output.edge_in.add(init_edge.ID)\n init_edge.from_vertex = init_vertex_proto_input.ID\n init_edge.to_vertex = init_vertex_proto_output.ID\n\n\n self.vertex_proto = {init_vertex_proto_input.ID:init_vertex_proto_input,\n init_vertex_proto_output.ID:init_vertex_proto_output}\n self.edge_proto = {init_edge.ID:init_edge}\n self.learning_rate = 0.1\n self.fitness = 0\n self.ID = uuid.uuid4()", "def construct_adjacency_lists(self):\n\n self.root = self.data[\"root\"]\n self.vertices = [node[\"id\"] for node in self.data[\"nodes\"]]\n\n for edge in self.data[\"edges\"]:\n _from = edge[\"from\"]\n _to = edge[\"to\"]\n\n if _from not in self.adj:\n self.adj[_from] = []\n\n self.adj[_from].append(_to)", "def __init__(self,n:int) -> None:\r\n self.vertices = [None]*n\r\n for i in range(n):\r\n self.vertices[i] = Vertex(i)", "def _create_adjacency_list(self, vertices, edges, m):\n self.adjacency_list = dict()\n # first, initialise empty lists for all vertices\n for v in vertices:\n self.adjacency_list[v.vertex_id] = []\n # now add all edges\n for e in edges:\n self.adjacency_list[e.from_vertex_id].append(e)\n # and also the opposite way\n for e in edges:\n self.adjacency_list[e.to_vertex_id].append(e.create_opposite_edge(self.undirected, e.edge_id + m))" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a new vertex object to the graph with the given key and return the vertex.
def add_vertex(self, key): self.num_verticies += 1 new_vertex = Vertex(key) self.vert_dict[key] = new_vertex return new_vertex
[ "def add_vertex(self, key):\n\n if key in self.vert_dict:\n print(f'Vertex {key} already exists')\n return\n\n # create a new vertex\n new_vertex = Vertex(key)\n self.vert_dict[key] = new_vertex\n self.num_vertices += 1\n\n return self.vert_dict[key]", "def create_vertex(self, key):\n new_vertex = KjVertex(key)\n self._vertex_list[key] = new_vertex\n return new_vertex", "def create_vertex(self, key):\n new_vertex = SpVertex(key)\n self._vertex_list[key] = new_vertex\n return new_vertex", "def create_node(self, key, data=None):\n\n if self.exists(key):\n raise Exception(\"Vertex with same key already exists in graph\")\n\n v = Vertex(key, data, self._directed)\n self._add_node(v)", "def add_vertex(self, vertex):\n if vertex.label not in self.vertices():\n self.__graph_dict[vertex.label] = vertex", "def add_vertex(self):\n u = self.g.add_vertex()\n return u", "def add_vertex(self, v):\n pass", "def graph_vertex( g, i, add_if_necessary = False ):\n if add_if_necessary and i not in g.id_to_vertex:\n v = g.add_vertex()\n g.id_to_vertex[ i ] = v\n g.vertex_properties[ 'vertex_id' ][ v ] = i\n return g.id_to_vertex[ i ]", "def add_vertex(self, vertex):\r\n self.vertices.append(vertex)", "def add_vertex(self, vertex):\n if vertex not in self.__graph_dict:\n self.__graph_dict[vertex] = []\n self.__directed_dict[vertex] = []", "def addVertexKey(self):\n self.outMesh.addKey(VertexKey())", "def add_tagged_vertex(self, tag: _VertexTag) -> Vertex:\n vertex = super().add_vertex(Vertex())\n self.vertex_tags[vertex] = tag\n if tag in self.tag_to_vertices:\n self.tag_to_vertices[tag].add(vertex)\n else:\n self.tag_to_vertices[tag] = {vertex}\n return vertex", "def add_vertex(self, group_number: int, vertex: Union[Vertex, Any], property_: Any = None):\n self._validate_group(group_number)\n the_vertex = self._graph.add_vertex(vertex, property_)\n self._vertex_group_dict[the_vertex] = group_number\n return the_vertex", "def add_vertex(self, vertex):\n\n\t\tself.vertices.append(vertex)", "def add_vertex(self, vertex):\n if isinstance(vertex, Vertex) and vertex.name not in self.vertices:\n self.vertices[vertex.name] = vertex\n return True\n else:\n return False", "def add_vertex(self, vertex: str):\n Logger.log(Logger.LogLevel.VERBOSE,\n f\"Adding vertex {self.vertex_count}: {vertex}\")\n self.vertices[self.vertex_count] = vertex\n self.vertex_count += 1", "def vertex():\n return Vertex('v1')", "def add_node(self, key, data=None):\n if key in self:\n raise KeyError(\"Duplicate key '{0}' found.\".format(key))\n\n new_node = GraphNode(key, data=data)\n self.nodes[new_node] = {}", "def add_vertex(self, id, vertex):\n \n # Check if vertex with given id already exists.\n if id in self.vertices:\n return\n \n # Check if each vertex in adjacent_to exists.\n for i in vertex.adjacent_to:\n if not i in self.vertices:\n return\n \n # Add given vertex at given id.\n self.vertices[id] = vertex\n \n # Add id to adjacent_to of each vertex in vertex's adjacent_to.\n for i in vertex.adjacent_to:\n self.vertices[i].add_edge(id)", "def append_vertex(self, vertex):" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
add an edge from vertex f to vertex t with a cost
def add_edge(self, f, t, cost=0): if f not in self.vert_dict: self.add_vertex(f) if t not in self.vert_dict: self.add_vertex(t) self.vert_dict[f].add_neighbor(self.vert_dict[t], cost) self.vert_dict[t].add_neighbor(self.vert_dict[f], cost) self.num_edges += 1
[ "def add_edge(self, f_key, t_key, f_data=None, t_data=None, cost=0):\n if f_key not in self:\n self.add_node(f_key, data=f_data)\n if t_key not in self:\n self.add_node(t_key, data=t_data)\n f_node, t_node = self[f_key], self[t_key]\n self.nodes[f_node][t_node] = cost\n f_node.add_connection(t_node, cost)\n\n if not self.directed:\n self.nodes[t_node][f_node] = cost\n t_node.add_connection(f_node, cost)", "def add_edge(self, v1, v2, weight):", "def add_directed_edge(self, u, v, weight):\n # add u to v\n curr_edge = Edge(u, v, weight)\n curr_vertex = self.vertices[u]\n curr_vertex.add_edge(curr_edge)", "def new_cost(self, from_node, to_node):\n return from_node.cost + self.dist(from_node, to_node)", "def add_edge(source, target, label):\n if target not in elements_set: return\n if simple:\n if source != target:\n result.add_edge([source, target])\n else:\n result.add_edge([source, target, label])", "def addCost(self, x, y, c):\n if c != 0:\n if not self.isEdge(x, y):\n raise ValidException(\"Inexisting edge.\")\n if (x, y) in self.__cost:\n raise ValidException(\"Existing cost.\")\n self.__cost[(x, y)] = c", "def _add_edge_to_spanner(H, residual_graph, u, v, weight):\n H.add_edge(u, v)\n if weight:\n H[u][v][weight] = residual_graph[u][v]['weight'][0]", "def _create_cost_function_node(self):\n\n with tf.name_scope(\"cost\"):\n if self.triplet_strategy != 'none':\n if self.triplet_strategy == 'batch_all':\n _triplet_loss = batch_all_triplet_loss\n elif self.triplet_strategy == 'batch_hard':\n _triplet_loss = batch_hard_triplet_loss\n\n self.triplet_loss, data_weight, self.fraction_triplet, self.num_triplet = _triplet_loss(self.sparse_input, self.input_label, self.encode,)\n tf.summary.scalar('triplet_' + self.triplet_strategy, self.triplet_loss)\n\n self.autoencoder_loss = weighted_loss(self.sparse_input, self.input_data, self.decode, loss_func=self.loss_func, weight=data_weight)\n tf.summary.scalar('autoencoder_' + self.loss_func, self.autoencoder_loss)\n\n tf.summary.scalar('alpha', self.alpha)\n\n self.cost = self.autoencoder_loss + self.alpha * self.triplet_loss\n tf.summary.scalar('overall', self.cost)\n else:\n self.cost = weighted_loss(self.sparse_input, self.input_data, self.decode,loss_func=self.loss_func)\n tf.summary.scalar('autoencoder_' + self.loss_func, self.cost)", "def add_directed_edge(self, from_vertex, to_vertex, weight=1.0):\n\n # O(1)\n new_from_vertex = self.adjacency_table.get(from_vertex)\n new_from_vertex[len(new_from_vertex):] = [to_vertex]\n\n # O(E)\n self.edge_weights_table.add((from_vertex, to_vertex), weight)\n\n # O(V)\n self.adjacency_table.update(from_vertex, new_from_vertex)", "def tour_cost(g: Graph, tour: List[int]) -> float:\n return sum([g.edge_weight(tour[i], tour[i+1]) for i in range(len(tour)-1)])", "def add_edge(self, key, edge, weight):\n target = self.get_node(key)\n if target:\n # add edge from Node(key) to Node(edge)\n target.add_nbr(edge, weight)\n else:\n return 'Cannot add edge. Selected node does not exist'", "def set_f_cost(self):\n self.f_cost = self.get_g_cost() + self.get_h_cost()", "def add_vertex_constraint(self, label, key):", "def compute_cost(self, u, v):\n pass", "def add_edge_fun(graph):\n\n # Namespace shortcut for speed.\n succ, pred, node = graph.succ, graph.pred, graph.nodes\n\n def add_edge(u, v, **attr):\n if v not in succ: # Add nodes.\n succ[v], pred[v], node[v] = {}, {}, {}\n\n succ[u][v] = pred[v][u] = attr # Add the edge.\n\n return add_edge # Returns the function.", "def addEdge(self, u, v):\r\n self.graph[u].append(v)", "def add_node_cost_fn(self, node, srv, name, fn):\n\n self._add_node_cost_fn(node, srv, name, fn, override=True)", "def add_edge(self, src: int, dst: int, weight=1) -> None:\n if src > self.v_count - 1 or dst > self.v_count - 1:\n return\n if weight < 1:\n return\n if src == dst:\n return\n\n self.adj_matrix[src][dst] = weight", "def cost(self, from_node, to_node):\n return 1", "def append_edge(self, edge):" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns all the edges of a given vertex
def get_edges(self, vertex): dict_edges = self.vert_dict[vertex].neighbors return dict_edges
[ "def get_edges(graph, vertex):\n try:\n vertex = vertex.index\n except AttributeError:\n pass\n pairs = (\n (vertex, cur_vertex)\n for cur_vertex in range(graph.vcount())\n if graph[vertex, cur_vertex] > 0\n )\n return tuple(graph.es[idx] for idx in graph.get_eids(tuple(pairs)))", "def edges(self):\n return [e for v in self.__adj for e in v]", "def get_edges(self):\n edges = []\n vertices = self.get_vertices()\n for i, v in enumerate(vertices):\n edge = vector_between_points(v, vertices[i-1])\n edges.append(edge)\n return edges", "def getVerticesOfSelectedEdges(graph: edu.uci.ics.jung.graph.Graph) -> java.util.Collection:\n ...", "def generateEdges(self):\n edges = []\n for vertex in self.adjacency_list:\n for neighbour in self.adjacency_list[vertex]:\n if {neighbour, vertex} not in edges:\n edges.append({vertex, neighbour})\n return edges", "def get_edges(self, vertex, in_edges = True, out_edges = True, raw_results = False):\n if isinstance(vertex, Document):\n vertex_id = vertex._id\n elif (type(vertex) is str) or (type(vertex) is bytes):\n vertex_id = vertex\n else:\n raise ValueError(\"Vertex is neither a Document nor a String\")\n\n params = {\"vertex\": vertex_id}\n if in_edges and out_edges:\n pass\n elif in_edges:\n params[\"direction\"] = \"in\"\n elif out_edges:\n params[\"direction\"] = \"out\"\n else:\n raise ValueError(\"in_edges, out_edges or both must have a boolean value\")\n\n response = self.connection.session.get(self.edgesURL, params = params)\n data = response.json()\n if response.status_code == 200:\n if not raw_results:\n cached_document = []\n for edge in data[\"edges\"]:\n cached_document.append(Edge(self, edge))\n return cached_document\n else:\n return data[\"edges\"]\n else:\n raise CreationError(\"Unable to return edges for vertex: %s\" % vertex_id, data)", "def edges(self):\n return self.generateEdges()", "def in_edges(self, v):\n\n es = []\n for w in self.reverse_graph[v]:\n e = self.reverse_graph[v][w]\n if e not in es:\n es.append(e)\n return es", "def adjEdgeVerts(self):\n first = self.anyHalfEdge\n curr = self.anyHalfEdge\n while True:\n\n yield (curr.edge, curr.vertex)\n\n curr = curr.twinHE.nextHE\n if(curr == first):\n break", "def out_edges(self, v):\n\n es = []\n for w in self[v]:\n e = self[v][w]\n if e not in es:\n es.append(e)\n return es", "def getAllEdges(self, sourceVertices: java.util.Set) -> java.util.Set:\n ...", "def getConnectedEdges(*args, **kwargs):\n \n pass", "def getAdjacentVertices(self,vertex,onlyNumbers=False):\n if isinstance(vertex,int):\n numV=vertex\n else:\n numV=self.vertices.index(vertex) #Number of vertex\n adjacentList=[]\n for edge in self.edgeList:\n if edge[0]==numV:\n adjacentList.append(edge[1])\n if edge[1]==numV:\n adjacentList.append(edge[0])\n if onlyNumbers:\n return adjacentList\n else:\n return list(map(lambda r:self.vertices[r],adjacentList))", "def enumerate_edges(self):\n q = queue.Queue()\n seen = [False for _ in range(self.max_vertex+1)]\n list_of_edges = []\n q.put(0)\n while not q.empty():\n v = q.get()\n if seen[v]:\n continue\n seen[v]=True\n for u in self.geodesics_continuations(v, self.max_vertex):\n q.put(u)\n list_of_edges.append((v,u))\n return list_of_edges", "def vertices(graph):\n return graph.keys()", "def get_edges():\r\n\r\n edges = traci.edge.getIDList()\r\n return list(filter(lambda x: x[0] != \":\", edges))", "def get_graph_edges(graph):\n flattened = graph.flattened()\n return list(flattened.get_records(class_or_type_or_tuple=ProvRelation))", "def neighbours(self, vertex):\n\n if vertex not in self.adjacency_dict.keys():\n raise ValueError(\"Vertex {} is not in graph\".format(vertex))\n\n return list(self.adjacency_dict[vertex])", "def neighbours(self, vertex):\n return self._vertices[vertex]", "def get_edges(self):\n edges = []\n for n1 in self.edges.keys():\n for n2 in self.edges[n1].keys():\n edge = self.edges[n1][n2]\n if n1 != n2 and edge.constraint:\n edges.append(edge)\n return edges" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
a sequence of 2tuples (x,y) from the given string, which is a path, as represented by SVG's or 'd' attribute.
def parseSVGPath(pathstring): actions = [Action(part) for part in PARTFINDER.findall(pathstring)] # assert (len(parts) % 2) == 0, "Path string does not contain even number of x's and y's" r = [] for a in [a for a in actions if a.type in 'ML']: x, y = a.parts r.append((x,y)) return r
[ "def tuplesPath(path):\n\n\treturn map(lambda n: (n.location.x, n.location.y), path)", "def string_to_coordinates(s):\n\t\n\tx, y = map(float, s.split(maxsplit = 2))\n\t\n\treturn x, y", "def _ParseD(self, d_str):\n #PATH_IDENTIFIERS = \"ML\"\n chars_to_remove = \"z|Z\"\n\n self.d_str = d_str\n self.d_str = re.sub(chars_to_remove, '', self.d_str)\n self.d_str = re.sub(\" +\", ' ', self.d_str).strip()\n \n ListOfPaths = list(filter(None, self.d_str.split(\"M\"))) \n ListOfPoints = [] \n for path in ListOfPaths:\n Points = []\n StringsWCoordinates = path.split(\"L\")\n for string in StringsWCoordinates:\n try:\n x,y = re.split(\",\" ,string)\n except ValueError:\n print(\"!!! Tried to unpack: \" + string + \" !!!\")\n raise\n Points.append((float(x),float(y)))\n ListOfPoints.append(Points) \n return ListOfPoints", "def _extract_svg_coordinates_helper_function_(paths, number_of_samples=30):\n path_coordinates = []\n x_coord = []\n y_coord = []\n\n for idx in paths:\n for jdy in idx:\n for j in range(number_of_samples):\n path_coordinates.append(jdy.point(j / (number_of_samples - 1)))\n\n for k in range(len(path_coordinates)):\n xi = path_coordinates[k].real\n yi = path_coordinates[k].imag\n\n x_coord.append(xi)\n y_coord.append(yi)\n\n return list(zip(np.asarray(x_coord), np.asarray(y_coord)))", "def svg_str_to_tuple(str_list):\n new_list = []\n for item in str_list:\n new_list.append(eval(\"({})\".format(item)))\n\n return new_list", "def binary_path_to_coordinates(path):\n\n x = 0\n y = 0\n splitted_path = path.split('/')\n for xy in splitted_path:\n x = x << 1\n y = y << 1\n x += int(xy[0])\n y += int(xy[1])\n return (x, y, len(splitted_path))", "def parse_stop_coordinates(s):\n xlo_node = s.getElementsByTagName(\"GEOMETRY_XLO\")\n ylo_node = s.getElementsByTagName(\"GEOMETRY_YLO\")\n return xlo_node[0].firstChild.data, ylo_node[0].firstChild.data", "def extract_start_end_points_of_linestring(linestring: LineString) -> Tuple[Tuple, Tuple]:\n start = (linestring.coords.xy[0][0], linestring.coords.xy[1][0])\n end = (linestring.coords.xy[0][-1], linestring.coords.xy[1][-1])\n return start, end", "def parse(string):\n elements = Path.separator_re.split(string)[1:]\n separators = elements[::2]\n parts = elements[1::2]\n if not len(elements) == 2 * len(separators) == 2 * len(parts):\n raise ValueError\n\n nodes = []\n for separator, part in equizip(separators, parts):\n if separator == Path.separator:\n nodes.append(Path.BrickName(part))\n elif Path.param_separator == Path.param_separator:\n nodes.append(Path.ParamName(part))\n else:\n # This can not if separator_re is a correct regexp\n raise ValueError(\"Wrong separator {}\".format(separator))\n\n return Path(nodes)", "def parse_point(coords_str):\n x, y = coords_str.split()\n return float(x), float(y)", "def parse_coords(coords_str):\n itr = (float(v) for v in coords_str.split())\n return zip(itr, itr)", "def asSVGPath(self):\n segs = self.asSegments()\n pathParts = [\"M %f %f\" % (segs[0][0].x, segs[0][0].y)]\n\n operators = \"xxLQC\"\n for s in segs:\n op = operators[len(s)] + \" \"\n for pt in s[1:]:\n op = op + \"%f %f \" % (pt.x, pt.y)\n pathParts.append(op)\n if self.closed:\n pathParts.append(\"Z\")\n\n return \" \".join(pathParts)", "def get_point_list(data):\n try:\n ls_pair = data.split(' ')\n except AttributeError:\n lnd_points = data.xpath(\"(.//@points)[1]\")\n s_points = lnd_points[0]\n ls_pair = s_points.split(' ')\n l_xy = list()\n for s_pair in ls_pair: # s_pair = 'x,y'\n (sx, sy) = s_pair.split(',')\n l_xy.append((int(sx), int(sy)))\n return l_xy", "def parse_path(instructions: list) -> list:\n path = [(0, 0)]\n for instruction in instructions:\n direction = instruction[0]\n value = int(instruction[1:])\n old_x, old_y = path[-1]\n if direction == 'R':\n new_x = old_x + value\n new_y = old_y\n elif direction == 'L':\n new_x = old_x - value\n new_y = old_y\n elif direction == 'U':\n new_x = old_x\n new_y = old_y + value\n elif direction == 'D':\n new_x = old_x\n new_y = old_y - value\n else:\n raise ValueError('Invalid direction!')\n path.append((new_x, new_y))\n return path", "def result_coords_from_path(path):\n model_id, freq, genotype = re.search('model=(.*)__freq=(.*)__genotype=(.*)', path).groups()\n return model_id, float(freq), genotype", "def parse_area_coords(string):\n _, _, left_top, area = string.split(' ')\n left, top = [int(num) for num in left_top[:-1].split(',')]\n width, height = [int(num) for num in area.split('x')]\n\n return [(i, j) for i in range(left, left + width) for j in range(top, top + height)]", "def parse_path_args(arg_str):\n path_split = arg_str.lower().split()\n if len(path_split) == 0:\n return None, None\n else:\n path_name, *path_args = path_split\n path = PIXEL_PATH_DICT.get(path_name, None)\n\n path_args = [parse_single_path_arg(a) for a in path_args]\n if None in path_args:\n print(\"Error: Arguments for path must be all of type 'name=value'.\")\n exit()\n path_kwargs = dict(path_args)\n # some janky reflection to get the number of arguments that this type of path accepts\n arg_count = path.__code__.co_argcount - 1\n if arg_count < len(path_kwargs):\n print(\"Error: Path '%s' only takes %d argument(s).\" % (path_name, arg_count))\n exit()\n return path_name, path_kwargs", "def getVillageCoords(self, s=''):\n if s: self.parse(s)\n # we try to get village coordinates\n c = {}\n nx = self.doc.getElementById(\"x\")\n ny = self.doc.getElementById(\"y\")\n #print nx.textContent, ny.textContent\n c['x'] = nx.textContent\n c['y'] = ny.textContent\n return c", "def string_to_shape(shape_string: str) -> Optional[List[Position]]:\n if is_valid_shape_string(shape_string):\n positions = list()\n position_strings = shape_string.split(\";\")\n for pos_str in position_strings:\n vals = pos_str.split(\",\")\n x_val = vals[0][1:]\n y_val = vals[1][:-1]\n positions.append((int(x_val), int(y_val)))\n return positions\n else:\n return None" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for email_subscriptions_mailing_lists_add
def test_email_subscriptions_mailing_lists_add(self): pass
[ "def test_email_subscriptions_mailing_lists_list(self):\n pass", "def test001MethodsForEmaillist(self):\n \n user_name = 'YujiMatsuo-' + self.postfix\n family_name = 'Matsuo'\n given_name = 'Yuji'\n password = '123$$abc'\n suspended = 'false'\n\n try:\n user_yuji = self.apps_client.CreateUser(\n user_name=user_name, family_name=family_name, given_name=given_name,\n password=password, suspended=suspended)\n except Exception, e:\n self.fail('Unexpected exception occurred: %s' % e)\n\n self.created_users.append(user_yuji)\n\n user_name = 'TaroMatsuo-' + self.postfix\n family_name = 'Matsuo'\n given_name = 'Taro'\n password = '123$$abc'\n suspended = 'false'\n\n try:\n user_taro = self.apps_client.CreateUser(\n user_name=user_name, family_name=family_name, given_name=given_name,\n password=password, suspended=suspended)\n except Exception, e:\n self.fail('Unexpected exception occurred: %s' % e)\n\n self.created_users.append(user_taro)\n\n # tests CreateEmailList method\n list_name = 'list01-' + self.postfix\n try:\n created_email_list = self.apps_client.CreateEmailList(list_name)\n except Exception, e:\n self.fail('Unexpected exception occurred: %s' % e)\n\n self.assert_(isinstance(created_email_list, gdata.apps.EmailListEntry),\n \"Return value of CreateEmailList method must be an instance of \" +\n \"EmailListEntry: %s\" % created_email_list)\n self.assertEquals(created_email_list.email_list.name, list_name)\n self.created_email_lists.append(created_email_list)\n\n # tests AddRecipientToEmailList method\n try:\n recipient = self.apps_client.AddRecipientToEmailList(\n user_yuji.login.user_name + '@' + apps_domain,\n list_name)\n except Exception, e:\n self.fail('Unexpected exception occurred: %s' % e)\n\n self.assert_(isinstance(recipient, gdata.apps.EmailListRecipientEntry),\n \"Return value of AddRecipientToEmailList method must be an instance \" +\n \"of EmailListRecipientEntry: %s\" % recipient)\n self.assertEquals(recipient.who.email, \n user_yuji.login.user_name + '@' + apps_domain)\n\n try:\n recipient = self.apps_client.AddRecipientToEmailList(\n user_taro.login.user_name + '@' + apps_domain,\n list_name)\n except Exception, e:\n self.fail('Unexpected exception occurred: %s' % e)\n\n # tests RetrieveAllRecipients method\n try:\n recipient_feed = self.apps_client.RetrieveAllRecipients(list_name)\n except Exception, e:\n self.fail('Unexpected exception occurred: %s' % e)\n\n self.assert_(isinstance(recipient_feed, gdata.apps.EmailListRecipientFeed),\n \"Return value of RetrieveAllRecipients method must be an instance \" +\n \"of EmailListRecipientFeed: %s\" % recipient_feed)\n self.assertEquals(len(recipient_feed.entry), 2)\n\n # tests RemoveRecipientFromEmailList method\n try:\n self.apps_client.RemoveRecipientFromEmailList(\n user_taro.login.user_name + '@' + apps_domain, list_name)\n except Exception, e:\n self.fail('Unexpected exception occurred: %s' % e)\n\n # make sure that removal succeeded.\n try:\n recipient_feed = self.apps_client.RetrieveAllRecipients(list_name)\n except Exception, e:\n self.fail('Unexpected exception occurred: %s' % e)\n\n self.assert_(isinstance(recipient_feed, gdata.apps.EmailListRecipientFeed),\n \"Return value of RetrieveAllRecipients method must be an instance \" +\n \"of EmailListRecipientFeed: %s\" % recipient_feed)\n self.assertEquals(len(recipient_feed.entry), 1)\n\n # tests RetrieveAllEmailLists\n try:\n list_feed = self.apps_client.RetrieveAllEmailLists()\n except Exception, e:\n self.fail('Unexpected exception occurred: %s' % e)\n self.assert_(isinstance(list_feed, gdata.apps.EmailListFeed),\n \"Return value of RetrieveAllEmailLists method must be an instance\" +\n \"of EmailListFeed: %s\" % list_feed)\n succeed = False\n for email_list in list_feed.entry:\n if email_list.email_list.name == list_name:\n succeed = True\n self.assert_(succeed, \"There must be an email list named %s\" % list_name)\n \n # tests RetrieveEmailLists method.\n try:\n list_feed = self.apps_client.RetrieveEmailLists(\n user_yuji.login.user_name + '@' + apps_domain)\n except Exception, e:\n self.fail('Unexpected exception occurred: %s' % e)\n self.assert_(isinstance(list_feed, gdata.apps.EmailListFeed),\n \"Return value of RetrieveEmailLists method must be an instance\" +\n \"of EmailListFeed: %s\" % list_feed)\n succeed = False\n for email_list in list_feed.entry:\n if email_list.email_list.name == list_name:\n succeed = True\n self.assert_(succeed, \"There must be an email list named %s\" % list_name)", "def test_user_list_subscriptions(self):\n pass", "def test_add_subscriber_with_subs(bond_with_subs):\n new_sub = Subscriber(sid='lmoreo200',\n name='Lynne',\n email='lynne@shlomo.com')\n bond_with_subs.add_subscriber(new_sub)\n assert len(bond_with_subs.subscribers) == 4\n assert new_sub.sid in bond_with_subs.subscribers.keys()", "def test_get_list_unsubscribe_recipients(self):\n pass", "def test_add_email_addresses(self):\n self.assert_requires_auth(self.instance.add_email_addresses, [])", "def test_admin_subscriber_view_add(self):\n response = self.client.get('/admin/dialer_campaign/subscriber/add/')\n self.failUnlessEqual(response.status_code, 200)\n\n response = self.client.post(\n '/admin/dialer_campaign/subscriber/add/',\n data={\n \"status\": \"1\",\n \"campaign\": \"1\",\n \"duplicate_contact\": \"1234567\",\n \"count_attempt\": \"1\",\n \"completion_count_attempt\": \"1\",\n })\n self.assertEqual(response.status_code, 200)", "def test_add_email_addresses(self):\n self.instance.add_email_addresses(\n [\"example1@example.com\", \"example2@example.com\"]\n )\n\n self.post_called_with(\n url_for(\"user/emails\"),\n data=[\"example1@example.com\", \"example2@example.com\"],\n )", "def test_user_current_list_subscriptions(self):\n pass", "def test_add_domains(add_siteslinkingin_domains):\n msg = 'Load of SitesLinkingIn domains into Kafka error'\n assert add_siteslinkingin_domains == 100, msg", "def test_subscriber_list(self):\n response = self.client.get('/subscribers/')\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, 'frontend/subscriber/list.html')\n\n request = self.factory.get('/subscribers/')\n request.user = self.user\n request.session = {}\n response = subscriber_list(request)\n self.assertEqual(response.status_code, 200)", "def test_add_subscriber_no_subs(bond_no_subs):\n new_sub = Subscriber(sid='lmoreo200',\n name='Lynne',\n email='lynne@shlomo.com')\n bond_no_subs.add_subscriber(new_sub)\n assert len(bond_no_subs.subscribers) == 1\n assert new_sub.sid in bond_no_subs.subscribers.keys()", "def test_notification_list(self):\n pass", "def test_add_donor_already_in_list():\n mail_room2.add_donor('Steve')\n assert len(mail_room2.list_of_donors) == 2\n mail_room2.add_donor(\"Steve\")\n assert len(mail_room2.list_of_donors) == 2", "def test_email_subscribe(self):\n self.user.subscribe_to_replied_threads = UserModel.SUBSCRIBE_ALL\n self.user.save()\n\n response = self.client.post(\n self.api_link, data={\n 'post': \"This is test response!\",\n }\n )\n self.assertEqual(response.status_code, 200)\n\n # user has subscribed to thread\n subscription = self.user.subscription_set.get(thread=self.thread)\n\n self.assertEqual(subscription.category_id, self.category.id)\n self.assertTrue(subscription.send_email)", "def test_add_to_queue(self):\n job = self.create_job()\n job.add_to_queue()\n self.verify_adds_to_queue(job.key, 'scheduled', '/api/tasks/send')", "def test_user_add_email(self):\n pass", "def test_create_subscriptions(self):\n response = self.post_json(self.resource, {\n 'target_id': 1,\n 'target_type': 'project'\n })\n subscription = response.json\n\n self.assertEqual('project', subscription['target_type'])\n self.assertEqual(1, subscription['target_id'])\n self.assertEqual(2, subscription['user_id'])\n self.assertIsNotNone(subscription['id'])\n\n response2 = self.post_json(self.resource, {\n 'user_id': 2,\n 'target_id': 2,\n 'target_type': 'project'\n })\n subscription2 = response2.json\n\n self.assertEqual('project', subscription2['target_type'])\n self.assertEqual(2, subscription2['target_id'])\n self.assertEqual(2, subscription2['user_id'])\n self.assertIsNotNone(subscription2['id'])", "def test_can_send_email_to_multiple_recipients(self):\n\n new_email = mail.Mail()\n email_recipient = 'foo@company.com,bar@company.com'\n email_sender = 'xyz@company.com'\n email_connector_config = {\n 'fake_sendgrid_key': 'xyz010'\n }\n email_util = sendgrid_connector.SendgridConnector(\n email_sender,\n email_recipient,\n email_connector_config)\n new_email = email_util._add_recipients(new_email, email_recipient)\n\n self.assertEqual(1, len(new_email.personalizations))\n\n added_recipients = new_email.personalizations[0].tos\n self.assertEqual(2, len(added_recipients))\n self.assertEqual('foo@company.com', added_recipients[0].get('email'))\n self.assertEqual('bar@company.com', added_recipients[1].get('email'))" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for email_subscriptions_mailing_lists_list
def test_email_subscriptions_mailing_lists_list(self): pass
[ "def test_email_subscriptions_mailing_lists_add(self):\n pass", "def test_get_list_unsubscribe_recipients(self):\n pass", "def test_user_list_subscriptions(self):\n pass", "def test_user_current_list_subscriptions(self):\n pass", "def testListSubscriptionIDs(self, mock_list):\n mock_list.return_value = MOCK_LIST_IDS\n subscription_ids = FAKE_ACCOUNT.resource.ListSubscriptionIDs()\n self.assertEqual(2, len(subscription_ids))\n self.assertEqual('fake-subscription-id-1', subscription_ids[0])", "def test001MethodsForEmaillist(self):\n \n user_name = 'YujiMatsuo-' + self.postfix\n family_name = 'Matsuo'\n given_name = 'Yuji'\n password = '123$$abc'\n suspended = 'false'\n\n try:\n user_yuji = self.apps_client.CreateUser(\n user_name=user_name, family_name=family_name, given_name=given_name,\n password=password, suspended=suspended)\n except Exception, e:\n self.fail('Unexpected exception occurred: %s' % e)\n\n self.created_users.append(user_yuji)\n\n user_name = 'TaroMatsuo-' + self.postfix\n family_name = 'Matsuo'\n given_name = 'Taro'\n password = '123$$abc'\n suspended = 'false'\n\n try:\n user_taro = self.apps_client.CreateUser(\n user_name=user_name, family_name=family_name, given_name=given_name,\n password=password, suspended=suspended)\n except Exception, e:\n self.fail('Unexpected exception occurred: %s' % e)\n\n self.created_users.append(user_taro)\n\n # tests CreateEmailList method\n list_name = 'list01-' + self.postfix\n try:\n created_email_list = self.apps_client.CreateEmailList(list_name)\n except Exception, e:\n self.fail('Unexpected exception occurred: %s' % e)\n\n self.assert_(isinstance(created_email_list, gdata.apps.EmailListEntry),\n \"Return value of CreateEmailList method must be an instance of \" +\n \"EmailListEntry: %s\" % created_email_list)\n self.assertEquals(created_email_list.email_list.name, list_name)\n self.created_email_lists.append(created_email_list)\n\n # tests AddRecipientToEmailList method\n try:\n recipient = self.apps_client.AddRecipientToEmailList(\n user_yuji.login.user_name + '@' + apps_domain,\n list_name)\n except Exception, e:\n self.fail('Unexpected exception occurred: %s' % e)\n\n self.assert_(isinstance(recipient, gdata.apps.EmailListRecipientEntry),\n \"Return value of AddRecipientToEmailList method must be an instance \" +\n \"of EmailListRecipientEntry: %s\" % recipient)\n self.assertEquals(recipient.who.email, \n user_yuji.login.user_name + '@' + apps_domain)\n\n try:\n recipient = self.apps_client.AddRecipientToEmailList(\n user_taro.login.user_name + '@' + apps_domain,\n list_name)\n except Exception, e:\n self.fail('Unexpected exception occurred: %s' % e)\n\n # tests RetrieveAllRecipients method\n try:\n recipient_feed = self.apps_client.RetrieveAllRecipients(list_name)\n except Exception, e:\n self.fail('Unexpected exception occurred: %s' % e)\n\n self.assert_(isinstance(recipient_feed, gdata.apps.EmailListRecipientFeed),\n \"Return value of RetrieveAllRecipients method must be an instance \" +\n \"of EmailListRecipientFeed: %s\" % recipient_feed)\n self.assertEquals(len(recipient_feed.entry), 2)\n\n # tests RemoveRecipientFromEmailList method\n try:\n self.apps_client.RemoveRecipientFromEmailList(\n user_taro.login.user_name + '@' + apps_domain, list_name)\n except Exception, e:\n self.fail('Unexpected exception occurred: %s' % e)\n\n # make sure that removal succeeded.\n try:\n recipient_feed = self.apps_client.RetrieveAllRecipients(list_name)\n except Exception, e:\n self.fail('Unexpected exception occurred: %s' % e)\n\n self.assert_(isinstance(recipient_feed, gdata.apps.EmailListRecipientFeed),\n \"Return value of RetrieveAllRecipients method must be an instance \" +\n \"of EmailListRecipientFeed: %s\" % recipient_feed)\n self.assertEquals(len(recipient_feed.entry), 1)\n\n # tests RetrieveAllEmailLists\n try:\n list_feed = self.apps_client.RetrieveAllEmailLists()\n except Exception, e:\n self.fail('Unexpected exception occurred: %s' % e)\n self.assert_(isinstance(list_feed, gdata.apps.EmailListFeed),\n \"Return value of RetrieveAllEmailLists method must be an instance\" +\n \"of EmailListFeed: %s\" % list_feed)\n succeed = False\n for email_list in list_feed.entry:\n if email_list.email_list.name == list_name:\n succeed = True\n self.assert_(succeed, \"There must be an email list named %s\" % list_name)\n \n # tests RetrieveEmailLists method.\n try:\n list_feed = self.apps_client.RetrieveEmailLists(\n user_yuji.login.user_name + '@' + apps_domain)\n except Exception, e:\n self.fail('Unexpected exception occurred: %s' % e)\n self.assert_(isinstance(list_feed, gdata.apps.EmailListFeed),\n \"Return value of RetrieveEmailLists method must be an instance\" +\n \"of EmailListFeed: %s\" % list_feed)\n succeed = False\n for email_list in list_feed.entry:\n if email_list.email_list.name == list_name:\n succeed = True\n self.assert_(succeed, \"There must be an email list named %s\" % list_name)", "def test_notification_list(self):\n pass", "def test_self_mailers_list_with_scheduled_param(self):\n self.mock_api.self_mailers_list = self.mock_list_of_self_mailers\n self_mailers = self.mock_api.self_mailers_list(scheduled=True)\n self.assertIsNotNone(self_mailers)\n self.assertEqual(len(self_mailers[\"data\"]), 2)", "def test_subscriber_list(self):\n response = self.client.get('/subscribers/')\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, 'frontend/subscriber/list.html')\n\n request = self.factory.get('/subscribers/')\n request.user = self.user\n request.session = {}\n response = subscriber_list(request)\n self.assertEqual(response.status_code, 200)", "def test_list(self):\n payloads = [\n b'payload A',\n b'second payload'\n b'payload 3+'\n ]\n res = []\n provider = payload_provider.List(payloads)\n for payload in provider:\n res.append(payload)\n for num, payload in enumerate(payloads):\n self.assertEqual(res[num], payload, 'Payload not expected in position {0}'.format(num))", "def test_user_list_emails(self):\n pass", "def test_self_mailers_list(self):\n self.mock_api.self_mailers_list = self.mock_list_of_self_mailers\n self_mailers = self.mock_api.self_mailers_list()\n self.assertIsNotNone(self_mailers)\n self.assertEqual(len(self_mailers[\"data\"]), 2)", "def test_self_mailers_list_with_mail_type_param(self):\n self.mock_api.self_mailers_list = self.mock_list_of_self_mailers\n self_mailers = self.mock_api.self_mailers_list(mail_type=MailType('usps_first_class'))\n self.assertIsNotNone(self_mailers)\n self.assertEqual(len(self_mailers[\"data\"]), 2)", "def test_admin_subscriber_view_list(self):\n response = self.client.get('/admin/dialer_campaign/subscriber/')\n self.failUnlessEqual(response.status_code, 200)", "def test_list(self):\n an = baker.make(\"Announcement\", expiration=datetime.now()+timedelta(days=1))\n an2 = baker.make(\"Announcement\",expiration=datetime.now()-timedelta(days=2))\n r = self.client.get(reverse('makeReports:announ-list'))\n self.assertContains(r,an.text)\n self.assertContains(r,an2.text)", "def test_self_mailers_list_with_before_param(self):\n self.mock_api.self_mailers_list = self.mock_list_of_self_mailers\n self_mailers = self.mock_api.self_mailers_list(before=\"before\")\n self.assertIsNotNone(self_mailers)\n self.assertEqual(len(self_mailers[\"data\"]), 2)", "def test_self_mailers_list_with_after_param(self):\n self.mock_api.self_mailers_list = self.mock_list_of_self_mailers\n self_mailers = self.mock_api.self_mailers_list(after=\"after\")\n self.assertIsNotNone(self_mailers)\n self.assertEqual(len(self_mailers[\"data\"]), 2)", "def test_getting_all_subscribers(self):\n response = self.app.get(\n \"/api/1.0/subscribers/\",\n headers={\n 'User': self.admin_id,\n 'Authorization': self.valid_tokens[2]\n }\n )\n data = json.loads(response.data.decode())\n\n self.assertEqual(200, response.status_code)\n self.assertTrue(\"subscribers\" in data)\n self.assertEqual(1, len(data[\"subscribers\"]))\n self.assertEqual(self.subscriber_with_email_id, data[\"subscribers\"][0][\"id\"])", "def verify_list(mailchimp, list_id, course_id):\n lists = mailchimp.lists(filters={'list_id': list_id})['data']\n\n if len(lists) != 1:\n log.error('incorrect list id')\n return False\n\n list_name = lists[0]['name']\n\n log.debug('list name: %s', list_name)\n\n # check that we are connecting to the correct list\n parts = course_id.replace('_', ' ').replace('/', ' ').split()\n count = sum(1 for p in parts if p in list_name)\n if count < 3:\n log.info(course_id)\n log.info(list_name)\n log.error('course_id does not match list name')\n return False\n\n return True" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Log parameters and/or response of the wrapped/decorated function using logging package
def log(parameters=False, response=False): def decorator(func): def wrapper(*args, **kwargs): if parameters: LOGGER.info(PARAM_LOG_MESSAGE, func.__name__, args) func_response = func(*args, **kwargs) if response: LOGGER.info(RESPONSE_LOG_MESSAGE, func.__name__, func_response) return func_response return wrapper return decorator
[ "def log_call(func):\n @wraps(func)\n def logged(*args, **kawrgs):\n header = \"-\" * len(func.__name__)\n print(green(\"\\n\".join([header, func.__name__, header]), bold=True))\n return func(*args, **kawrgs)\n return logged", "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_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_decorator(func):\n\t\t@functools.wraps(func)\n\t\tdef log_wrapper(*args, **kwargs):\n\t\t\t\"\"\"Prints info before and after start of the function\"\"\"\t\t\n\t\t\tdebug_string = \"Start of {}\".format(func.__name__)\n\n\t\t\tlogger.log(logging.DEBUG, debug_string)\n\n\t\t\tresult = func(*args, **kwargs)\n\t\t\n\t\t\tdebug_string = \"End of {}\".format(func.__name__)\n\t\t\tlogger.log(logging.DEBUG, debug_string)\n\t\t\t\n\t\t\treturn result\n\t\t\t\n\t\tif DEBUG:\n\t\t\treturn log_wrapper\n\t\telse:\n\t\t\treturn func", "def __call__(self, func):\n # set logger if it was not set earlier\n if not self.logger:\n formatter = logging.Formatter('%(asctime)s %(levelno)s %(name)s @ %(message)s')\n self.logger = logging.getLogger(func.__module__)\n self.logger.setLevel(logging.INFO)\n console = logging.StreamHandler()\n console.setFormatter(formatter)\n console.setLevel(logging.INFO)\n self.logger.addHandler(console)\n\n @functools.wraps(func)\n def wrapper(*args, **kwds):\n self.logger.info(self.ENTRY_MESSAGE.format(func.__name__))\n f_result = func(*args, **kwds)\n self.logger.info(self.RETURNS_MESSAGES.format(pformat(f_result)))\n self.logger.info(self.EXIT_MESSAGE.format(func.__name__))\n return f_result\n return wrapper", "def logged(f):\n if hasattr(f, 'call_log'):\n return f\n\n @wraps(f)\n def wrapped_f(*args, **kwargs):\n value = wrapped_f.call_log.get(*args, **kwargs)\n if value is None:\n value = f(*args, **kwargs)\n wrapped_f.call_log.insert(value, *args, **kwargs)\n return value\n wrapped_f.call_log = CallLog()\n return wrapped_f", "def log(func):\n @wraps(func)\n def wrapped(update, context, *args, **kwargs):\n id = update.effective_user.id\n name = update.effective_user.username\n context.user_data['meta'] = {\n 'last_talked': update.effective_message['date'],\n 'user_details': update.effective_message.to_dict()['from']\n }\n logging.info(f'{name} ({id}) said:\\n{update.effective_message.text}')\n return func(update, context, *args, **kwargs)\n return wrapped", "def log_i(func):\n def log_wrapper(*args, **kwargs):\n \"\"\"send function call to kivy log\"\"\"\n log_entry = \"{}()\".format(func.__name__)\n kivy.logger.Logger.info(log_entry)\n return func(*args, **kwargs)\n return log_wrapper", "def loggable(\n log_addr='*',\n *,\n log_args=True,\n log_results=True,\n log_enter=True,\n log_exit=True,\n log_path=True,\n short=None,\n long=None,\n short_det = None,\n long_det = None,\n hidden=False,\n):\n verbosity_settings = dict(\n log_args = log_args,\n log_results = log_results,\n log_enter = log_enter,\n log_exit = log_exit,\n log_path = log_path,\n )\n\n def loggable_decorator(x):\n \"\"\" Actual decorator for \"loggables\"\n\n It decorates functions/methods/property accesors, but also classes with any of the above.\n \"\"\"\n nonlocal log_addr, verbosity_settings, log_path, hidden\n # If it is a function or method\n if isinstance(x, types.FunctionType):\n # replace the wildcard `*` in the given name with the actual name of the function\n log_addr = log_addr.replace('*', x.__name__.strip('_'), 1)\n if x.__qualname__ != x.__name__:\n # It is a method, so a manager is created that has parent temporarily set to `None` it will be sorted\n # out when the class will be decorated. It is also temporarily attached to `_methodtolog` property of\n # the method. It hangs there until the class is decorated -- then all the `_methodtolog` will be cleaned\n # up. If not, the logger is \"dangling\" -- that means that the class of this method was not decorated as\n # it should.\n x._methodtolog = LogSimpleManager(\n addr = log_addr,\n log_path = log_path,\n func_parent = None,\n func_name = x.__name__,\n verbosity_settings = verbosity_settings,\n hidden = hidden,\n )\n else:\n # standalone function, so module can be given for a parent\n lfm = LogSimpleManager(\n addr = log_addr,\n log_path = log_path,\n func_parent = inspect.getmodule(x),\n func_name = x.__name__,\n verbosity_settings = verbosity_settings,\n hidden = hidden,\n )\n # That's it for a function, so it can be added to the registry\n lfm.add(auto_on=main._logging_enabled)\n elif isinstance(x, classmethod):\n # if it is a class method, the manager is created similarily as for a method, only the name must be digged a\n # one step deeper\n log_addr = log_addr.replace('*', x.__func__.__name__.strip('_'), 1)\n x._methodtolog = LogSimpleManager(\n addr = log_addr,\n log_path = log_path,\n func_parent = None,\n func_name = x.__func__.__name__,\n verbosity_settings = verbosity_settings,\n hidden = hidden,\n )\n elif isinstance(x, type):\n # Finally a class is decorated.\n if issubclass(x, LogManager):\n # If it is an \"aunt\" class, the decorator performes a singlenton semantic That is it creates a single\n # object, and registers it in the registry\n manager = x(log_addr, log_path, hidden)\n manager.add(auto_on=main._logging_enabled)\n else:\n # It is a regular user's class Now we will hopefully collect all the managers that were temporarily\n # attached to methods `_methodtolog` properties\n log_addr = log_addr.replace('*', x.__name__.strip('_'), 1)\n for prop_name in dir(x):\n # for each member of the class we try...\n # First we must find the member, and that means we must traverse the Method Resolution Order\n for mro_class in x.__mro__:\n try:\n member = x.__getattribute__(mro_class, prop_name)\n except AttributeError:\n # The member is not in this class so we move one step in MRO.\n pass\n else:\n # We found the member, so we can break from the loop\n break\n else:\n # The loop was never broken.\n # So we haven't found the member anuwhere in the `__mro__` - this should never happen, because\n # the member was returned by `dir(x)` so it should exist somwhere. To fail safe (quaietly) we\n # assign a `None` value to the member that will fail in expected manner down the line at\n # `member._methodtolog.log_path`.\n member = None\n if isinstance(member, property):\n # if it is an actual property we will have potentially three managers to sort out\n members = ((member.fget, 'fget'), (member.fset, 'fset'), (member.fdel, 'fdel'))\n else:\n # if it is a regular method we have just one manager\n members = ((member, None),)\n for member, subname in members:\n try:\n # Now we just try to update the manager that is hanging in the function. If it is not\n # hanging there that means that we have something other than decorated method here end the\n # exception occurs.\n #\n # The `log_path` value is really only meaningful in the class decorator, but it is needed in\n # all method managers, hence it is copied here\n member._methodtolog.log_path = log_path\n # New name for the wrapper is created from the name given in the class decorator, and the\n # name obtained when the method was decorated\n member._methodtolog.addr = log_addr + '.' + member._methodtolog.addr\n # the parent is finally known and can be assigned to the manager\n member._methodtolog.func_parent = x\n # if `subname` we are in a property\n if subname:\n # what was stored before in the manager as a name in fact was the name of the property\n # so it has to be rewriten\n member._methodtolog.set_as_property_manager(member._methodtolog.func_name, subname)\n # Function name is now one of the accesor functions: `fget`, `fset` or `fdel`\n # The method is finnaly properly set up and can be added to the registry\n member._methodtolog.add(auto_on=main._logging_enabled)\n # This temporary member is no longer needed\n del member._methodtolog\n except Exception:\n # It was not a decorated method (most of the time it is not), so we do nothing\n pass\n # When we decorate a class we can assign a logging \"repr\"s here. One is \"short\" and one is \"long\". For\n # description see docstring of `enh_repr` function.\n loggable_class(x, short=short, long=long, short_det=short_det, long_det=long_det)\n # After decoration we return the original method/function, so the class/module has exactly the same structure as\n # it would have it wasn't decorated at all. All the information needed is stored in the managers now. When the\n # logging is turned on, the wrappers are created, and module/class is altered\n return x\n return loggable_decorator", "def log_output(func: Callable):\n\tdef wrapper_log(*args, **kwargs):\n\t\toutput = func(*args, **kwargs)\n\t\tlog(text=output, \n\t\t\tlevel=Logging.INFO.value)\n\t\treturn output\n\treturn wrapper_log", "def hook_Log(state, level, ea):\n DeepManticore(state).api_log(level, ea)", "def log_argumrnts(logger):\n def decorator(func):\n @wraps\n def wraped_func(*args, **kwargs):\n args = inspect.getcallargs(func, *args, **kwargs)\n msg = \"call `{}` with arguments: {}\".format(func.__name__, args)\n logger.info(msg)\n return func(*args, **kwargs)\n return wraped_func\n return decorator", "def timer_logger(orig_func):\n\n @wraps(orig_func)\n def wrapper(*args, **kwargs):\n\n start_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n t1 = time()\n\n log_file_path = '../QUBEKit_log.txt'\n\n with open(log_file_path, 'a+') as log_file:\n log_file.write(f'{orig_func.__qualname__} began at {start_time}.\\n\\n')\n log_file.write(f'Docstring for {orig_func.__qualname__}:\\n {orig_func.__doc__}\\n\\n')\n\n time_taken = time() - t1\n\n mins, secs = divmod(time_taken, 60)\n hours, mins = divmod(mins, 60)\n\n secs, remain = str(float(secs)).split('.')\n\n time_taken = f'{int(hours):02d}h:{int(mins):02d}m:{int(secs):02d}s.{remain[:5]}'\n end_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n\n log_file.write(f'{orig_func.__qualname__} finished in {time_taken} at {end_time}.\\n\\n')\n # Add some separation space between function / method logs.\n log_file.write(f'{\"-\" * 50}\\n\\n')\n\n return orig_func(*args, **kwargs)\n return wrapper", "def log_return(fn):\n\t@wraps(fn)\n\tdef inside(*args, **kwargs):\n\t\treturn_value = fn(*args, **kwargs)\n\t\tgv.RETURN_LOG_FILE += f'Fn : {fn.__name__}\\n{return_value}\\n\\n'\n\t\treturn return_value\n\treturn inside", "def rpc_logger(func):\n @wraps(func)\n async def wrap(self, *args, **kwargs):\n try:\n return await func(self, *args, **kwargs)\n except Exception as ex:\n logging.error(ex)\n raise\n\n return wrap", "def logged(level,name=None,message=None):\n\n def decorate(func):\n logname = name if name else func.__module__\n \n log = logging.getLogger(logname)\n logmsg = message if message else func.__name__\n\n @wraps(func)\n def wrapper(*args,**kwargs):\n\n log.log(level,logmsg)\n return func(*args,**kwargs)\n return wrapper\n\n return decorate", "def debug_decorator_factory(logger):\n\tdef debug_decorator(func):\n\t\t\"\"\"\n\t\tDecorator that returns wrapper that prints arguments of function \n\t\tArgs:\n\t\t\tlogger(logging.Logger): logger where logs will be printed\n\t\t\tfunc(function): function that will be decorated\n\t\tReturns:\n\t\t\t wrapper that prints info in logger before and after start of the func\n\t\t\"\"\"\n\t\t@functools.wraps(func)\n\t\tdef debug_wrapper(*args, **kwargs):\n\t\t\t\"\"\"Prints info before and after start of the function\"\"\"\t\t\n\t\t\tlist_of_args = [str(arg) for arg in args]\n\t\t\tlist_of_kwargs = [\"{} : {}\".format(name, arg) for name, arg in kwargs]\n\n\t\t\tdebug_string = \"args: {} ; \\nkwargs: \".format(', '.join(list_of_args), ', '.join(list_of_kwargs))\n\n\t\t\tlogger.log(logging.DEBUG, debug_string)\n\n\t\t\tresult = func(*args, **kwargs)\n\t\t\t\n\t\t\treturn result\n\t\t\t\n\t\tif DEBUG:\n\t\t\treturn debug_wrapper\n\t\telse:\n\t\t\treturn func\n\treturn debug_decorator", "def log_info(func):\n\n @wraps(func)\n def wrapped(*a, **kw):\n\n # Log environment information\n logging.info('User: ' + getpass.getuser())\n logging.info('System: ' + socket.gethostname())\n logging.info('Python Version: ' + sys.version.replace('\\n', ''))\n logging.info('Python Executable Path: ' + sys.executable)\n\n # Call the function and time it\n t1_cpu = time.clock()\n t1_time = time.time()\n func(*a, **kw)\n t2_cpu = time.clock()\n t2_time = time.time()\n\n # Log execution time\n hours_cpu, remainder_cpu = divmod(t2_cpu - t1_cpu, 60 * 60)\n minutes_cpu, seconds_cpu = divmod(remainder_cpu, 60)\n hours_time, remainder_time = divmod(t2_time - t1_time, 60 * 60)\n minutes_time, seconds_time = divmod(remainder_time, 60)\n logging.info('Elapsed Real Time: {0:.0f}:{1:.0f}:{2:f}'.format(hours_time, minutes_time, seconds_time))\n logging.info('Elapsed CPU Time: {0:.0f}:{1:.0f}:{2:f}'.format(hours_cpu, minutes_cpu, seconds_cpu))\n\n return wrapped", "def add_logging(before: str = None, after: str = None):\n def decorator(func):\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n if before is not None:\n LOGGER.info(before)\n result = func(*args, **kwargs)\n if after is not None:\n LOGGER.info(after)\n return result\n return wrapper\n return decorator" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handles all exceptions thrown by the wrapped/decorated function.
def handle_all_exceptions(): def decorator(func): def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except Exception as ex: # noqa: pylint - catching-non-exception LOGGER.error(str(ex)) return failure(str(ex)) return wrapper return decorator
[ "def exception_handler(function: Any) -> Any:\n\n @functools.wraps(function)\n def wrapper(*args: Any, **kwargs: Any) -> Any:\n try:\n return function(*args, **kwargs)\n\n except pexpect.EOF as exception:\n error_message = exception.value.split(\"\\n\")[5]\n\n if \"Host key verification failed\" in error_message:\n raise netcat.CustomException(\"Device identity verification failed\")\n\n if \"Authorization failed\" in error_message:\n raise netcat.CustomException(\"Authorization failed\")\n\n if \"Connection timed out\" in error_message:\n raise netcat.CustomException(\"Connection timeout\")\n\n raise netcat.CustomException(f\"Expect error '{error_message}'\")\n\n except pexpect.TIMEOUT:\n raise netcat.CustomException(\"Connection timeout\")\n\n return wrapper", "def exception_handler(func: Callable) -> Callable:\r\n\r\n @wraps(func)\r\n def wrapper(*args):\r\n try:\r\n result = func(*args)\r\n except BaseException as e:\r\n raise NoMaterialDataException from e\r\n return result\r\n\r\n return wrapper", "def normalize_exceptions(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n message = \"Whoa, you found a bug.\"\n try:\n return func(*args, **kwargs)\n except requests.HTTPError as err:\n raise CommError(err.response, err)\n except RetryError as err:\n if \"response\" in dir(err.last_exception) and err.last_exception.response is not None:\n try:\n message = err.last_exception.response.json().get(\n 'errors', [{'message': message}])[0]['message']\n except ValueError:\n message = err.last_exception.response.text\n else:\n message = err.last_exception\n\n if env.is_debug():\n six.reraise(type(err.last_exception), err.last_exception, sys.exc_info()[2])\n else:\n six.reraise(CommError, CommError(\n message, err.last_exception), sys.exc_info()[2])\n except Exception as err:\n # gql raises server errors with dict's as strings...\n if len(err.args) > 0:\n payload = err.args[0]\n else:\n payload = err\n if str(payload).startswith(\"{\"):\n message = ast.literal_eval(str(payload))[\"message\"]\n else:\n message = str(err)\n if env.is_debug():\n six.reraise(*sys.exc_info())\n else:\n six.reraise(CommError, CommError(\n message, err), sys.exc_info()[2])\n\n return wrapper", "def exception_wrapper(method):\n def _wrapper(*args, **kwargs):\n try:\n return method(*args, **kwargs)\n except IOError as e:\n if not isinstance(e, OSError):\n raise OSError(e.errno, e.strerror)\n else:\n raise e\n\n return _wrapper", "def errorHandler(func):\n @wraps(func)\n async def _errorHandling(*args, **params):\n \"\"\"\n Error handling function for decorator\n \"\"\"\n if not args[0].errorHandling:\n return await func(*args, **params)\n else:\n try:\n return await func(*args, **params)\n #Errors that should be retried\n except exc.RateLimit as e:\n if args[0].debug:\n print(e)\n print(\"Retrying\")\n i = e.waitFor()\n while i < 6:\n await asyncio.sleep(i)\n try:\n return await func(*args, **params)\n except Exception as e2:\n if args[0].debug:\n print(e2)\n i += 2\n raise e\n except (exc.ServerError, exc.Timeout) as e:\n if args[0].debug:\n print(e)\n print(\"Retrying\")\n i = 1\n while i < 6:\n await asyncio.sleep(i)\n try:\n return await func(*args, **params)\n except (exc.Timeout, exc.ServerError) as e2:\n\n pass\n i += 2\n if args[0].debug:\n print(e2)\n print(\"Retrying\")\n print(\"there is no bug\")\n raise e\n except (exc.NotFound, exc.BadRequest) as e:\n raise e\n except (exc.Forbidden, exc.Unauthorized,) as e:\n print(e)\n raise SystemExit(0)\n except Exception as e:\n raise e\n\n return _errorHandling", "def decorate_exception_hook(func: Callable) -> Callable:\n @functools.wraps(func)\n def wrapped(*args, **kwargs):\n with exception_hook():\n return func(*args, **kwargs)\n return wrapped", "def allow_exception(exceptions):\n _exceptions = tuple(exceptions)\n\n def decorate(func):\n def wrap(*args, **kwargs):\n try:\n return func(*args, **kwargs)\n except _exceptions:\n warnings.warn('Exception occurred in function %s. Args: %s\\n'\n 'Traceback:\\n%s' % (func.__name__, args,\n traceback.format_exc()))\n return wrap\n\n return decorate", "def pretty_exception_handler(original_function):\n def wrapped_function(*args, **kwargs):\n try:\n original_function(*args, **kwargs)\n except VimPrettyException as e:\n print(six.text_type(e), file=sys.stderr)\n\n return wrapped_function", "def wrap_keystone_exception(func):\n @functools.wraps(func)\n def wrapped(*args, **kwargs):\n try:\n return func(*args, **kwargs)\n except keystone_exceptions.AuthorizationFailure:\n raise AuthorizationFailure(\n client=func.__name__, message=\"reason: %s\" % sys.exc_info()[1])\n except keystone_exceptions.ClientException:\n raise AuthorizationFailure(\n client=func.__name__,\n message=\"unexpected keystone client error occurred: %s\"\n % sys.exc_info()[1])\n return wrapped", "def handle_exception(func=None, store_exception=True):\n def _handle_exception(f):\n @functools.wraps(f)\n def wrapper(*args, **kwargs):\n try:\n output = f(*args, **kwargs)\n except Exception as ex:\n log.error(f'An error occured in {f.__qualname__}')\n output = None\n # store exception in object if no name collision with \"exception\"\n if store_exception:\n try:\n args[0].exception = ex\n except:\n log.warning(f'Could not store exception as an attribute'\n f' of {args[0]}')\n # attribute cannot be set\n pass\n traceback.print_exc()\n return output\n return wrapper\n if func is None:\n # handle_exception was called with arguments; return a function that\n # decorates\n return _handle_exception\n else:\n # handle_exception was called without arguments;\n # return a decorated function\n return _handle_exception(func)", "def use_custom_exception_handler(): # pragma: no cover\n sys.excepthook = _my_exception_handler", "def io_error_handle(func):\n\n @wraps(func)\n def wrapper(*args, **kwargs):\n \"\"\"A wrapper function.\"\"\"\n try:\n return func(*args, **kwargs)\n except (OSError, IOError) as err:\n print('{0}.{1} I/O error: {2}'.format(\n func.__module__, func.__name__, err))\n raise\n return wrapper", "def handle_exception(self, e):\n\n # Determine which method to call based on exception type\n mappings = (\n (ServerRequestError, self.handle_server_error),\n # (BadRequestException, self.handle_bad_request),\n # (NotFoundException, self.handle_not_found),\n # (ConflictException, self.handle_conflict),\n # (ConnectionException, self.handle_connection_error),\n # (PermissionsException, self.handle_permission),\n # (InvalidConfig, self.handle_invalid_config),\n # (WrongHost, self.handle_wrong_host),\n # (gaierror, self.handle_unknown_host),\n # (socket_error, self.handle_socket_error),\n # (ApacheServerException, self.handle_apache_error),\n )\n\n handle_func = self.handle_unexpected\n for exception_type, func in mappings:\n if isinstance(e, exception_type):\n handle_func = func\n break\n\n exit_code = handle_func(e)\n return exit_code", "def decorator(fun):\n def decorated(*__args, **__kwargs):\n \"\"\"Call a function within an interrupt handler\"\"\"\n try:\n return fun(*__args, **__kwargs)\n except tuple(exceptions): # pylint: disable=catching-non-exception\n return handler(*args, **kwargs)\n return decorated", "def handle_api_exception(func):\n\n def inner(*args, **kwargs):\n \"\"\"\n handler api exception\n \"\"\"\n request = args[0]\n content_type = \"application/json\"\n try:\n body, status = func(*args, **kwargs)\n except CustomException as error:\n exp = HTTPException.from_custom_exception(error)\n body = _serialize(exp.as_dict())\n status = exp.status\n except HTTPException as error:\n body = _serialize(error.as_dict())\n status = error.status\n except Exception as error:\n error_traceback = traceback.format_exc()\n Logger.error(error_traceback)\n body = \"Something went wrong\"\n status = 500\n return HttpResponse(\n json.dumps(body), status=status, content_type=content_type\n )\n\n return inner", "def HandleKnownHttpError(func):\n\n @functools.wraps(func)\n def Wrapped(*args, **kwargs):\n try:\n return func(*args, **kwargs)\n except api_exceptions.HttpError as error:\n maybe_known_error = GetError(error)\n if not maybe_known_error:\n raise\n # GetError returns either a tuple or None, the above check ensures it\n # must be a tuple by this point.\n # pylint: disable=unpacking-non-sequence\n error_class, error_args = maybe_known_error\n raise error_class, error_args, sys.exc_info()[2]\n\n return Wrapped", "def trap_error(func, on_error = None):\r\n try:\r\n return func()\r\n except:\r\n if callable(on_error):\r\n return on_error(sys.exc_info())\r\n else:\r\n return on_error", "def handlesException(self):\n self.runner = PythonRunner(EXCEPTION_METHOD)\n results = None\n try:\n results = self.runner.processFunction()\n except IndentationError as error:\n self.fail('An Indentation Error should not have occured')\n \n self.assertEquals(['My Exception'], results[4])", "def wandb_alert_on_exception(func):\n\n def wrapper(*args, **kwargs):\n try:\n return func(*args, **kwargs)\n except Exception as e:\n wandb.alert(title=\"Run crashed\", text=traceback.format_exc())\n raise e\n\n return wrapper" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds HSTS header to the response of the decorated function
def hsts(max_age: int = None): def decorator(func): def wrapper(*args, **kwargs): response = func(*args, **kwargs) if isinstance(response, dict): headers_key = find_key_case_insensitive("headers", response) resp_headers = response[headers_key] if headers_key in response else {} header_key = find_key_case_insensitive("Strict-Transport-Security", resp_headers) header_value = f"max-age={max_age}" if max_age else "max-age=63072000" resp_headers[header_key] = header_value response[headers_key] = resp_headers return response else: LOGGER.error(NON_DICT_LOG_MESSAGE) return failure(HSTS_NON_DICT_ERROR, HTTPStatus.INTERNAL_SERVER_ERROR) return wrapper return decorator
[ "def _patch_header(response: HttpResponse, status: Status) -> None:\n # Patch cache-control with no-cache if it is not already set.\n if status == Status.SKIP and not response.get(\"Cache-Control\", None):\n response[\"Cache-Control\"] = CacheControl.NOCACHE.value\n # Add our custom header.\n if wagtailcache_settings.WAGTAIL_CACHE_HEADER:\n response[wagtailcache_settings.WAGTAIL_CACHE_HEADER] = status.value", "def cors_header(func):\n @wraps(func)\n def wrapper(self, request, *args, **kwargs):\n res = func(self, request, *args, **kwargs)\n request.setHeader('Access-Control-Allow-Origin', '*')\n return res\n return wrapper", "def add_header(r):\n\n r.headers[\"Cache-Control\"] = \"no-cache, no-store, must-revalidate\"\n # To fix the issue of making a new team on the dashboard, and using the\n #browser's nav button to go back\n return r", "def header(request, response, name, value, append=False):\n if not append:\n response.headers.set(name, value)\n else:\n response.headers.append(name, value)\n return response", "def fudge_headers(response, stats):\n if not stats:\n add_never_cache_headers(response)\n else:\n patch_cache_control(response, max_age=seven_days)", "def json_response(func):\n def decorator(*args, **kwargs):\n instance = args[0]\n request = getattr(instance, 'request', None)\n request.response.setHeader(\n 'Content-Type',\n 'application/json; charset=utf-8'\n )\n result = func(*args, **kwargs)\n if isinstance(result, list):\n request.response.setStatus(200)\n return json.dumps(result, indent=2, sort_keys=True)\n else:\n request.response.setStatus(result.get('status_code', 200))\n return json.dumps(result.get('data', result), indent=2, sort_keys=True)\n\n return decorator", "def add_auth(f):\n\n def add_auth_decorator(*args, **kwargs):\n token = get_user_token()\n if 'headers' not in kwargs:\n kwargs['headers'] = {}\n kwargs['headers']['Authorization'] = \"Bearer %s\" % token\n return f(*args, **kwargs)\n\n return add_auth_decorator", "def set_status_and_headers_in_response(response, status, headers):\n ...", "def _require_header(func, header):\n\n @wraps(func)\n def decorated(self, *args, **kwargs):\n if self.request.headers.get(header) or is_dev():\n return func(self, *args, **kwargs)\n else:\n raise HTTPForbidden()\n\n return decorated", "def private_response(response, force=True):\n if force or CDN_CACHE_CONTROL_HEADER not in response.headers:\n response.headers[CDN_CACHE_CONTROL_HEADER] = \"private\"", "def extra_outgoing_headers_from_callable(callable_obj, *args, **kwargs):\n with patch.object(urllib2, 'urlopen') as urlopen_mock:\n urlopen_mock.return_value = StringIO.StringIO(VALID_JSON)\n with patch.object(urllib2.Request, 'add_header') as add_header_mock:\n callable_obj(*args, **kwargs)\n headers = [\n header for (header, _) in add_header_mock.call_args_list]\n return headers", "def token_handler(self, f):\r\n @wraps(f)\r\n def decorated(*args, **kwargs):\r\n server = self.server\r\n uri, http_method, body, headers = extract_params()\r\n credentials = f(*args, **kwargs) or {}\r\n log.debug('Fetched extra credentials, %r.', credentials)\r\n ret = server.create_token_response(\r\n uri, http_method, body, headers, credentials\r\n )\r\n return create_response(*ret)\r\n return decorated", "def request_token_handler(self, f):\r\n @wraps(f)\r\n def decorated(*args, **kwargs):\r\n server = self.server\r\n uri, http_method, body, headers = extract_params()\r\n credentials = f(*args, **kwargs)\r\n try:\r\n ret = server.create_request_token_response(\r\n uri, http_method, body, headers, credentials)\r\n return create_response(*ret)\r\n except errors.OAuth1Error as e:\r\n return _error_response(e)\r\n return decorated", "def access_token_handler(self, f):\r\n @wraps(f)\r\n def decorated(*args, **kwargs):\r\n server = self.server\r\n uri, http_method, body, headers = extract_params()\r\n credentials = f(*args, **kwargs)\r\n try:\r\n ret = server.create_access_token_response(\r\n uri, http_method, body, headers, credentials)\r\n return create_response(*ret)\r\n except errors.OAuth1Error as e:\r\n return _error_response(e)\r\n return decorated", "def add_unredirected_header(self, key, val):\n self.unredirected_hdrs[key.capitalize()] = val", "def secure_headers():\n headers = cherrypy.response.headers\n headers['Cache-Control'] = 'no-cache, no-store, private, mustrevalidate'\n headers['Pragma'] = 'no-cache'\n headers['X-XSS-Protection'] = '1; mode=block'\n headers['Content-Security-Policy'] = \"default-src='self'\"", "def json_response(func):\n\n @functools.wraps(func)\n def json_wrapper(request, *args, **kwds):\n data = func(request, *args, **kwds)\n if isinstance(data, HttpResponse):\n return data\n\n status = 200\n if isinstance(data, collections.MutableMapping):\n status = data.pop(STATUS_CODE, status)\n\n if request.REQUEST.get('pretty','0').lower() in ('1', 'true', 'on'):\n data = json.dumps(data, indent=2, sort_keys=True)\n else:\n data = json.dumps(data, separators=(',',':'))\n return HttpResponse(data, content_type='application/json; charset=utf-8',\n status=status)\n\n return json_wrapper", "def _default_headers_hook():\n bottle.response.headers['Cache-Control'] = 'no-store'\n bottle.response.headers['Server'] = 'Hibiki/2016'\n bottle.response.headers['X-Username'] = get_current_username() or ''", "def testCachingHeaders(self):\n self.handler.get(\"status\")\n self.assertEquals(\"public; max-age=300\",\n self.handler.response.headers[\"Cache-Control\"])" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plot a heatmap for the given matrix A.
def plot_matrix(A, ax=None, vmin=-3, vmax=3, formt="%0.2f", thresh=1e-16, block=False): if ax is None: plt.figure() ax = plt.gca() ax.imshow(A, vmin=vmin, vmax=vmax, cmap='bwr') for i in range(len(A)): for j in range(len(A)): if A[i, j] != 0: ax.text(j, i, formt % A[i, j], ha='center', va='center') plt.show(block=block)
[ "def heatmap(self):\n plt.imshow(self.M)\n plt.yticks([])\n plt.xticks(np.arange(self.size[1]))\n plt.show()", "def show_heatmap(self):\n plt.show()", "def plot_heat_map(\n data_matrix, x_free_variable, y_free_variable, matrix_range=(None, None),\n cmap=None, cbar_name=None, save_path=None):\n\n fig, ax = plt.subplots()\n im = ax.imshow(data_matrix, cmap=cmap, vmin=matrix_range[0], vmax=matrix_range[1])\n ax.set_xlim([0, x_free_variable.total_num])\n ax.set_ylim([0, y_free_variable.total_num])\n ax.set_xticks(x_free_variable.tick_in_range)\n ax.set_yticks(y_free_variable.tick_in_range)\n ax.set_xticklabels(x_free_variable.tick_labels)\n ax.set_yticklabels(y_free_variable.tick_labels)\n if cbar_name:\n cbar = ax.figure.colorbar(im, ax=ax)\n cbar.ax.set_ylabel(cbar_name, rotation=-90, va=\"bottom\")\n if save_path:\n # print(save_path)\n fig.savefig(save_path, dpi=fig.dpi)", "def visualize_matrice_mi(self):\n ax_heatmap = plt.axes()\n sns.heatmap(self.matrice_mi, ax=ax_heatmap)\n ax_heatmap.set_title(\\\n \"Heatmap of the compute mutual information for the different positions\")\n plt.show()", "def plot_matrix():\n CHARACTERS = 'abcdefghijklmnopqrstuwxyz '\n MATRIX_PATH = Path('learned_matrices')\n matrices = list(map(np.loadtxt, glob.glob(str(MATRIX_PATH / '*.np'))))\n languages = [os.path.basename(path)[:-3] for path in glob.glob(str(MATRIX_PATH / '*.np'))]\n for matrix, lang in zip(matrices, languages):\n ax = sns.heatmap(matrix, center=0, xticklabels=CHARACTERS, yticklabels=CHARACTERS)\n ax.set_xticklabels(ax.get_xticklabels(), rotation=30)\n ax.set_yticklabels(ax.get_yticklabels(), rotation=100)\n plt.title(f\"{lang.upper()} MATRIX\")\n plt.xlabel(\"Second character\")\n plt.ylabel(\"First characters\")\n plt.savefig(f\"images/{lang}-matrix.png\")\n plt.show()", "def heatmap(tfidf_matrix, title, xlabel, ylabel, xticklabels, yticklabels):\r\n\r\n # Plot it out\r\n fig, ax = plt.subplots()\r\n c = ax.pcolor(tfidf_matrix, edgecolors='k', linestyle='dashed', cmap=plt.cm.Blues, linewidths=0.2, vmin=0.0,\r\n vmax=1.0)\r\n\r\n # put the major ticks at the middle of each cell\r\n ax.set_yticks(np.arange(tfidf_matrix.shape[0]) + 0.5, minor=False)\r\n ax.set_xticks(np.arange(tfidf_matrix.shape[1]) + 0.5, minor=False)\r\n\r\n # set tick labels\r\n # ax.set_xticklabels(np.arange(1,tfidf_matrix.shape[1]+1), minor=False)\r\n ax.set_xticklabels(xticklabels, minor=False, rotation='vertical')\r\n ax.set_yticklabels(yticklabels, minor=False)\r\n\r\n # set title and x/y labels\r\n plt.title(title)\r\n plt.xlabel(xlabel)\r\n plt.ylabel(ylabel)\r\n\r\n # Remove last blank column\r\n # plt.xlim( (0, tfidf_matrix.shape[1]) )\r\n for i in range(tfidf_matrix.shape[0]):\r\n for j in range(tfidf_matrix.shape[1]):\r\n c = round(tfidf_matrix[i, j], 2)\r\n ax.text(j, i, str(c))\r\n\r\n plt.show()", "def test_plot_heatmap(self):\n import matplotlib.pyplot as plt\n conn = self._get_conn(astype='pandas')\n plot_conn_heatmap(conn, cbar=True, cbar_title='Never use jet')\n plot_conn_heatmap(conn, cbar=False, cmap='jet') # :(\n plot_conn_heatmap(conn, categories=[0, 0, 1])\n plot_conn_heatmap(conn, xticklabels=True)\n plot_conn_heatmap(conn, xticklabels=10)\n plot_conn_heatmap(conn, xticklabels=False)\n plot_conn_heatmap(conn, yticklabels=True)\n plot_conn_heatmap(conn, yticklabels=10)\n plot_conn_heatmap(conn, yticklabels=False)\n plt.close()", "def visualize_adjacency(title, A):\r\n assert type(title) == str, \"Title not a string!\"\r\n assert len(A.shape) == 2, \"Image array not 2D!\"\r\n \r\n plt.figure(figsize=(7, 7))\r\n\r\n # Visualize adjacency matrix\r\n # We manually set the black value with `vmin`, and the white value with `vmax`\r\n plt.imshow(A, vmin=0.0, vmax=1.0, cmap=\"gray\")\r\n\r\n # Give our plot a title -- this is purely cosmetic!\r\n plt.title(f\"{title}, shape={A.shape}\")\r\n\r\n # Show image\r\n plt.show()", "def draw_heatmap(X_labels, data_dict):\r\n if version.parse(mpl_version) < version.parse(MATPLOTLIB_VERSION):\r\n print(\"\\n *** Error: To create the heatmap, matplotlib version\", MATPLOTLIB_VERSION, \"is needed.\")\r\n print(\"Current matplotlib version:\", version.parse(mpl_version),\"\\n\")\r\n return\r\n data_names = data_dict.keys()\r\n if len(data_names) == 0:\r\n print(\">>>No information to display\")\r\n return\r\n\r\n fig, ax = plt.subplots()\r\n display_amount = min(len(data_names), PAGE_DISPLAY_AMOUNT)\r\n try:\r\n all_vals = [item for sublist in data_dict.values() for item in sublist]\r\n except:\r\n print(\"Expected format of data_dict parameter is a dictionary of string keys and tuple values\")\r\n return\r\n\r\n \r\n img = ax.imshow([[min(all_vals)], [max(all_vals)]], aspect='auto', cmap=HEATMAP_COLORS, interpolation='bilinear', origin='upper', extent=[0, 2*len(X_labels), 2*display_amount, 0]) # First param is dummy data before it is updated\r\n\r\n aux.create_x_labels(ax, X_labels)\r\n aux.update_scroll(0, img, ax, list(data_dict.values()), list(data_names), display_amount)\r\n \r\n fig.colorbar(img)\r\n img.set_clim(vmin=0)\r\n \r\n aux.value_on_hover(ax, img)\r\n\r\n radio = aux.create_radio_buttons(ax)\r\n def radio_func(label):\r\n current_interpolation = aux.INTERPOLATION_DICT[label]\r\n img.set_interpolation(current_interpolation)\r\n plt.draw()\r\n\r\n radio.on_clicked(radio_func)\r\n \r\n if len(data_names) > PAGE_DISPLAY_AMOUNT:\r\n aux.create_scrollbar(fig, img, ax, data_names, list(data_dict.values()))\r\n \r\n plt.show()", "def plot_matrix(matrix, xaxis=None, yaxis=None, xunits='time (s)', yunits='Hz',\n zunits='(dB rel.)'):\n\n if xaxis is None:\n xaxis = [c for c in range(matrix.shape[1])]\n if yaxis is None:\n yaxis = [r for r in range(matrix.shape[0])]\n\n # Plot the matrix as a mesh, label axes and add a scale bar for\n # matrix values\n plt.pcolormesh(xaxis, yaxis, matrix)\n plt.xlabel(xunits)\n plt.ylabel(yunits)\n plt.colorbar(label=zunits)\n plt.show()", "def plot_confusion_matrix(confusion_matrix):\n ax = sns.heatmap(confusion_matrix, annot=True)\n ax.set(xlabel=\"predicted\", ylabel=\"true\")", "def plot1D_mat(a,b,M,title=''):\n \n na=M.shape[0]\n nb=M.shape[1]\n \n gs = gridspec.GridSpec(3, 3)\n \n \n xa=np.arange(na)\n xb=np.arange(nb)\n \n \n ax1=pl.subplot(gs[0,1:])\n pl.plot(xb,b,'r',label='Target distribution')\n pl.yticks(())\n pl.title(title)\n \n #pl.axis('off')\n \n ax2=pl.subplot(gs[1:,0])\n pl.plot(a,xa,'b',label='Source distribution')\n pl.gca().invert_xaxis()\n pl.gca().invert_yaxis()\n pl.xticks(())\n #pl.ylim((0,n))\n #pl.axis('off')\n \n pl.subplot(gs[1:,1:],sharex=ax1,sharey=ax2)\n pl.imshow(M,interpolation='nearest')\n \n pl.xlim((0,nb))", "def plot_heatmap(acc_list, algorithm, param1_space, param2_space):\n fig, ax = plt.subplots(figsize=(10,8))\n ax = sns.heatmap(acc_list, cmap=\"YlGnBu_r\", ax=ax, cbar_kws={'label': 'F1-score'})\n if algorithm == \"lle\":\n ax.set_xlabel(\"Regularization term (R)\")\n ax.set_ylabel(\"Number of Neighbors (K)\")\n elif algorithm == \"tsne\":\n ax.set_xlabel(\"Tolerance (tol)\")\n ax.set_ylabel(\"Perplexity (Perp)\")\n ax.set_xticklabels(HL.round_array(param2_space), rotation=90)\n ax.set_yticklabels(param1_space, rotation=0)\n plt.tight_layout()\n plt.savefig(\"images/MNIST_heatmap_\" + algorithm)\n plt.show()", "def show_heatmap_pixel(M,col,row,win,ax=None,vmin=None,vmax=None,ax_visible=False):\n assert 0<col<M.shape[0]\n assert 0<row<M.shape[0]\n \n hr = slice(col-win,col+win+1)\n vr = slice(row-win,row+win+1)\n\n # if no axes has been provided:\n if ax is None:\n plt.clf()\n f = plt.gcf()\n ax = plt.gca()\n\n hic_cmap = 'YlOrRd'\n im = ax.imshow(M[hr,vr],\n interpolation='nearest',\n cmap=hic_cmap,\n vmin=vmin,\n vmax=vmax)\n\n ax.xaxis.set_visible(ax_visible)\n ax.yaxis.set_visible(ax_visible)\n\n \n return ax", "def show_attention_matrix(alpha, layer):\n sensors = conf.get_config('data-parameters', 'valid-sensors')\n channel_num = len(sensors)\n plt.figure(figsize=(10, 10))\n\n sns.set()\n heat_map = sns.heatmap(alpha, cmap='YlGnBu', linewidths=0.5)\n plt.title(f'layer-{layer}')\n plt.xlabel('sensor')\n plt.ylabel('sensor')\n plt.xticks(range(1, channel_num + 1), sensors, rotation=90)\n plt.yticks(range(channel_num), sensors, rotation=360)\n plt.show()", "def heatmap_diagonals(matrix,matrix_notnan_add,x_grid,y_grid,line1_x,line1_y,line2_x,line2_y,title,xlabel,ylabel,colorbarlabel,round_int = 1,round_int2 = 0,max_float = 100,norm = None,vmin=None, vmax=None,equal_dur = False,saveplot = False,save_path = None):\n params = {'figure.figsize': (20,20),\n 'lines.linewidth': 4,\n 'legend.fontsize': 20,\n 'axes.labelsize': 40,\n 'axes.titlesize':45,\n 'xtick.labelsize':35,\n 'ytick.labelsize':35,\n 'xtick.major.size': 10,\n 'xtick.major.width' : 2,\n 'xtick.minor.size' :5,\n 'xtick.minor.width' : 1,\n 'ytick.major.size': 10,\n 'ytick.major.width' : 2,\n 'ytick.minor.size' :5,\n 'ytick.minor.width' : 1,\n 'figure.constrained_layout.use': True}\n plt.rcParams.update(params)\n fig = plt.figure()\n ax = fig.add_subplot(111)\n textcolors=(\"black\", \"white\")\n bounds = range(int(min(matrix_notnan_add)),int(max(matrix_notnan_add))+1,1)\n cmap_20 = plt.cm.get_cmap(\"tab20\")\n norm = colors.BoundaryNorm(bounds, cmap_20.N)\n\n x, y = np.meshgrid(x_grid,y_grid)\n dist_x = np.round(x_grid[1]-x_grid[0],2)/2 # calculating half of the distance between to gridpoints to get the ticks into the middle\n dist_y = np.round(y_grid[0]-y_grid[1],2)/2\n\n # plotting\n ax.plot(line1_x,line1_y,color = \"black\")#plotting bifurcation lines\n ax.plot(line2_x,line2_y,color = \"black\",linestyle = \"--\")\n if equal_dur:\n ax.plot(x_grid,-0.2*x_grid+2.4,color = \"red\",linewidth = 4)\n # extent set such that the ticks are in the middle of the squares\n heatmap = ax.imshow(matrix,extent=[x.min()-dist_x, x.max()+dist_x, y.min()-dist_y, y.max()+dist_y], origin = \"upper\",cmap = \"tab20\",aspect = 4,norm = norm,vmin = vmin,vmax = vmax)\n cbar = fig.colorbar(heatmap, ax=ax,shrink = 0.75,ticks=np.array(np.arange(-10,12,1))+0.5)#fraction can resize the colorbar\n cbar.set_label(colorbarlabel,fontsize = 40)\n cbar.set_ticklabels(np.array(np.arange(-5,10,1)))\n ax.set_xticks(x_grid)\n ax.set_yticks(y_grid)\n ax.set_xticklabels(np.round(x_grid,2), rotation=90) # rotate the xticks such that still readable for more comma vals\n ax.set_yticklabels(np.round(y_grid,2))\n ax.set_xlabel(xlabel)\n ax.set_ylabel(ylabel)\n ax.set_title(title)\n\n # Loop over data dimensions and create text annotations.\n for (idxi,i) in enumerate(y_grid):\n for (idxj,j) in enumerate(x_grid):\n if not np.isnan(matrix[idxi, idxj]):# do not want to display the nan values\n text = ax.text(j, i, int(np.round(matrix[idxi, idxj],round_int2)),\n ha=\"center\", va=\"center\", color=textcolors[int(heatmap.norm(matrix[idxi, idxj]) < 0.5)],size = 18)\n\n # possibility to save the plot\n if saveplot:\n plt.savefig(save_path,dpi=200)\n plt.show()", "def plotHeatMap(values,xlabels,ylabels,colormap=None, minvalue=None,maxvalue=None,calpha=0.8,ax=None,annotate=False):\n\n #Verify the inputs.\n if not len(xlabels) == len(values):\n raise Exception('x-labels do not have same length as values length.')\n for i in range(len(xlabels)):\n if not len(ylabels) == len(values[i]):\n raise Exception('y-labels do not have the same length as values[%d] length.' % i)\n\n if colormap == None:\n colormap = plt.cm.binary\n\n if ax == None:\n ax=plt.gca()\n\n #Create the array of color values.\n mincolor = None\n maxcolor = None\n colors = np.zeros(shape=(len(xlabels),len(ylabels)))\n for i in range(len(xlabels)):\n colors[i] = [0]*len(ylabels)\n for j in range(len(ylabels)):\n\n value = values[i][j]\n\n colors[i][j] = value\n\n #Plot the heatmap\n plt.pcolor(colors,cmap=colormap, alpha=calpha, vmin=minvalue, vmax=maxvalue)\n\n #Format it\n ax.set_frame_on(False)\n\n ax.invert_yaxis()\n ax.xaxis.tick_top()\n\n plt.xticks(rotation=90)\n\n ax.set_yticks(np.arange(colors.shape[0])+0.5, minor=False)\n ax.set_xticks(np.arange(colors.shape[1])+0.5, minor=False)\n\n ax.set_xticklabels(ylabels, minor=False)\n ax.set_yticklabels(xlabels, minor=False)\n plt.xticks(rotation=90)\n\n ax = plt.gca()\n\n for t in ax.xaxis.get_major_ticks():\n t.tick1On = False\n t.tick2On = False\n for t in ax.yaxis.get_major_ticks():\n t.tick1On = False\n t.tick2On = False\n\n if annotate:\n for y in range(colors.shape[0]):\n for x in range(colors.shape[1]):\n plt.text(x + 0.5, y + 0.5, '%.2f' % values[y][x],\n horizontalalignment='center',\n verticalalignment='center',\n )", "def visualise_grid(self, *args, **kwargs):\n\n plt.figure(figsize=(20,15))\n sns.heatmap(self.grid, xticklabels=False, yticklabels=False,\n *args, **kwargs)", "def plot(self, ax, allow_large = False, **kwargs):\n tile = self.as_one_image(allow_large)\n scale = 2 ** self.zoom\n x0, y0 = self.extent.project(self.xtilemin / scale, self.ytilemin / scale)\n x1, y1 = self.extent.project((self.xtilemax + 1) / scale, (self.ytilemax + 1) / scale)\n ax.imshow(tile, interpolation=\"lanczos\", extent=(x0,x1,y1,y0), **kwargs)\n ax.set(xlim = self.extent.xrange, ylim = self.extent.yrange)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a dictionnary of anti dependencies for design unit
def compute_anti_dependences(self): res = {} lib = libraries.Get_Libraries_Chain() while lib != nodes.Null_Iir: files = nodes.Get_Design_File_Chain(lib) while files != nodes.Null_Iir: units = nodes.Get_First_Design_Unit(files) while units != nodes.Null_Iir: if nodes.Get_Date_State(units) == nodes.Date_State.Analyze: # The unit has been analyzed, so the dependencies are know. deps = nodes.Get_Dependence_List(units) assert deps != nodes.Null_Iir_List deps_it = lists.Iterate(deps) while lists.Is_Valid(byref(deps_it)): el = lists.Get_Element(byref(deps_it)) if nodes.Get_Kind(el) == nodes.Iir_Kind.Design_Unit: if res.get(el, None): res[el].append(units) else: res[el] = [units] else: assert False lists.Next(byref(deps_it)) units = nodes.Get_Chain(units) files = nodes.Get_Chain(files) lib = nodes.Get_Chain(lib) return res
[ "def test_cfg_exclude_component_dict(self):\n # create the top level externals file\n desc = self.setup_dict_config()\n # Test an excluded repo\n external = create_externals_description(desc, model_format='dict',\n exclude=['simp_tag',\n 'simp_opt'])\n self.assertIsInstance(external, ExternalsDescriptionDict)\n self.assertFalse('simp_tag' in external)\n self.assertTrue('simp_branch' in external)\n self.assertFalse('simp_opt' in external)\n self.assertTrue('mixed_req' in external)", "def missing_dependencies(self):\n missing_dependencies = []\n if self.schedule is None:\n missing_dependencies.append('schedule')\n if self.email_server is None:\n missing_dependencies.append('email_server')\n if self.email_template is None:\n missing_dependencies.append('email_template')\n if self.target_lists.exists() is False:\n missing_dependencies.append('target_lists')\n if self.is_oauth is True and \\\n self.oauthengagement.oauth_consumer is None:\n missing_dependencies.append('oauth_consumer')\n if self.is_oauth is False and self.domain is None:\n missing_dependencies.append('domain')\n if self.is_oauth is False and self.landing_page is None:\n missing_dependencies.append('landing_page')\n if self.is_oauth is False and self.redirect_page is None:\n missing_dependencies.append('redirect_page')\n return missing_dependencies", "def _dependencies(self):\n dep = {}\n for node in self._nodes.values():\n d = dep.setdefault(node.id, [])\n for inp in node.input_names:\n for node2 in self._nodes.values():\n if inp in node2.output_names:\n d.append(node2.id)\n return dep", "def _getSoftInternals(self, unit):\r\n isValidUnarmoured = lambda x: x.armour < 1 and x.isAlive\r\n validTargets = [(internal, unit) for internal in filter(\r\n isValidUnarmoured, unit._internalCriticals)]\r\n\r\n for subUnit in filter(isValidUnarmoured, unit._internalSubUnits):\r\n validTargets += [\r\n (internal, subUnit) for internal in\r\n filter(isValidUnarmoured, subUnit._internalCriticals)]\r\n return validTargets", "def get_blend_dependecies(self, **kwargs):\n self.logger.debug(\"get_blend_dependecies function was called.\")\n\n blend = kwargs[\"blend\"]\n release = kwargs[\"release\"]\n nodepends = kwargs[\"nodepends\"]\n taskdescription = kwargs['taskdescription']\n\n #initialize the tasks' info before getting the dependencies for the tasks\n blend_dependencies = self.__get_tasks_info(blend = blend, release = release, tasksprefix = kwargs[\"tasksprefix\"])\n \n architectures = self.get_available_architectures()\n\n blend_alternatives_virtuals = DictList()\n single_alternatives_list = []\n virtual_packages = []\n available = []\n missing = []\n excluded = []\n\n wanted_dependencies = []\n if nodepends or taskdescription:\n wanted_dependencies += ['d', 'r']\n else:\n wanted_dependencies.append('d')\n\n query = self.__build_all_architectures_query(blend, release, architectures + [\"all\"] )\n \n #indexes of row: task(0), package(1), dependency(2), distribution(3), component(4), p.contains_provides(5)\n #the rest are architectures\n for row in self.__execute_query(query):\n #task, package, dependency, distribution, component, provides = (row[0], row[1], row[2], row[3], row[4], row[5], row[6])\n task, package, dependency, distribution, component, contains_provides = row[:6]\n exist_in_archs = [ x for x in row[6:] if x ]\n\n if not dependency == 'i' and not dependency == 'a':\n blend_dependencies[task][\"haspackages\"] += 1\n\n #check for alternatives('|') and virtuals(provides)\n #if a Depends-virtual does not exist into an alternative relation, let it be\n #it will go into Suggests cause it will not have any element into exist_in_archs\n if '|' in package:\n #no need to handle alternatives or virtual which are not Debian,main\n #because they will go into Suggests if they are Depends/Recommends\n ###TODO check this out again\n #if dependency in wanted_dependencies and distribution == 'debian' and component == 'main':\n if dependency in wanted_dependencies:\n #TODO check again, do not include at all virtual packages when it comes to the tasksel template file\n if contains_provides and not taskdescription:\n virtual_packages += [ myalt.strip() for myalt in package.split(\"|\") ]\n \n blend_alternatives_virtuals[task].append(package)\n single_alternatives_list += [ myalt.strip() for myalt in package.split(\"|\")]\n\n continue\n\n #TODO check again if: if else is with proper syntax\n if nodepends or taskdescription:\n #in this case all the Depends go to Recommends and the recommend packages\n #follow the same rules as the depends packages\n #dependency 'd'== depends and 'r' == recommends\n if dependency == 'd' or dependency == 'r':\n if distribution == 'debian' and component == 'main':\n #here also note that stand-alone virtual packages will provide an empty exist_in_archs\n #so they correctly be added to Suggests (handles properly the virtual-package-depends-without-real-package-depends problem)\n if exist_in_archs:\n archs_resolved = self.__resolve_architectures(exist_in_archs, architectures)\n blend_dependencies[task][\"Recommends\"].append(package + archs_resolved)\n elif not exist_in_archs and contains_provides:\n blend_dependencies[task][\"Suggests\"].append(package)\n else:\n #a debian/main package which does not exist for any arch then \n #it's a candidate for updated name/version inside name\n missing.append({ \"pkg\" : package, \"task\" : task})\n else:\n blend_dependencies[task][\"Suggests\"].append(package)\n else:\n if dependency == 'd':\n if distribution == 'debian' and component == 'main':\n if exist_in_archs:\n archs_resolved = self.__resolve_architectures(exist_in_archs, architectures)\n blend_dependencies[task][\"Depends\"].append(package + archs_resolved)\n elif not exist_in_archs and contains_provides:\n blend_dependencies[task][\"Suggests\"].append(package)\n else:\n #a debian/main package which does not exist for any arch then \n #it's a candidate for updated name/version inside name\n missing.append({ \"pkg\" : package, \"task\" : task})\n else:\n blend_dependencies[task][\"Suggests\"].append(package)\n elif dependency == 'r':\n blend_dependencies[task][\"Recommends\"].append(package)\n\n if dependency == 's':\n blend_dependencies[task][\"Suggests\"].append(package)\n if dependency == 'i':\n if '|' in package:\n blend_dependencies[task][\"Ignore\"] += [ x.strip() for x in package.split('|') ]\n else:\n blend_dependencies[task][\"Ignore\"].append(package)\n #missing.append(package)\n if dependency == 'a':\n if '|' in package:\n blend_dependencies[task][\"Ignore\"] += [ x.strip() for x in package.split('|') ]\n else:\n blend_dependencies[task][\"Avoid\"].append(package)\n excluded.append(package)\n\n ## Up to this point we have properly handled all the single stand-alone packages\n ## now its time to also handle the alternatives(+ virtuals)\n if blend_alternatives_virtuals:\n available_packages = self.__get_available_alternatives(single_alternatives_list, release, architectures + [\"all\"])\n available_provides = {}\n\n if virtual_packages:\n available_provides = self.__get_available_virtuals(virtual_packages, release, architectures + [\"all\"])\n\n for task in blend_alternatives_virtuals:\n alternatives_list = blend_alternatives_virtuals[task]\n for alternative in alternatives_list:\n\n single_alt_exist_temp, single_alt_missing = self.__get_resolved_alternatives(alternative, available_packages, available_provides)\n\n single_alt_exist = []\n\n for tmp in single_alt_exist_temp:\n if tmp in available_packages:\n archs_exist = available_packages[tmp]\n elif tmp in available_provides:\n archs_exist = available_provides[tmp]\n\n single_alt_exist.append(tmp + self.__resolve_architectures(archs_exist, architectures))\n\n if nodepends or taskdescription:\n if single_alt_exist:\n blend_dependencies[task][\"Recommends\"].append(' | '.join(single_alt_exist))\n if single_alt_missing:\n blend_dependencies[task][\"Suggests\"].append(' | '.join(single_alt_missing))\n else:\n if single_alt_exist:\n blend_dependencies[task][\"Depends\"].append(' | '.join(single_alt_exist))\n if single_alt_missing:\n blend_dependencies[task][\"Suggests\"].append(' | '.join(single_alt_missing))\n\n if single_alt_missing:\n for mis in single_alt_missing:\n #these packages are already added into Suggest so provide an added flag here\n #so they won't be added again from the resolve_missing function\n missing.append({ \"pkg\" : mis, \"task\" : task, \"added\" : True})\n \n #all missing should go to suggests, if not then there is a problem\n #TODO I tested it and it's fine but I should check it again\n if missing:\n missing_to_suggests = self.__get_resolved_missing(missing)\n if missing_to_suggests:\n for pkg in missing_to_suggests:\n #check if the package is already added(from the alternatives/virtual handling function, check above)\n if \"added\" in pkg and pkg[\"added\"]:\n continue\n\n blend_dependencies[pkg[\"task\"]][\"Suggests\"].append(pkg[\"pkg\"])\n\n ##TODO, available is empty, check with debian-edu people if they need it\n return ( blend_dependencies, available, list(set( pkg[\"pkg\"] for pkg in missing )), excluded )", "def dependent_upon(self):\r\n return self._portal.get_item_dependencies(self.itemid)", "def test_get_deposits(self):\n pass", "def get_deletable_dist_set(self, name):\n #\n # FIXME: Despite the deletable package, there is not picked up the case.\n # If you remove specify multiple packages, no package only they are\n # dependent has been determined to be deleted .\n #\n dists = list(self.get_installed_distributions())\n uninstall_candidates = self.get_dependencies(name)\n remaining_dist_set = {d.key for d in dists} - {d.key for d in uninstall_candidates}\n cannot_delete_dists = []\n for non_required in remaining_dist_set:\n cannot_delete_dists.extend(self.get_dependencies(non_required))\n deletable_dist_set = {d.key for d in uninstall_candidates} - {d.key for d in cannot_delete_dists}\n deletable_dist_set.add(name)\n return deletable_dist_set.difference(self.white_list)", "def get_excluded_items():", "def _FilterOutUnneededSkylabDeps(self, deps):\n file_ignore_list = [\n re.compile(r'.*build/chromeos.*'),\n re.compile(r'.*build/cros_cache.*'),\n # No test target should rely on files in [output_dir]/gen.\n re.compile(r'^gen/.*'),\n ]\n return [f for f in deps if not any(r.match(f) for r in file_ignore_list)]", "def _resolve_dependencies(dependencymap):\n d = dict((k, set(dependencymap[k])) for k in dependencymap)\n r = []\n\n while d:\n # values not in keys (items without dep)\n # Basically if an item x is in values, then it has another item y in the keys\n # which depends on x : x -> y , but if x is not in keys, then it does not have\n # anyone that it depends on\n t = set(i for v in d.values() for i in v) - set(d.keys())\n # and keys without value (items without dep)\n # Basically if an item x has no items in the values, then it does not have any item\n # that it depends on\n t.update(k for k, v in d.items() if not v)\n # can be done right away\n r.append(t)\n # and cleaned up\n # Here, read every key value pair in the dict, and process further if the v is not empty\n # (k has dependencies) So basically we only take those items forward that that dependencies\n # Create a new dict such that for every key, the value does not contain items that have been\n # added to t, as they are a part of that set.\n d = dict(((k, v - t) for k, v in d.items() if v))\n\n return r", "def search_dependencies(self):\n result = [self.module.name]\n #First we look at the explicit use references from this module and all\n #its dependencies until the chain terminates.\n stack = self.needs\n while len(stack) > 0:\n module = stack.pop()\n if module in result:\n continue\n \n self.parent.load_dependency(module, True, True, False)\n if module in self.parent.modules:\n for dep in self.parent.modules[module].needs:\n modname = dep.split(\".\")[0]\n if modname not in result:\n result.append(modname)\n if modname not in stack:\n stack.append(modname)\n\n #Add any incidentals from the automatic construction of code. These can be from\n #executables that use special precision types without importing them or from\n #derived types. Same applies to the local members of this module.\n for ekey, anexec in list(self.executables.items()):\n for dep in anexec.search_dependencies():\n if dep is not None and dep not in result:\n result.append(dep)\n\n for member in list(self.members.values()):\n dep = member.dependency()\n if dep is not None and dep not in result:\n result.append(dep)\n \n return result", "def get_info_dependencies(self):\n opsconfig = self.config_json\n info_dep = {}\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_dep[\"ops_\" + info_i[\"name\"]] = info_i[\"dependencies\"]\n\n return info_dep", "def get_not_always_used(self):\n results_list = []\n\n # initial list is made of fixtures that are in the children\n initial_list = self.gather_all_required(include_parents=False)\n\n for c in self.get_leaves():\n j = 0\n for i in range(len(initial_list)):\n fixture_name = initial_list[j]\n if fixture_name not in c.gather_all_required():\n del initial_list[j]\n results_list.append(fixture_name)\n else:\n j += 1\n\n return results_list", "def _build_cache(self):\n self._dimensional_equivalents = dict()\n\n deps = dict((name, set(definition.reference.keys() if definition.reference else {}))\n for name, definition in self._units.items())\n\n for unit_names in solve_dependencies(deps):\n for unit_name in unit_names:\n if '[' in unit_name:\n continue\n parsed_names = tuple(self.parse_unit_name(unit_name))\n _prefix = None\n if parsed_names:\n _prefix, base_name, _suffix = parsed_names[0]\n else:\n base_name = unit_name\n prefixed = True if _prefix else False\n try:\n uc = ParserHelper.from_word(base_name)\n\n bu = self._get_root_units(uc)\n di = self._get_dimensionality(uc)\n\n self._root_units_cache[uc] = bu\n self._dimensionality_cache[uc] = di\n\n if not prefixed:\n if di not in self._dimensional_equivalents:\n self._dimensional_equivalents[di] = set()\n\n self._dimensional_equivalents[di].add(self._units[base_name]._name)\n\n except Exception as e:\n logger.warning('Could not resolve {0}: {1!r}'.format(unit_name, e))", "def all_dependencies():\n return Dependency.all_instances().keys()", "def dependencies(self):\n ready, goods, bads = self.dependency_check()\n if goods:\n for guy in goods:\n yield guy\n if bads:\n for guy1, guy2 in bads:\n yield guy1\n yield guy2", "def needs(self) :\r\n return ({'water need':self._waterNeed,'food need':self._foodNeed})", "def find_dependency_cycles(ir):\n errors = _find_module_dependency_cycles(ir)\n return errors + _find_object_dependency_cycles(ir)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the currently running Bot instance.
def bot(cls): return cls._cur_bot
[ "def current_app(self):\n return self.app", "def bot_id(self):\n return self._bot_id", "def get_instance(self):\n if not self.is_server_active():\n self._log('The TCPServer instance is not running!')\n return self._process", "def get_instance():\n if Overworld.__instance is None:\n Overworld()\n return Overworld.__instance", "def get_translator_instance():\n\n\t\tif (TranslatorInstance.__api == None):\n\n\t\t\tTranslatorInstance()\n\n\t\treturn TranslatorInstance.__api", "def instance(self):\n if hasattr(self, '_instance'):\n return self._instance\n\n if self.instance_uuid:\n server = nova.server_get(self._request, self.instance_uuid)\n return server\n\n return None", "def client(self) -> Optional[Client]:\n return self._active_client", "def get_shared_with_me(self):\n\n\t\treturn self.__shared_with_me", "def Instance():\n assert hasattr(OpManager, '_instance'), 'instance not initialized'\n return OpManager._instance", "def getApplication(self):\r\n return self.app", "def current():\n\n return Context.__current_context", "def instance(self):\n self._instance = self.stack_env.nova.servers.get(self._instance.id)\n return self._instance", "def get_instance():\n # Instance creation should be synchronized\n if not _ObjectTracker._instance:\n _ObjectTracker._instance = _ObjectTracker()\n\n return _ObjectTracker._instance", "def GetCurrentBackend(self):\n return networking.get_current_backend()", "def _get_current_object(self):\n if callable(self.__target):\n return self.__target()\n try:\n return getattr(self.__target, self.__name__)\n except AttributeError:\n raise RuntimeError('no object bound to %s' % self.__name__)", "def _get_activeWorkspace(self) -> \"adsk::core::Ptr< adsk::core::Workspace >\" :\n return _core.UserInterface__get_activeWorkspace(self)", "def site(self):\n import pywikibot\n if not self._site:\n self._site = pywikibot.Site(self._lang, self._project,\n self._config.username)\n return self._site", "def get_window(self):\n return self.get_object(self.__winid)", "def chat_client(self) -> ChatClient:\n return self.chat_clients[self.client_id]" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse and do whatever work necessary for the message. If the message necessitates a reply, save it to self.reply_msg.
def _parse(self): self.reply_msg = MessageHandler.fire_handlers(self)
[ "def process(self, message):\n assert self._state.connected\n try:\n prefix, command, params = parsing.parse(message)\n three_digits = re.compile('[0-9][0-9][0-9]')\n if three_digits.match(command):\n numeric_reply = int(command)\n if 0 <= numeric_reply <= 399:\n self._process_numeric_reply(\n numeric_reply, prefix, params, message)\n elif 400 <= numeric_reply <= 599:\n self._process_numeric_error(numeric_reply, params, message)\n else:\n self._logger.error(('Received numeric response out of ' +\n 'range: {}').format(command))\n raise MessageHandlingError(message)\n elif command == Cmd.PING:\n self._process_ping(params, message)\n elif command == Cmd.PRIVMSG:\n self._process_privmsg(prefix, params, message)\n elif command == Cmd.JOIN:\n self._process_join(prefix, params)\n elif command == Cmd.PART:\n self._process_part(prefix, params)\n elif command == Cmd.MODE:\n self._process_mode(prefix, params, message)\n elif command == Cmd.KICK:\n self._process_kick(prefix, params)\n elif command == Cmd.NICK:\n self._process_nick(prefix, params)\n elif command == Cmd.TOPIC:\n self._process_topic(prefix, params)\n elif command == Cmd.QUIT:\n self._process_quit(prefix, params)\n else:\n raise MessageHandlingError(message)\n except MessageHandlingError as e:\n self._logger.debug('Unhandled message: {}'.format(e))\n self._handler.handle_unhandled_message(str(e))\n except ParserError as e:\n self._logger.error('Message Parsing failed. {}'.format(e.message))\n self._logger.error('Message discarded!')", "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 handle_message(self, message): \n packets = Message.parse_xml(message)\n\n reply = self.dbase.process_packets(packets)\n\n return reply", "def handle_reply(self, msg):\n print msg", "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 receive_and_send_message(self):\n\n message_received = request.body.read().decode()\n print(get_chat_line_separator())\n print(chat_tag(DISPLAY_NAME_OTHER) + message_received)\n\n # Get reply for the message\n # Bot answers the message\n if self.tester_type == TESTER_BOT:\n # Get the reply from the bot\n t_start = time()\n bot_reply = self.conv.say(message_received)\n t = time() - t_start\n\n # Normalize and humanize the text\n bot_reply = humanize_text(normalize_text(bot_reply))\n\n # Add a thinking break\n sleep(0.5)\n\n # Add a delay to the message sending in case the bot responded\n # too fast\n estimated_writing_time = len(bot_reply) * self.writing_speed\n if t < estimated_writing_time:\n sleep(estimated_writing_time-t)\n\n print(chat_tag(DISPLAY_NAME_YOU) + bot_reply)\n return bot_reply\n\n # You answer the message\n return normalize_text(input(chat_tag(DISPLAY_NAME_YOU)))", "def setreply(self, msg):\n return CONTINUE", "def process_message(self, message):\r\n self.log.debug(\"Processing message '%s'...\" % message)\r\n\r\n if not ':' in message:\r\n self.log.error(\"Unable to parse message '%s'. Moving on...\" % message)\r\n return\r\n\r\n action, obj_identifier = message.split(':')\r\n self.log.debug(\"Saw '%s' on '%s'...\" % (action, obj_identifier))\r\n\r\n if action == 'update':\r\n # Remove it from the delete list if it's present.\r\n # Since we process the queue in order, this could occur if an\r\n # object was deleted then readded, in which case we should ignore\r\n # the delete and just update the index.\r\n if obj_identifier in self.actions['delete']:\r\n self.actions['delete'].remove(obj_identifier)\r\n\r\n self.actions['update'].add(obj_identifier)\r\n self.log.debug(\"Added '%s' to the update list.\" % obj_identifier)\r\n elif action == 'delete':\r\n # Remove it from the update list if it's present.\r\n # Since we process the queue in order, this could occur if an\r\n # object was updated then deleted, in which case we should ignore\r\n # the update and just delete the document from the index.\r\n if obj_identifier in self.actions['update']:\r\n self.actions['update'].remove(obj_identifier)\r\n\r\n self.actions['delete'].add(obj_identifier)\r\n self.log.debug(\"Added '%s' to the delete list.\" % obj_identifier)\r\n else:\r\n self.log.error(\"Unrecognized action '%s'. Moving on...\" % action)", "def process_next(self, msg_string):\n # Next message received - stop connection timer.\n self._stop_connection_timer_callback()\n\n # Create BiomioMessage instance form message string\n input_msg = None\n try:\n input_msg = self._builder.create_message_from_json(msg_string)\n except ValidationError, e:\n logger.exception('Not valid message - %s' % msg_string)\n logger.exception(e)\n\n # If message is valid, perform necessary actions\n if input_msg and input_msg.msg and input_msg.header:\n output_str = (msg_string[:256] + '...') if len(msg_string) > 256 else msg_string\n logger.debug('RECEIVED MESSAGE STRING: \"%s\" ' % output_str)\n\n # Refresh session if necessary\n if self._session and hasattr(input_msg.header,\n 'token') and self._session.refresh_token == input_msg.header.token:\n self._refresh_session()\n\n # Restore session and state (if no session, and message contains token)\n if not self._session and hasattr(input_msg.header, 'token') and input_msg.header.token:\n self._restore_state(refresh_token=str(input_msg.header.token))\n\n # Try to process RPC request subset, if message is RCP request - exit after processing\n\n if input_msg.msg.oid in ('rpcReq', 'rpcEnumNsReq', 'rpcEnumCallsReq'):\n self.process_rpc_request(input_msg)\n return\n\n # Process protocol message\n if not self._state_machine_instance.current == STATE_DISCONNECTED:\n self._process_message(input_msg)\n else:\n self._state_machine_instance.bye(protocol_instance=self,\n status='Invalid message sent (message string:%s)' % msg_string)", "def handle_message(self, msg):\n obj = msg.obj\n line = msg.line\n msg_id = msg.msg_id\n msg = msg.msg\n self.message_ids[msg_id] = 1\n if obj:\n obj = \":%s\" % obj\n sigle = msg_id[0]\n if linesep != \"\\n\":\n # 2to3 writes os.linesep instead of using\n # the previosly used line separators\n msg = msg.replace(\"\\r\\n\", \"\\n\")\n self.messages.append(\"%s:%3s%s: %s\" % (sigle, line, obj, msg))", "def PROCESS(\n parts = None,\n reply_address_object = None,\n subject_line = None,\n from_address = None,\n **kwargs\n):\n #1) get actual email content\n # todo: factor this out into the process_reply decorator\n reply_code = reply_address_object.address\n body_text, stored_files, signature = mail.process_parts(parts, reply_code)\n\n #2) process body text and email signature\n user = reply_address_object.user\n\n if signature != user.email_signature:\n user.email_signature = signature\n\n #3) validate email address and save user along with maybe new signature\n user.email_isvalid = True\n user.save()#todo: actually, saving is not necessary, if nothing changed\n\n #here we might be in danger of chomping off some of the \n #message is body text ends with a legitimate text coinciding with\n #the user's email signature\n body_text = user.strip_email_signature(body_text)\n\n #4) actually make an edit in the forum\n robj = reply_address_object\n add_post_actions = ('post_comment', 'post_answer', 'auto_answer_or_comment')\n if robj.reply_action == 'replace_content':\n robj.edit_post(body_text, title = subject_line)\n elif robj.reply_action == 'append_content':\n robj.edit_post(body_text)#in this case we don't touch the title\n elif robj.reply_action in add_post_actions:\n if robj.was_used:\n robj.edit_post(body_text, edit_response = True)\n else:\n robj.create_reply(body_text)\n elif robj.reply_action == 'validate_email':\n #todo: this is copy-paste - factor it out to askbot.mail.messages\n data = {\n 'site_name': askbot_settings.APP_SHORT_NAME,\n 'site_url': site_url(reverse('questions')),\n 'ask_address': 'ask@' + askbot_settings.REPLY_BY_EMAIL_HOSTNAME\n }\n template = get_template('email/re_welcome_lamson_on.html')\n\n mail.send_mail(\n subject_line = _('Re: %s') % subject_line,\n body_text = template.render(Context(data)),#todo: set lang\n recipient_list = [from_address,]\n )", "def process_message(self, user, msg, session=None, callback=None):\n reply = None\n if isinstance(msg, mplane.model.Specification):\n reply = self.submit_job(user, specification=msg, session=session, callback=callback)\n elif isinstance(msg, mplane.model.Redemption):\n job_key = msg.get_token()\n if job_key in self.jobs:\n job = self.jobs[job_key]\n reply = job.get_reply()\n if job.finished():\n self.jobs.pop(job_key, None)\n else:\n reply = mplane.model.Exception(token=job_key,\n errmsg=\"Unknown job\")\n elif isinstance(msg, mplane.model.Interrupt):\n job_key = msg.get_token()\n if job_key in self.jobs:\n job = self.jobs[job_key]\n logger.info(\"Scheduler: interrupting \" + job.specification.get_label())\n job.interrupt()\n reply = job.get_reply()\n else:\n reply = mplane.model.Exception(token=job_key,\n errmsg=\"Unknown job\")\n else:\n reply = mplane.model.Exception(token=msg.get_token(),\n errmsg=\"Unexpected message type\")\n\n return reply", "def handle_replies(self, message):\n if self.last_reply_timestamp == None or \\\n message.published > self.last_reply_timestamp:\n self.publish_message(\n message_id=message.id,\n content=message.text,\n to_addr=message.title,\n from_addr=message.author.screen_name,\n session_event=TransportUserMessage.SESSION_RESUME,\n transport_type=self.transport_type,\n transport_metadata=message.raw,\n )\n self.last_reply_timestamp = message.published", "def handle_reply(self, msg):\n for append_msg in self._message_recorders.values():\n append_msg(msg)\n return super(BlockingTestClient, self).handle_reply(msg)", "def parse_message(self, message):\n messageClass = Message(self.message_type)\n\n try:\n msg = messageClass(message)\n msg.decode()\n return msg\n except (ValueError, TypeError), err:\n self.log(\"Failed to read input message as %s.\\n\"\n \"Cause: %s\\n\"\n \"Original message: '%s'\"\n % (messageClass.typeName(), err, message),\n logLevel.WARN)\n return False", "def _muc_message(self, msg):\n # Ignore messages from unauthorized users\n if not self.xmpp.is_jid_room_user(self.xmpp.get_jid(msg)):\n return\n\n chatbot = self.chatbot\n txt = msg.get('body', '').strip()\n\n # We are going to analyze the whole user message as it appeared in the chat room\n # We don't want to learn anything, just see if we are confident enough to post a reply into the room\n try:\n start_time = time.time()\n # The next lines are taken from ChatBot.get_response()\n session_id = str(chatbot.default_session.uuid)\n input_statement = chatbot.input.process_input_statement(txt)\n\n for preprocessor in chatbot.preprocessors:\n input_statement = preprocessor(chatbot, input_statement)\n\n statement, response = chatbot.generate_response(input_statement, session_id)\n\n if response.confidence > self.muc_confidence_threshold:\n chatbot.conversation_sessions.update(session_id, (statement, response,))\n res = chatbot.output.process_response(response, session_id)\n reply = res.text\n logger.info('Found chatbot response in MUC room (with confidence %s) in %g seconds: \"%s\" -> \"%s\"',\n res.confidence, (time.time() - start_time), txt, reply)\n self.xmpp.msg_reply(msg, reply)\n except Exception as exc:\n logger.error('Chatbot malfunction in MUC room while analyzing text \"%s\"', txt)\n logger.exception(exc)", "def _process_message(self, input_msg):\n try:\n # State machine instance has callback with the same name as possible messages, that it could\n # receive from client. Retrieve function object (callback) for message and perform transition.\n logger.info('RECEIVED MESSAGE: \"%s\" ' % str(input_msg.msg.oid))\n make_transition = getattr(self._state_machine_instance, '%s' % input_msg.msg.oid, None)\n if make_transition:\n if self._state_machine_instance.current == STATE_DISCONNECTED:\n return\n\n self._last_received_message = input_msg\n make_transition(request=input_msg, protocol_instance=self)\n\n # Start connection timer, if state machine does no reach its final state\n if not (self._state_machine_instance.current == STATE_DISCONNECTED):\n self._start_connection_timer_callback()\n else:\n self._state_machine_instance.bye(request=input_msg, protocol_instance=self,\n status='Could not process message: %s' % input_msg.msg.oid)\n except FysomError, e:\n logger.exception('State event for method not defined')\n self._state_machine_instance.bye(request=input_msg, protocol_instance=self, status=str(e))\n except AttributeError:\n status_message = 'Internal error during processing next message'\n logger.exception(status_message)\n self._state_machine_instance.bye(request=input_msg, protocol_instance=self, status=status_message)", "def reply_checker(self):\n logger.info(\"ENTERED REDDIT INBOX SCRAPER\")\n while True:\n try:\n # TODO: CHANGE TO STREAM FOR PROD\n # PULL REDDIT INBOX STREAM\n new_reddit_messages = self.reddit.reddit_conn.inbox.unread()\n # LOOP THROUGH REDDIT MESSAGES\n for message in new_reddit_messages:\n # GET REDDIT USERNAME / ID OF NEW MESSAGE\n reddit_username_of_new_message = message.author.name\n message_id = message.id\n # CHECK TO SEE IF MESSAGE IS ALREADY IN MESSAGE QUEUE\n message_exists = Messages.query.filter_by(\n recipient=reddit_username_of_new_message).filter_by(\n ca_user_id_assoc=message_id).first()\n if not message_exists:\n # FIND PARENT COMMENT, SO WE CAN IDENTIFY WHO REACHED OUT\n parent_message = Messages.query.filter_by(\n recipient=reddit_username_of_new_message).filter_by(\n ca_user_id_assoc='parent').first()\n if parent_message:\n # GET THE SENDERS EMAIL\n sender = parent_message.sender\n # GET THE BODY TEXT OF THE NEW MESSAGE\n body = message.body\n parent_message_subect = parent_message.subject\n # THE IDEA IS TO CODE THE REDDIT-EMAIL LINK IN JSON:\n reddit_user_email_id = \"\\\"username\\\": \\\"{reddit_username_of_new_message}\\\", \" \\\n \"\\\"message_id\\\": \\\"{message_id}\\\", \" \\\n \"\\\"subject\\\": \\\"{subject}\\\"\".format(\n reddit_username_of_new_message=reddit_username_of_new_message,\n message_id=message_id,\n subject=message.subject)\n\n subject = \"{\" + reddit_user_email_id + \"}\"\n # STORE MESSAGE IN DATABASE\n ca_message = Messages(sender=reddit_username_of_new_message,\n recipient=sender,\n body=body,\n subject=subject,\n date_sent=datetime.datetime.now(),\n has_been_sent_for_processing=0,\n ca_user_id_assoc=message.parent_id)\n\n # WE HAVE ADDED NEW MESSAGE TO DB, TIME TO EMAIL THE COMPLAINING ABOUT USER WHO STARTED CONVO\n # We want to notify the user that they received a response\n Messages.add_record(ca_message)\n # TODO: UPDATE FOR PROD\n self.send_email(sender,\n \"router@communityphone.org\",\n body,\n subject)\n ca_message.has_been_sent_for_processing = 1\n self.reddit.reddit_conn.inbox.mark_read([message])\n db.session.commit()\n else:\n # IF PARENT MESSAGE DOESNT EXIST, MARK AS READ\n self.reddit.reddit_conn.inbox.mark_read([message])\n\n except Exception as e:\n logger.info(\"EXCEPTION IN REDDIT READER\")\n traceback.print_exc()\n\n # logger.info(\"NOTHING NEW IN INBOX STREAM--SLEEPING\")\n time.sleep(100)", "def parse_message_div(self, msg, url, pagenum):\n #Set default edit status\n edit_status = 'Unedited'\n\n if type(msg) is not element.Tag:\n print(f'Msg obj: {msg}')\n\n #Get profile URL\n try:\n _url = 'https://community.upwork.com' + \\\n msg.find('a', class_='lia-link-navigation lia-page-link lia-user-name-link user_name', href=True)['href']\n except:\n _url = '**Deleted Profile**'\n\n #Get profile name\n try:\n name = msg.find('a', class_='lia-link-navigation lia-page-link lia-user-name-link user_name').find('span').text\n except:\n name = '**Deleted Profile**'\n #Get profile joindate\n try:\n member_since = msg.find('span', class_='custom-upwork-member-since').text.split(': ')[1]\n except:\n member_since = '**Deleted Profile**'\n\n try:\n #Get profile rank\n rank = msg.find('div', class_='lia-message-author-rank lia-component-author-rank lia-component-message-view-widget-author-rank')\\\n .text.replace(' ', '').strip()\n except:\n rank = '**Deleted Profile**'\n \n #Get post/edit info container\n dateheader = msg.find('p', class_='lia-message-dates lia-message-post-date lia-component-post-date-last-edited lia-paging-page-link custom-lia-message-dates')\n \n if dateheader is not None:\n #Get postdate\n timestamp = dateheader.find('span', class_='DateTime lia-message-posted-on lia-component-common-widget-date')\\\n .find('span', class_='message_post_text').text\n \n #Try to parse an editdate if available\n try:\n e = dateheader.find('span', class_='DateTime lia-message-edited-on lia-component-common-widget-date')\n for span in e.find_all('span', class_='message_post_text'):\n if span.text != 'by':\n editdate = span.text\n except:\n editdate = ''\n\n #Try to parse an editor name if available\n try:\n edited_by = dateheader.find('span', class_='username_details').find('span', class_='UserName lia-user-name lia-user-rank-Power-Member lia-component-common-widget-user-name')\\\n .find('a').find('span').text\n except:\n edited_by = ''\n \n #Try to post an editor URL\n try:\n box = dateheader.find('span', class_='username_details').find('span', class_='UserName lia-user-name lia-user-rank-Power-Member lia-component-common-widget-user-name')\\\n .find('a')\n edited_url = 'https://community.upwork.com/' \n edited_url += str(box).split('href=\"')[1].split('\"')[0]\n except Exception as e:\n edited_url = ''\n else:\n timestamp, editdate, edited_by, edited_url = datetime.now().strftime(\"%b %d, %Y %I:%M:%S %p\"), datetime.now().strftime(\"%b %d, %Y %I:%M:%S %p\")\\\n , '**Info Inaccessible**', '**Info Inaccessible**'\n\n #If we have editor info, generate MD5 hash ID for them\n if edited_by != '' and edited_url != '':\n editor_id = hashlib.md5((edited_by + edited_url).encode('utf-8')).hexdigest()[:16]\n else:\n editor_id = ''\n\n #Get post index and add to checked indices\n postdate = str(timestamp)\n index = msg.find('span', class_='MessagesPositionInThread').find('a').text.replace('\\n', '')\n\n #Parse message content\n body = msg.find('div', class_='lia-message-body-content').find_all(['p', 'ul'])\n post = ''\n for p in body:\n if p.text == '&nbsp':\n pass\n if p.name == 'ul':\n li = p.find_all('li')\n for item in li:\n post += item.text\n else:\n post += ('' + p.text + '').replace('\\u00a0', '').replace('\\n', '')\n\n #Generate author user object\n u = User(name, member_since, _url, rank)\n\n #Generate post object\n p = Post(postdate, editdate, post, u, url, pagenum, index, url.split('/t5/')[1].split('/')[0])\n\n return p, editor_id, edited_url, edited_by" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }