query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Attempts to get something from the results queue.
def results_q_get(self): while not self.stopped(): try: return self.results_queue.get(timeout=self.heart_beat) except queue.Empty: pass raise StopIteration()
[ "def _get_result(self):\n if self.verbose:\n print('Trying to get a result at %f' % (time()-self.t0, ))\n r = self.results_queue.get()\n ijob = r['ijob']\n if self.verbose:\n print('Got result %d at %f' % (ijob, time()-self.t0))\n self.results[ijob] = r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Try to put the given value into the output queue until it is inserted (if it was previously full), or the stop signal was given.
def q_put(self, val): put = False while not put and not self.stopped(): try: self.q.put(val, timeout=self.heart_beat) put = True except queue.Full: pass
[ "def q_put(self, val):\n put = False\n while not put and not self.stopped():\n try:\n self.out_q.put(val, timeout=self.heart_beat)\n put = True\n except queue.Full:\n pass", "def _put_nowait(self, value):\n while True:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Try to put the given value into the output queue while keeping an eye out for an exit request.
def q_put(self, val): put = False while not put and not self.stopped(): try: self.out_q.put(val, timeout=self.heart_beat) put = True except queue.Full: pass
[ "def queue(self, queue_, value):\n while not self.closed:\n try:\n queue_.put(value, block=True, timeout=1)\n return\n except queue.Full:\n continue", "def _put_nowait(self, value):\n while True:\n if self._waiting_consume...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shortcut to get the point format
def point_format(self) -> PointFormat: return self.points.point_format
[ "def fmt_point(point):\n assert len(point) == 2\n return f\"({point[0]},{point[1]})\"", "def point(value):\r\n return '({}, {})'.format(value.x(), value.y())", "def coords_format(format):\n if format == 'galactic':\n return 'galactic'\n elif format in ['fk5','icrs']:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a new 2D numpy array with the x,y,z coordinates >>> import laspy >>> las = laspy.read("tests/data/simple.las") >>> xyz = las.xyz >>> xyz.ndim 2 >>> xyz.shape (1065, 3) >>> np.all(xyz[..., 0] == las.x) True
def xyz(self) -> np.ndarray: return np.vstack((self.x, self.y, self.z)).transpose()
[ "def test_xyz_to_np_array(self):\n xyz_dict = {'symbols': ('O', 'N', 'C', 'H', 'H'),\n 'isotopes': (16, 14, 12, 1, 1),\n 'coords': ((1.1746411, -0.15309781, 0.0),\n (0.06304988, 0.35149648, 0.0),\n (-1.12708952,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add multiple extra dimensions at once
def add_extra_dims(self, params: List[ExtraBytesParams]) -> None: self.header.add_extra_dims(params) new_point_record = record.PackedPointRecord.from_point_record( self.points, self.header.point_format ) self.points = new_point_record
[ "def add_extra_dim(self, name: str, type: str, description: str = \"\"):\n self.add_extra_dims([(name, type, description)])", "def adddim(fld, size=1):\n fld = np.atleast_1d(fld)\n s = np.ones(fld.ndim + 1).astype(int)\n s[0] = int(size)\n return np.tile(fld, s)", "def _add_dimensions(self, i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the information stored in the header to be in sync with the actual data. This method is called automatically when you save a file using
def update_header(self) -> None: self.header.partial_reset() self.header.point_format_id = self.points.point_format.id self.header.point_data_record_length = self.points.point_size if len(self.points) > 0: self.header.update(self.points) if self.header.version.minor...
[ "def update_header(self):\n pass", "def _save_header(self):\n\n\t\tstr=struct.pack(self.LUKS_FORMAT, self.magic, self.version, self.cipherName, self.cipherMode, self.hashSpec, \\\n self.payloadOffset, self.keyBytes, self.mkDigest, self.mkDigestSalt, self.mkDigestIterations, self.uui...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This changes the scales and/or offset used for the x,y,z dimensions. It recomputes the internal, nonscaled X,Y,Z dimensions to match the new scales and offsets. It also updates the header with the new values of scales and offsets.
def change_scaling(self, scales=None, offsets=None) -> None: self.points.change_scaling(scales, offsets) self.header.scales = scales self.header.offsets = offsets
[ "def _update_change_information(self) :\n \n if None in [self._world_to_slice, self._image, self._display_coordinates] :\n return\n \n if self.display_coordinates in [\"physical\", \"nearest_axis_aligned\"] :\n # Transform the bounding box of the image to find the c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Automatically called by Python when the attribute named 'item' is no found. We use this function to forward the call the point record. This is the mechanism used to allow the users to access the points dimensions directly through a LasData.
def __getattr__(self, item): try: return self.points[item] except ValueError: raise AttributeError( f"{self.__class__.__name__} object has no attribute '{item}'" ) from None
[ "def GetPoint(self):\n ...", "def plot(self, plotItem: PlotItem) -> Any:\n raise NotImplementedError", "def object_at(self, point, **kwargs):\n args = dict(self.defaults)\n args.update(**kwargs)\n page = self.document.pages[args['page']] # AS Pageref!\n #point = (point[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is called on every access to an attribute of the instance. Again we use this to forward the call the the points record But this time checking if the key is actually a dimension name so that an error is raised if the user tries to set a valid LAS dimension even if it is not present in the field.
def __setattr__(self, key, value): try: key = OLD_LASPY_NAMES[key] except KeyError: pass if ( key in self.point_format.dimension_names or key in self.points.array.dtype.names ): self.points[key] = value elif key in dim...
[ "def __setattr__(self, key, value):\n if key in self.point_format.dimension_names:\n self.points[key] = value\n elif key in dims.DIMENSIONS_TO_TYPE:\n raise ValueError(\n f\"Point format {self.point_format} does not support {key} dimension\"\n )\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prepares ElasticSearch index for work if it's not yet ready.
def prepare_environment(): elastic_search = Elasticsearch('{}:{}'.format( _CONFIG.elastic.elastic_hostname, _CONFIG.elastic.elastic_port)) try: if not elastic_search.indices.exists(_CONFIG.elastic.elastic_index): elastic_search.indices.create( index=_CONFIG.el...
[ "def init(self):\n for name in self._indexes.keys():\n LogService.debug(\"Init on %s\" % name)\n try:\n self.rebuild(self._indexes.get(name))\n except NotFoundError or KeyError or AttributeError as e:\n LogService.warning(\"Error re-initing index...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
accept data from an mca call and make a transformer
def mca_transformer(transform_data): M, dims, index, v0v1 = transform_data def transform(dfp): # dims, index, v0v1 P = np.zeros((len(dfp), dims), dtype=float) print("transforming") for i, (_, row) in (enumerate(dfp.iterrows())): ivec = np.zeros(M) for col,...
[ "def transform(self, data):", "def __transform_data(self, parameter, data):\n # Identify the type of transform that we're doing\n if self.transform_parameters[parameter]['t_type'] == 'simple':\n transform_func = self.__simple_transform\n elif self.transform_parameters[parameter]['t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
given either, uid, email or cell delete user
def delete_user(self, uid: typing.Union[str, None] = None, email: typing.Union[str, None] = None, cell: typing.Union[str, None] = None) -> tuple: if (uid != "") and (uid is not None): user_instance: UserModel = UserModel.query(UserModel.uid == uid).get() if isinstanc...
[ "def delete_user():", "def deletedata(self, uid):\n return self.deleteemail(uid)", "def test_delete_users_by_username_hooks_by_uid(self):\n pass", "def delete_user(self, email, **kwargs):\n return self.delete(self.MakeMultidomainUserProvisioningUri(email), **kwargs)", "def delete_user(user)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return a user either by uid, cell or email
def get_user(self, uid: typing.Union[str, None] = None, cell: typing.Union[str, None] = None, email: typing.Union[str, None] = None) -> tuple: if (uid is not None) and (uid != ""): user_instance: UserModel = UserModel.query(UserModel.uid == uid).get() if isinstance(us...
[ "def get_user_by_email(self, strategy, email):\r\n return strategy.storage.user.user_model().objects.get(email=email)", "def get_user_by_email(email):\n for user in USERS:\n if user.email == email:\n return user", "def get_user_by_email(email: str) -> dict:\n for user in get_curre...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the main page, frame data page and icon.png from all characters
def _get_all_characters(self, main_page): heading_div = main_page.find('div', {'class': 'heading'}) # dustloop changed its code so this is necessary character_div = heading_div.next.next if character_div is None: # CF fix character_div = main_page.find_all('div', {'class': 'cente...
[ "def page():\n return load(\"page.png\")", "def jig2Main(symbolPath='symboltable', pagefiles=glob.glob('page-*')):\n print(\"** symbolPath=%s\" % symbolPath, file=sys.stderr)\n print(\"** pagefiles= %d: %s\" % (len(pagefiles), pagefiles), file=sys.stderr)\n\n doc = Doc()\n pages = Obj({'Type': '/Pa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find the specific character given a name
def _get_specific_character(self): characters = self._get_all_characters(self._main_page) for character in characters.keys(): if self._find_name.lower() in character.lower(): return {character: characters[character]} else: raise CharacterNotFound
[ "def findCharObj(self, characterName):\n for char in range(len(self._charList)):\n if self._charList[char].getName() == characterName:\n return self._charList[char]", "def find_chr(str_, chr):\n for i in range(0, Utils.len(str_)):\n if str_[i] == chr:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse a bs4 object cointaining the character's page and extract its sprite links
def _get_sprites(self): character = self._get_main_page(self._data[self.name]['sprites']) result = {} for big_tag in character.find_all('big'): # big contain the move name. Its next siblings contain the sprite link. move_name = big_tag.get_text() sprite = '' ...
[ "def _get_all_characters(self, main_page):\n\n heading_div = main_page.find('div', {'class': 'heading'}) # dustloop changed its code so this is necessary\n character_div = heading_div.next.next\n\n if character_div is None: # CF fix\n character_div = main_page.find_all('div', {'cla...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Translate a value in a range to a value in the servo's limits
def translate(self, value, left_min, left_max, right_min=None, right_max=None): if right_min is None: right_min = self.values['pulse_min'].data if right_max is None: right_max = self.values['pulse_max'].data # Figure out how 'wide' each range is left_span = left_ma...
[ "def scale_servos(self, value, minrange=500, maxrange=2500):\n min_servo_range = -1\n max_servo_range = 1\n return min_servo_range + (max_servo_range - min_servo_range) / (maxrange - minrange) * (value - minrange)", "def translate_range(self, value, leftMin, leftMax, rightMin, rightMax):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prueba transformar una lista de ciudades
def test_obtener_lista_ciudades_transformadas(self): lista = [{"id": 707860, "name": "Hurzuf", "country": "UA", "coord": {"lon": 34.283333, "lat": 44.549999}}, {"id": 519188, "name": "Novinki", "country": "RU", "coord": {"lon": 37.666668, "lat": 55.683334}}] lista_transformada = CIUDADES_CONTROLLER.obte...
[ "def transform(self):\n\n # definição de constantes\n self.interessante = ['regiao', 'estado', 'municipio', 'data', 'dias_caso_0',\n 'obitosAcumulado', 'casosAcumulado', 'obitosNovo', 'casosNovo',\n 'obitosMMhab', 'casosMMhab', 'obitosAcumMMhab',...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the primary_language of this BlogAuthorCloneRequestVNext.
def primary_language(self, primary_language): self._primary_language = primary_language
[ "def primary_lead_source(self, primary_lead_source):\n\n self._primary_lead_source = primary_lead_source", "def primary_election(self, primary_election):\n\n self._primary_election = primary_election", "def set_default_language(language_code):\n thread_locals.DEFAULT_LANGUAGE = language_code", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the blog_author of this BlogAuthorCloneRequestVNext.
def blog_author(self, blog_author): if self.local_vars_configuration.client_side_validation and blog_author is None: # noqa: E501 raise ValueError("Invalid value for `blog_author`, must not be `None`") # noqa: E501 self._blog_author = blog_author
[ "def set_author (self, author):\n self.author = author", "def set_author(self, author: str):\r\n\r\n self.metadata['common']['author'] = author", "def set_rev_author(self, author):\n self.__rev_props[\"svn:author\"] = author", "def author(self, author):\n\n self._author = author", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plot Exponential Moving Average Indicator. 绘出EMA曲线
def plot_ema( self, head: int = 90, ns: Optional[List[int]] = None, verbose: bool = False ): if ns is None: ns = EXPMA_N func = self.ema verbose_func = self._plot_stock_data self._plot_moving_lines( func=func, verbose_func=verbose_func, ...
[ "def plot_ema(ax, data):\n \n ema_indicator = talib.EMA(data['Adj_Close'], timeperiod=30)\n \n ax.plot(data[\"Date\"], ema_indicator, label='Exponential Moving Average', color=\"aqua\")", "def plot_kaufman(ax, data):\n\n\n kaufman_ind = talib.KAMA(data['Adj_Close'], timeperiod=30)\n \n ax.pl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plot MACD (Moving Average Convergence and Divergence) Indicator. 绘出MACD曲线
def plot_macd(self, head: int = 90): df_macd = self.macd() if head: df_macd = df_macd.tail(head) df_macd.loc[:, "color"] = df_macd["macd"].apply( lambda x: "red" if x >= 0 else "green" ) layout = set_layout() fig = go.Figure(layout=layout) ...
[ "def plot_macd(ax, data):\n\n\n macd, macdsignal, macdhist = talib.MACD(data['Adj_Close'], fastperiod=12, slowperiod=26, signalperiod=9)\n \n ax.plot(data[\"Date\"], macd, label=\"macd\", color=\"lime\")\n ax.plot(data[\"Date\"], macdsignal, label=\"macdsignal\", color=\"crimson\")\n ax.plot(data[\"D...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plot VRSI (Volumn Relative Strength Index) Indicator. 绘出VRSI曲线。
def plot_vrsi(self, head: int = 90, ns: Optional[List] = None): if ns is None: ns = RSI_N func = self.vrsi verbose_func = self._plot_stock_data self._plot_moving_lines( func=func, verbose_func=verbose_func, y="rsi", name="VRSI"...
[ "def plot_pvi(close,volume):\r\n\tpv=pvi(close,volume)\r\n\tpvisignal=pd.Series(pv.rolling(10).mean(), name= \"PVIsignal\")\r\n\tfig = plt.figure()\r\n\tax1 = fig.add_subplot(211, ylabel='Values')\r\n\tclose.plot(ax=ax1, color='g', lw=2., legend=True,figsize=(13,9))\r\n\tax2 = fig.add_subplot(212, ylabel='PVI')\r\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plot Volumn over time. 绘出交易量能柱状图。
def plot_volumn(self, head: int = 90): df_volumn = self._df.copy() data = self._plot_volumn_data(df_volumn, head) layout = set_layout() fig = go.Figure(data=[data], layout=layout) fig.update_layout(title_text=f"Volumn Chart ({self.stock_code})") fig.show()
[ "def plot_V(self):\n plt.figure()\n plt.plot(times, np.ones_like(times) * self.thr, '--',\n label='threshold', color='black')\n plt.plot(times, np.zeros_like(times), color='black')\n for i in range(self.output_shape):\n plt.plot(times, self.Vt[i], '.', label='V...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plot VMACD (Volumn Moving Average Convergence and Divergence) Indicator. 绘出VMACD曲线
def plot_vmacd(self, head: int = 90): df_vmacd = self.vmacd() if head: df_vmacd = df_vmacd.tail(head) df_vmacd.loc[:, "color"] = df_vmacd["macd"].apply( lambda x: "red" if x >= 0 else "green" ) layout = set_layout() fig = go.Figure(layout=layout)...
[ "def plot_vmacd(self, head: int = 90):\n df_vmacd = self.vmacd()\n if head:\n df_vmacd = df_vmacd.tail(head)\n\n df_vmacd.loc[:, \"color\"] = df_vmacd[\"macd\"].apply(\n lambda x: \"red\" if x >= 0 else \"green\"\n )\n\n layout = self._set_layout()\n f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plot VSTD chart. 绘出VSTD曲线
def plot_vstd(self, head: int = 90, ns: Optional[List] = None): if ns is None: ns = MD_N func = self.vstd verbose_func = self._plot_volumn_data self._plot_moving_lines( func=func, verbose_func=verbose_func, y="vstd", name="vstd...
[ "def plot_VTx_variance(self, ax):\n V = self.V\n A = self.A\n b = self.b\n Ax = self.Ax\n x_ls_no = solve(A,b)\n x_ls = solve(A,Ax)\n\n ax.plot(dot(V.T, x_ls), 'r-', label='clean', lw=2.0)\n ax.plot(dot(V.T, x_ls_no), 'ko-', label='noisy')\n ax.set_xlabel(r'$...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plot ENV indicator. 绘出ENV曲线。
def plot_env(self, head: int = 90, n: int = 14, verbose: bool = False): df_env = self.env(n=n) self._plot( df=df_env, head=head, title="ENV", lines=["up", "down"], verbose=verbose )
[ "def plot_env_2D(ax):\n\n\tax.plot([0], [0], 'o', markersize=8, color='black', label='Earth')\n\tax.plot([cst.d_M * np.cos(t_) for t_ in np.linspace(0, 2*np.pi, 1000)], [cst.d_M * np.sin(t_) for t_ in np.linspace(0, 2*np.pi, 1000)], '-', \\\n\t\tlinewidth=1, color='black', label='Moon trajectory')", "def plot_env...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plot ADTM(23,8) indicator. 绘出动态买卖气指标 (ADTM(23, 8))
def plot_adtm(self, head: int = 90): df_adtm = self.adtm() self._plot(df=df_adtm, head=head, title="ADTM", lines=["adtm", "adtmma"])
[ "def plot_dry_adiabats(ax, t0=None, p=None, **kwargs):\n import numpy as np\n from matplotlib.collections import LineCollection\n # Determine set of starting temps if necessary\n if t0 is None:\n xmin, xmax = ax.get_xlim()\n t0 = np.arange(xmin, (xmax + 20) + 1, 15) #* units.degC\n\n # Get pressure level...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plot OBV (On Balance Volumn) Indicator。绘出能量指标
def plot_obv(self, head: int = 90): df_obv = self.obv() self._plot(df=df_obv, head=head, title="OBV", lines=["obv"])
[ "def plot_obv(df,vol):\r\n\tob=obv(df,vol)['OBV']\r\n\tobvsignal=pd.Series(ob.rolling(10).mean(),name= 'obvsignal')\r\n\tob.plot(legend=True, figsize=(10,5))\r\n\tobvsignal.plot(legend=True)", "def orb_vel_plot(v1,v2,t):\n plt.figure(figsize=(10,8))\n plt.plot(t, v1, label = r'$\\alpha$ Cen A'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plot RC (Price rate of Change) Indicator 绘出价格变化率指标
def plot_rc(self, head: int = 90, n: int = 30): df_rc = self.rc(n=n) self._plot(df=df_rc, head=head, title="RC", lines=["arc"])
[ "def plot_roc(df,w):\r\n\troc=rate_of_change(df,w)['ROC']\r\n\tfig = plt.figure()\r\n\tax1 = fig.add_subplot(211, ylabel='Values')\r\n\tdf.plot(ax=ax1, color='g', lw=2., legend=True,figsize=(13,9))\r\n\tax2 = fig.add_subplot(212, ylabel='ROC')\r\n\troc.plot(ax=ax2, color='b', lw=2., legend=True,grid=True)\r\n\tplt....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plot BOLL line indicator 绘出布林线。
def plot_bbiboll( self, head: int = 90, n: int = 11, m: int = 6, verbose: bool = False ): df_boll = self.bbiboll(n=n, m=m) self._plot( df=df_boll, head=head, title="BBIBOLL", lines=["upr", "bbiboll", "dwn"], verbose=verbose, ...
[ "def plotIndicator(self, ax, xlims, ylims, linec):\n ax.plot(xlims,ylims,linec)", "def abline(slope, intercept):\n axes = plt.gca()\n x_vals = np.array(axes.get_xlim())\n y_vals = intercept + slope * x_vals\n plt.plot(x_vals, y_vals, ':')", "def abline(slope, intercept):\n axes = plt.gca()...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Kernel for deleting particles if they are out of bounds.
def DeleteParticle(particle, fieldset, time): print('particle is deleted') #print(particle.lon, particle.lat, particle.depth) particle.delete()
[ "def delete_particle():\n function = LegacyFunctionSpecification()\n function.must_handle_array = True\n #function.can_handle_array = True\n function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN,\n description = \"Index of the particle to be remov...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a Zipline bundle for US stocks. This function defines the bundle parameters but does not ingest the actual data. To ingest the data, see `ingest_bundle`.
def create_usstock_bundle(code, sids=None, universes=None, free=False, data_frequency=None): params = {} params["ingest_type"] = "usstock" if sids: params["sids"] = sids if universes: params["universes"] = universes if free: params["free"] = free if data_frequency: ...
[ "def create_bundle_from_db(code, from_db, calendar,\n start_date=None, end_date=None,\n universes=None, sids=None,\n exclude_universes=None, exclude_sids=None,\n fields=None):\n params = {}\n params[\"ingest_type\"] ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a Zipline bundle from a history database or realtime aggregate database. You can ingest 1minute or 1day databases. This function defines the bundle parameters but does not ingest the actual data. To ingest the data, see `ingest_bundle`.
def create_bundle_from_db(code, from_db, calendar, start_date=None, end_date=None, universes=None, sids=None, exclude_universes=None, exclude_sids=None, fields=None): params = {} params["ingest_type"] = "from_db" ...
[ "def _create_bundle(self, payload=None, custody=None, lifetime=None):\n # The bundle payload is a Base64 encoded string\n bundle = \"Source: %s\\n\" % self._dtn_source_eid\n bundle += \"Destination: %s\\n\" % self._destination_eid\n # Set bundle custody processing flag\n if custod...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
List available data bundles and whether data has been ingested into them. Returns dict data bundles and whether they have data (True indicates data, False indicates config only)
def list_bundles(): response = houston.get("/zipline/bundles") houston.raise_for_status_with_json(response) return response.json()
[ "def fetch_bundles(bundle_id):\n return fetch_data(\"/bundles/%s\" % (bundle_id))", "def get_loaded_bundles():\n loaded = []\n loaded_names = []\n for bundle_name in loaded_bundle_names:\n if not bundle_name in loaded_names:\n loaded_names.append(bundle_name)\n loaded.appe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the current default bundle, if any. Returns dict default bundle
def get_default_bundle(): response = houston.get("/zipline/config") houston.raise_for_status_with_json(response) # It's possible to get a 204 empty response if not response.content: return {} return response.json()
[ "def bundle(self):\n return dict(bundle=self.data['bundle'])", "def bundle(self):\n return self._bundle", "def set_default_bundle(bundle):\n data = {\n \"default_bundle\": bundle\n }\n response = houston.put(\"/zipline/config\", data=data)\n houston.raise_for_status_with_json(re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the default bundle to use for backtesting and trading. Setting a default bundle is a convenience and is optional. It can be overridden by manually specifying a bundle when backtesting or trading.
def set_default_bundle(bundle): data = { "default_bundle": bundle } response = houston.put("/zipline/config", data=data) houston.raise_for_status_with_json(response) return response.json()
[ "def bundle(self, bundle):\n\n self._bundle = bundle", "def set_default_backend(new_default_backend):\n global __default_backend\n assert new_default_backend in __SUPPORTED_BACKENDS, (\n \"Backend %s is not supported\" % new_default_backend\n )\n __default_backend = new_default_backend",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a pyfolio PDF tear sheet from a Zipline backtest result.
def create_tearsheet(infilepath_or_buffer, outfilepath_or_buffer=None): url = "/zipline/tearsheets" # Pyfolio can take a long time timeout = 60*60*5 if infilepath_or_buffer == "-": infilepath_or_buffer = sys.stdin.buffer if six.PY3 else sys.stdin response = houston.post(url, data=infile...
[ "def create_pdf(f,s1,s2='',s3=''):\n # does not need reportlab!\n if s1 == 'White Ballot': s1 = '\"'+'_'*10+'\"'\n cod = zlib.compress('BT /F1 16 Tf ET\\r\\nBT 300 270 Td (%s) Tj ET\\r\\nBT /F1 48 Tf ET\\r\\nBT 5 180 Td (%16s) Tj ET\\r\\nBT /F1 12 Tf ET\\r\\nBT 10 50 Td (%s) Tj ET'%(s3,s1,s2))\n open(f,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Trade a Zipline strategy.
def trade(strategy, bundle=None, account=None, data_frequency=None): params = {} if bundle: params["bundle"] = bundle if account: params["account"] = account if data_frequency: params["data_frequency"] = data_frequency response = houston.post("/zipline/trade/{0}".format(stra...
[ "def placeTrade(trade):\n raise NotImplementedError()", "def trade(context, data):\n # Create a single series from our stock and bond weights\n total_weights = pd.concat([context.stock_weights, context.bond_weights])\n \n # Create a TargetWeights objective\n target_weights = opt.TargetWeights(t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
List actively trading Zipline strategies. Returns dict
def list_active_strategies(): response = houston.get("/zipline/trade") houston.raise_for_status_with_json(response) return response.json()
[ "def _get_strategies(self) -> Dict[str, str]:\n strategies = [method for method in dir(self) if STRATEGY_IDENTIFIER in method]\n\n if not strategies:\n logger.warning(\n \"There are no strategy provided. \"\n \"Make sure the implemented strategy methods \"\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Cancel actively trading strategies.
def cancel_strategies(strategies=None, accounts=None, cancel_all=False): params = {} if strategies: params["strategies"] = strategies if accounts: params["accounts"] = accounts if cancel_all: params["cancel_all"] = cancel_all response = houston.delete("/zipline/trade", param...
[ "def cancel(self, order: Order):\n pass", "def cancel_plan(self):\n for asv in self.asvs:\n asv._cancel_action = True", "def cancel_workers(self):\n pass", "def cancel_pending_orders(self):\n raise NotImplementedError(\"Broker must implement \\\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given any string input, output should always be a MultiDict.
def test_parse_always_return_a_multidict(text): result = parser.parse(text) assert isinstance(result, MultiDict)
[ "def request_data_to_dict(data):\r\n if not isinstance(data, ImmutableMultiDict):\r\n raise ValueError('Input must be ImmutableMultiDict type.')\r\n\r\n res = {}\r\n for (key, value) in data.to_dict().items():\r\n matches = re.match('(.*)\\[(.*)\\]', key)\r\n if matches:\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Copies contents of a directory to selected target location (also a directory). the specific source file to destination. If the source directory contains a directory, it will copy all the content recursively. Symlinks are preserved (not followed). The destination directory tree will be created if it does not exist.
def copy_recursively(source_directory, destination_directory): # If the source directory does not exists, return if not os.path.isdir(source_directory): return # Iterate over content in the source directory for name in os.listdir(source_directory): src = os.path.join(source_directory, ...
[ "def copy_directory(source_dir, target_dir=None):\n target_dir = source_dir if target_dir is None else target_dir\n source_dir = os.path.abspath(source_dir)\n target_dir = os.path.abspath(target_dir)\n source_basename = os.path.basename(source_dir)\n target_basename = os.path.basename(target_dir)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handles dependencies from selected object. If the object has 'dependencies' method, it will be called to retrieve a set of dependencies to check for.
def handle(self, o, params): if not o: return # Get the class of the object clazz = type(o) for var in [clazz, o]: # Check if a static method or variable 'dependencies' exists dependencies = getattr(var, "dependencies", None) if not dep...
[ "def handle(self, o: Any, params: Map) -> None:\n\n if not o:\n return\n\n # Get the class of the object\n clazz = type(o)\n\n for var in [clazz, o]:\n # Check if a static method or variable 'dependencies' exists\n dependencies = getattr(var, \"dependenci...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize the minimal database needed to run the next tests. For testing inclusion of Knowns 1. A known transcript (id = 1) (dataset 1) with low fracA 2. A known transcript (id = 2) (dataset 2) with high fracA For testing selective exclusion of genomic transcripts and min_dataset and min_count criteria 3. A genomic tr...
def init_mock_db(db_file): # Add reads. Fields that are not relevant for this purpose are set to None known = [(1, 1, 1, "read_1", "dataset_1", None, None, None, None, None, None, None, 0.2, None, None), (2, 1, 2, "read_2", "dataset_2", None, None, None, None, None, None, ...
[ "def test_verify_db_setup(self):\n phage_data = test_db_utils.get_data(test_db_utils.phage_table_query)\n gene_data = test_db_utils.get_data(test_db_utils.gene_table_query)\n trna_data = test_db_utils.get_data(test_db_utils.trna_table_query)\n tmrna_data = test_db_utils.get_data(test_db_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Emits signal after the team is saved.
def team_post_save_callback(sender, instance, **kwargs): # pylint: disable=unused-argument changed_fields = instance.field_tracker.changed() # Don't emit events when we are first creating the team. if not kwargs['created']: for field in changed_fields: if field not in instance.FIELD_BLA...
[ "def emit_save(self):\n self.saveNeeded.emit()", "def save(self):\n self.emit(\"save\", self.data)", "def onSave(self):\n self.triggerEvent(self.EVENT_SAVE_BUTTON_CLICKED)", "def post_save_queue(sender, **kwargs):\n common_signal(kwargs['instance'].manager_id)", "async def save(self,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Serialize and paginate objects in a queryset.
def _serialize_and_paginate(self, pagination_cls, queryset, request, serializer_cls, serializer_ctx): # Django Rest Framework v3 requires that we pass the request # into the serializer's context if the serialize contains # hyperlink fields. serializer_ctx["request"] = request # ...
[ "def paginate_queryset(self, queryset):\n if self.paginator is None:\n return None\n return self.paginator.paginate_queryset(\n queryset, self.request, view=self, count=self.data_count\n )", "def paginate(self, *args, **kwargs):\n result = {}\n result.updat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the list of team ids that should be excluded from the response. Staff can see all private teams. Users should not be able to see teams in private teamsets that they are not a member of.
def _get_private_team_ids_to_exclude(self, course_module): if has_access(self.request.user, 'staff', course_module.id): return set() private_teamset_ids = [ts.teamset_id for ts in course_module.teamsets if ts.is_private_managed] excluded_team_ids = CourseTeam.objects.filter( ...
[ "def _filter_hidden_private_teamsets(user, teamsets, course_module):\n if has_course_staff_privileges(user, course_module.id):\n return teamsets\n private_teamset_ids = [teamset.teamset_id for teamset in course_module.teamsets if teamset.is_private_managed]\n teamset_ids_user_has_access_to = set(\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the queryset used to access the given team.
def get_queryset(self): return CourseTeam.objects.all()
[ "def get_queryset(self):\n team = get_object_or_404(models.Team, pk=self.kwargs.get('pk'))\n\n return team.players.all()", "def get_queryset(self):\n\n userteammates = TeamMate.objects.filter(user=self.request.user)\n teams = []\n for teammateobject in userteammates:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the unit name where the ORA is located for better display naming
def _display_name_for_ora_block(self, block): unit = modulestore().get_item(block.parent) section = modulestore().get_item(unit.parent) return "{section}: {unit}".format( section=section.display_name, unit=unit.display_name )
[ "def unitName(self):\n if self.Unit:\n return self.Unit.Name", "def unit_name(self):\n return '%s_%s' % (\n ctr_models.generate_machine_name(self.pod_id),\n self.name,\n )", "def _display_unit(unit):\r\n name = getattr(unit, 'display_name'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the URL for jumping to a designated XBlock in a course
def _jump_location_for_block(self, course_id, location): return reverse('jump_to', kwargs={'course_id': str(course_id), 'location': str(location)})
[ "def xblock_studio_url(xblock):\r\n if not xblock_has_own_studio_page(xblock):\r\n return None\r\n category = xblock.category\r\n parent_xblock = get_parent_xblock(xblock)\r\n parent_category = parent_xblock.category if parent_xblock else None\r\n if category == 'course':\r\n return rev...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a filtered list of teamsets, removing any private teamsets that a user doesn't have access to. Follows the same logic as `has_specific_teamset_access` but in bulk rather than for one teamset at a time
def _filter_hidden_private_teamsets(user, teamsets, course_module): if has_course_staff_privileges(user, course_module.id): return teamsets private_teamset_ids = [teamset.teamset_id for teamset in course_module.teamsets if teamset.is_private_managed] teamset_ids_user_has_access_to = set( Cou...
[ "def _get_private_team_ids_to_exclude(self, course_module):\n if has_access(self.request.user, 'staff', course_module.id):\n return set()\n\n private_teamset_ids = [ts.teamset_id for ts in course_module.teamsets if ts.is_private_managed]\n excluded_team_ids = CourseTeam.objects.filte...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a list of team topics sorted alphabetically.
def get_alphabetical_topics(course_module): return sorted( course_module.teams_configuration.cleaned_data['team_sets'], key=lambda t: t['name'].lower(), )
[ "def get_topics(self):\r\n return [x[0] for x in get_published_topics()]", "def get_sorted_topics(self, bow):\n return sorted(self.lda[bow], key=lambda x: x[1], reverse=True)", "def get_sorted_topics_courses(self):\n return sorted(self.topics_courses, key=lambda course_topic: course_topic.s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the team with team_id, or throws Http404 if it does not exist.
def get_team(self, team_id): try: return CourseTeam.objects.get(team_id=team_id) except CourseTeam.DoesNotExist: raise Http404 # lint-amnesty, pylint: disable=raise-missing-from
[ "def get_team_by_id(self, team_id):\n return Team.objects.get(id=team_id)", "def getTeam(self, id):\n if self.checkIfExists(Teams, id):\n return self.session.query(Teams).filter_by(id=id)[0]\n else:\n warnings.warn('Team does not exist')", "def get_team(team_id):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the membership for the given user and team, or throws Http404 if it does not exist.
def get_membership(self, username, team): try: return CourseTeamMembership.objects.get(user__username=username, team=team) except CourseTeamMembership.DoesNotExist: raise Http404 # lint-amnesty, pylint: disable=raise-missing-from
[ "def test_returns_200_if_user_team_member(self):\n # Arrange\n # Create a team and add user to it\n test_team = create_canned_team()\n add_user_to_team(\n test_team, self.test_user, TeamMemberFunctions.MEMBER.value, True\n )\n # Assign team to project\n as...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Download CSV with team membership data for given course run.
def get(self, request, **_kwargs): self.check_access() response = HttpResponse(content_type='text/csv') filename = "team-membership_{}_{}_{}.csv".format( self.course.id.org, self.course.id.course, self.course.id.run ) response['Content-Disposition'] = f'attachment; fi...
[ "def csv_courses_download(request):\n response = HttpResponse(content_type=\"text/csv\")\n response['Content-Disposition'] = 'attachment; filename=\"courses.csv\"'\n writer = csv.writer(response)\n writer.writerow(['Course Number','Section Number', 'Course Name', 'Max Number of TAs','Teacher Odin Userna...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Process uploaded CSV to modify team memberships for given course run.
def post(self, request, **_kwargs): self.check_access() inputfile_handle = request.FILES['csv'] team_import_manager = TeamMembershipImportManager(self.course) team_import_manager.set_team_membership_from_csv(inputfile_handle) if team_import_manager.import_succeeded: ...
[ "def test_teams_id_team_data_records_upload_csv_post(self):\n pass", "def ProcessCSV(self, input_file, verbose, output_file):\n row_dict = self.CSVReader(input_file)\n report = []\n output_field_names = row_dict.fieldnames\n output_field_names.append('status')\n\n for row in row_dict:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return the version of pyzmq as a string
def pyzmq_version(): if __revision__: return '@'.join([__version__,__revision__[:6]]) else: return __version__
[ "def zmq_version():\n return \"%i.%i.%i\" % zmq_version_info()", "def pyzmq_version_info():\n return version_info", "def GetVersionString(self):\n return ConvertVersionToString(self.GetVersion())", "def pyzmq_version_info():\n import re\n parts = re.findall('[0-9]+', __version__)\n parts = [...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return the pyzmq version as a tuple of at least three numbers If pyzmq is a development version, `inf` will be appended after the third integer.
def pyzmq_version_info(): return version_info
[ "def pyzmq_version_info():\n import re\n parts = re.findall('[0-9]+', __version__)\n parts = [ int(p) for p in parts ]\n if 'dev' in __version__:\n parts.append(float('inf'))\n return tuple(parts)", "def zmq_version():\n return \"%i.%i.%i\" % zmq_version_info()", "def pyzmq_version():\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return the version of libzmq as a string
def zmq_version(): return "%i.%i.%i" % zmq_version_info()
[ "def pyzmq_version():\n if __revision__:\n return '@'.join([__version__,__revision__[:6]])\n else:\n return __version__", "def pyzmq_version_info():\n return version_info", "def GetVersionString(self):\n return ConvertVersionToString(self.GetVersion())", "def get_version():\n retu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load an account from a keystore file.
def load(cls, path, password=None): with open(path) as f: keystore = json.load(f) if not keys.check_keystore_json(keystore): raise ValueError('Invalid keystore file') return Account(keystore, password, path=path)
[ "def load(path, password):\n with open(path) as f:\n keystore_jsondata = json.load(f)\n privkey = Account._decode_keystore_json(keystore_jsondata, password).hex()\n account = Account.new(key=privkey)\n if \"id\" in keystore_jsondata:\n account.id = keystore_jsondata...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Dump the keystore for later disk storage. The result inherits the entries `'crypto'` and `'version`' from `account.keystore`, and adds `'address'` and `'id'` in accordance with the parameters `'include_address'` and `'include_id`'. If address or id are not known, they are not added, even if requested.
def dump(self, include_address=True, include_id=True): d = {} d['crypto'] = self.keystore['crypto'] d['version'] = self.keystore['version'] if include_address and self.address is not None: d['address'] = encode_hex(self.address) if include_id and self.uuid is not None...
[ "def dump(self, include_address=True, include_id=True):\n d = {}\n d['crypto'] = self.keystore['crypto']\n d['version'] = self.keystore['version']\n if include_address and self.address is not None:\n d['address'] = self.address.encode('hex')\n if include_id and self.uui...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Unlock the account with a password. If the account is already unlocked, nothing happens, even if the password is wrong.
def unlock(self, password): if self.locked: self._privkey = keys.decode_keystore_json(self.keystore, password) self.locked = False self.address # get address such that it stays accessible after a subsequent lock
[ "def unlock_password(self, unlock_password):\n\n self._unlock_password = unlock_password", "def wallet_unlock(timeout, password):\r\n return make_request({\"method\": \"wallet_unlock\",\r\n \"params\": [timeout, password],\r\n \"jsonrpc\": \"2.0\",\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Relock an unlocked account. This method sets `account.privkey` to `None` (unlike `account.address` which is preserved). After calling this method, both `account.privkey` and `account.pubkey` are `None. `account.address` stays unchanged, even if it has been derived from the private key.
def lock(self): self._privkey = None self.locked = True
[ "def unlock_account(self, hash_value):\n raise NotImplementedError(C.make_error('NOT_IMPLEMENTED', method=\"unlock_account\"))", "def account_locked(self, account_locked):\n\n self._account_locked = account_locked", "def unlock(self, password):\n if self.locked:\n self._privkey =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The account's private key or `None` if the account is locked
def privkey(self): if not self.locked: return self._privkey else: return None
[ "def get_private_key(self):\n# _log.debug(\"get_private_key: node_name={}\".format(self.node_name))\n with open(os.path.join(self.runtime_dir, \"private\", \"private.key\"), 'rb') as f:\n return f.read()", "def private_key(self):\n return self._private_key", "def pubkey(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The account's public key or `None` if the account is locked
def pubkey(self): if not self.locked: return privtopub(self.privkey) else: return None
[ "def public_key(self):\n return self._public_key", "def public_key():\n if not Authorizer.__public_key:\n Authorizer.__public_key = download_public_key()\n return Authorizer.__public_key", "def exposed_get_public_key(self):\n return self._privatekey.GetPublicKey()", "def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The account's address or `None` if the address is not stored in the key file and cannot be reconstructed (because the account is locked)
def address(self): if self._address: pass elif 'address' in self.keystore: self._address = decode_hex(self.keystore['address']) elif not self.locked: self._address = keys.privtoaddr(self.privkey) else: return None return self._addre...
[ "def address(self):\n if self._address:\n pass\n elif 'address' in self.keystore:\n self._address = self.keystore['address'].decode('hex')\n elif not self.locked:\n self._address = keys.privtoaddr(self.privkey)\n else:\n return None\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sign a Transaction with the private key of this account. If the account is unlocked, this is equivalent to ``tx.sign(account.privkey)``.
def sign_tx(self, tx): if self.privkey: log.info('signing tx', tx=tx, account=self) tx.sign(self.privkey) else: raise ValueError('Locked account cannot sign tx')
[ "def sign_transaction(self, transaction, prvkey):\n return self.web3.eth.account.sign_transaction(transaction, prvkey)", "def sign_transaction(transaction, priv_key):\n serialized_tx_msg = serialize_transaction(tx=transaction, signed=False)\n return sign_msg(serialized_tx_msg, priv_key)", "def sign...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the address that should be used as coinbase for new blocks. The coinbase address is given by the config field pow.coinbase_hex. If this does not exist or is `None`, the address of the first account is used instead. If there are no accounts, the coinbase is `DEFAULT_COINBASE`.
def coinbase(self): cb_hex = self.app.config.get('pow', {}).get('coinbase_hex') if cb_hex is None: if not self.accounts_with_address: return DEFAULT_COINBASE cb = self.accounts_with_address[0].address else: # [NOTE]: check it! # if ...
[ "def coinbase_transaction(self):\n return self.txns[0]", "def default_address(self):\n if self.addresses:\n return self.addresses[0]", "def _generate_new_address(self) -> str:\n while True:\n address = \"0x\" + \"\".join([str(hex(randint(0, 16)))[-1] for _ in range(20)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add an account. If `store` is true the account will be stored as a key file at the location given by
def add_account(self, account, store=True, include_address=True, include_id=True): log.info('adding account', account=account) if account.uuid is not None: if len([acct for acct in self.accounts if acct.uuid == account.uuid]) > 0: log.error('could not add account (UUID collis...
[ "def add_account(store):\r\n account = input(\"\\nEnter account to save in store: \")\r\n if account in store:\r\n print(\"This account is already in store.\")\r\n else:\r\n password = input(\"Please enter password: \")\r\n store[account] = password\r\n store.sync()\r\n p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a list of accounts whose address is known.
def accounts_with_address(self): return [account for account in self if account.address]
[ "def getaddressesbyaccount(self, account):\n return self.proxy.getaddressesbyaccount(account)", "def get_addresses_by_account(account):\n try:\n stdout = subprocess.check_output([\"litecoin-cli\", \"getaddressesbyaccount\", account])\n addresses = json.loads(stdout.decode())\n except:\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a list of all unlocked accounts.
def unlocked_accounts(self): return [account for account in self if not account.locked]
[ "def list_accounts(self):\n pass", "def accounts(self):\n return self._accounts.values()", "def get_accounts(self):\r\n return self._accounts", "def get_accounts(self) -> list:\n response = self.TradeAPI.makeRequest(\"GET\", \"account/list\")\n response = response.json()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find an account by either its address, its id or its index as string.
def find(self, identifier): try: uuid = UUID(identifier) except ValueError: pass else: return self.get_by_id(uuid.hex) try: index = int(identifier, 10) except ValueError: pass else: if index <= 0: ...
[ "def search_account_name(account_name):\n return Account.find_account(account_name)", "def get_by_address(self, address):\n assert len(address) == 20\n accounts = [account for account in self.accounts if account.address == address]\n if len(accounts) == 0:\n raise KeyError('acco...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get an account by its address. Note that even if an account with the given address exists, it might not be found if it is locked. Also, multiple accounts with the same address may exist, in which case the first one is returned (and a warning is logged).
def get_by_address(self, address): assert len(address) == 20 accounts = [account for account in self.accounts if account.address == address] if len(accounts) == 0: raise KeyError('account with address {} not found'.format(encode_hex(address))) elif len(accounts) > 1: ...
[ "def get_account(self, address):\n return self._get_account(self._call(\"getAccount\", address))", "def __get_account(self, address):\n\t\tfor acct in self.wallet:\n\t\t\tif acct[\"address\"] == address:\n\t\t\t\treturn acct\n\t\traise ValueError(\"The given address does not exist in the bunkr-wallet\")", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Provide app object to this function so it can render to the active screen. offset is tuple of x,y offset between screen and world spaces.
def render(self, app, offset, scale): if self.alive: # make the rectangle call more clear x, y = self.position x_off, y_off = offset # (x, y, width, height) pygame.draw.rect(app.screen, (0, 0, 0), ((x-x_off)*scale, (y-y_off)*scale, scale, scale))
[ "def draw(self, screen, offsets: tuple):\r\n pass", "def world_to_screen(self, xy):\n# world = Vec2d(self.rect.center) - xy\n# return self.abs_screen_center - world\n cx,cy = self.rect.topleft\n x,y = xy\n return Vec2d(x-cx, y-cy)", "def _View (self, offset_y, offset_x,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts radar constraints to loss function.
def _radar_constraints_to_loss_fn(model_object, model_metadata_dict, weight): if weight is None: return None list_of_layer_operation_dicts = model_metadata_dict[ cnn.LAYER_OPERATIONS_KEY] if list_of_layer_operation_dicts is None: return None error_checking.assert_is_greater(w...
[ "def _LossFunction(self,r):\n return (sum([cf * ((1.0 + r[0]) ** ((self.NDays - d)/self.NDays)) for d, cf in self.CashFlows.iteritems()]) + self.InitialValue * (1.0 + r[0]) - self.EndingValue) ** 2.0", "def compute_loss(theta_vector, *args):\n\n psi = args[0]\n circ_depth = args[1]\n num_qbits = a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts minmax constraints to loss function.
def _minmax_constraints_to_loss_fn(model_object, model_metadata_dict, weight): if weight is None: return None if isinstance(model_object.input, list): list_of_input_tensors = model_object.input else: list_of_input_tensors = [model_object.input] return weight * physical_constra...
[ "def minimum_maximum_model():\n inputs = tf.keras.Input(shape=(32, 32, 3,))\n x = tf.keras.layers.Conv2D(32, (3, 3))(inputs)\n x = tf.keras.layers.BatchNormalization(momentum=.3, epsilon=.65)(x, training=False)\n x = tf.minimum(x, .2)\n x = tf.maximum(x, .5)\n x = tf.keras.layers.Conv2D(16, (2, 2)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initializes model input to climatological means. This function uses one mean for each radar field/height pair and each sounding field/height pair, rather than one per field altogether, to create "realistic" vertical profiles. If len(matrix_dimensions) = 3, this function creates initial soundings. If len(matrix_dimensio...
def init_function(matrix_dimensions): initial_matrix = numpy.full(matrix_dimensions, numpy.nan) if len(matrix_dimensions) == 5: if model_metadata_dict[cnn.CONV_2D3D_KEY]: radar_field_names = [radar_utils.REFL_NAME] else: radar_field_names = train...
[ "def create_climo_initializer(model_metadata_dict):\n\n def init_function(dimensions):\n \"\"\"Creates starting point for backwards optimization.\n\n Specifically, sets all predictor values to climatological mean.\n\n :param dimensions: 1-D numpy array with dimensions of predictor matrix.\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Writes mean backwardsoptimized map to Pickle file. This is a mean over many examples, created by PMM (probabilitymatched means). T = number of input tensors to the model
def write_pmm_file( pickle_file_name, list_of_mean_input_matrices, list_of_mean_optimized_matrices, mean_initial_activation, mean_final_activation, threshold_count_matrix, model_file_name, standard_bwo_file_name, pmm_metadata_dict, monte_carlo_dict=None): error_checking.assert_is_st...
[ "def save_exact_samples(expt):\n if isinstance(expt, str):\n expt = get_experiment(expt)\n tr_expt = get_training_expt(expt)\n\n for it in tr_expt.save_after:\n for avg in AVG_VALS:\n print 'Iteration', it, avg\n try:\n rbm = load_rbm(expt, it, avg)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate host labels for given target paths.
def _target_hosts(self, paths): for path in paths: response = self.api_client.get(path) self.assertHttpOK(response) content = json.loads(response.content) (volume_node,) = content["volume"]["volume_nodes"] yield volume_node["host_label"]
[ "def _annotations_to_targets(self, labels):\n roots = ['A','B','C','D','E','F','G']\n natural = zip(roots, [0, 2, 3, 5, 7, 8, 10])\n root_note_map = {}\n for chord, num in natural:\n root_note_map[chord] = num\n root_note_map[chord + '#'] = (num + 1) % 12\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test selecting target by filesystem with valid and invalid filesystem ids.
def test_select_by_filesystem(self): self.create_simple_filesystem(synthetic_host("myserver")) response = self.api_client.get("/api/target/", data={"filesystem_id": self.fs.id}) self.assertHttpOK(response) content = json.loads(response.content) self.assertEqual(3, len(content["o...
[ "def test_fid2path_invalid_fid( testdir ):\n invalid_fids = [ '[0xffffffffff:0xfffff:0x0]', '[0xeeeeeeeeee:0xeeeee:0x0]' ]\n mnt = _getmountpoint( testdir.objects.values()[0][0].path )\n for fid in invalid_fids:\n with pytest.raises( Run_Cmd_Error ) as einfo:\n pylut.fid2path( mnt, fid )\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
(DivideAndConquer, list of numbers, number) > integer Return the index of key if key exists in list num_lst. Otherwise, return 1.
def linear_search(self, num_lst, key): # Running time: O(n) for i in range(len(num_lst)): if num_lst[i] == key: return i return -1
[ "def binary_search(self, num_lst, key):\r\n # Running time: O(log n) with O(n logn) overhead\r\n # get sorted list\r\n num_lst = sorted(num_lst)\r\n \r\n low, high, idx = 0, len(num_lst), -1\r\n \r\n while low < high:\r\n mid = int(math.floor((low+high) / ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
(DivideAndConquer, list of numbers, number) > integer Return the index of key if key exists in list num_lst. Otherwise, return 1.
def binary_search(self, num_lst, key): # Running time: O(log n) with O(n logn) overhead # get sorted list num_lst = sorted(num_lst) low, high, idx = 0, len(num_lst), -1 while low < high: mid = int(math.floor((low+high) / 2.0)) ...
[ "def linear_search(self, num_lst, key):\r\n # Running time: O(n)\r\n for i in range(len(num_lst)):\r\n if num_lst[i] == key:\r\n return i\r\n \r\n return -1", "def sequential_search(lst, key):\r\n for i in range(len(lst)):\r\n if lst[i] == key:\r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
(DivideAndConquer, list of items) > integer Return the number of inversion in the input list.
def get_number_of_inversions_naive(self, lst): # Running time: O(n ** 2) count_inv = 0 for i in range(len(lst)): for j in range(i+1, len(lst)): if lst[i] > lst[j]: count_inv += 1 return count_inv
[ "def count_inversion(li, c):\n \n length = len(li)\n if length < 2:\n return li\n else:\n middle = int(length / 2)\n return count_split_inversion(count_inversion(li[:middle], c), \\\n count_inversion(li[middle:], c), c)", "def countInversions(li...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
(DivideAndConquer, list of items) > list of items, integer Return sorted (nondecreasing order) list and number of inversion in the unsorted list.
def sort_and_get_number_of_inversions(self, lst): n = len(lst) if n == 1: return lst, 0 mid = int(n / 2) first_half_lst = lst[0:mid] second_half_lst = lst[mid:n] sorted_lst_a, inv_a = self.sort_and_get_number_of_inversions(first_half_lst) ...
[ "def sort_and_count_inv(my_list, length):\n #base case:\n if length <= 1:\n return (my_list, 0)\n\n len_first_half = length/2\n len_second_half = length - len_first_half\n first_half = my_list[:len_first_half]\n second_half = my_list[len_first_half:]\n\n sorted_first_half, count_1 = sort...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
(DivideAndConquer, list of items, list of items) > list of items, integer Return a merged list of items from the two given sorted lists, and the number of cross inversions.
def merge_and_get_number_of_inversions(self, sorted_lst_a, sorted_lst_b): a, b, cross_inv_count, out_lst = 0, 0, 0, [] while a < len(sorted_lst_a) and b < len(sorted_lst_b): next_ = min(sorted_lst_a[a], sorted_lst_b[b]) out_lst.append(next_) ...
[ "def mergeAndCount(list0, list1):\r\n newList = []\r\n index0, index1 = 0, 0\r\n len0, len1 = len(list0), len(list1)\r\n\r\n while ((index0 < len0) and (index1 < len1)):\r\n if list0[index0] <= list1[index1]:\r\n newList.append(list0[index0])\r\n index0 = index0 + 1\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
(list of items) > integer Return the total number of inversions in the list.
def get_number_of_inversions_fast(self, lst): [sorted_lst, number_of_inversions] = self.sort_and_get_number_of_inversions(lst) return number_of_inversions
[ "def get_number_of_inversions_naive(self, lst):\r\n # Running time: O(n ** 2)\r\n count_inv = 0\r\n \r\n for i in range(len(lst)):\r\n for j in range(i+1, len(lst)):\r\n if lst[i] > lst[j]:\r\n count_inv += 1\r\n \r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
(DivideAndConquer, list of numbers, list of numbers) > list of numbers Return the number of segments ([starts, ends]) that contains the given points.
def count_segments_naive(self, starts, ends, points): count = [0] * len(points) for i in range(len(points)): for j in range(len(starts)): if starts[j] <= points[i] <= ends[j]: count[i] += 1 return count
[ "def sort_and_count_segments(self, starts, ends, points):\r\n \r\n # Cons: needs lot of memeory space\r\n lst = []\r\n for i in range(len(starts)): \r\n lst.append(range(starts[i], ends[i]+1))\r\n \r\n # store all the items in list\r\n lst_2 = []\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
(DivideAndConquer, list of numbers, list of numbers) > list of numbers Return the number of segments ([starts, ends]) that contains the given points.
def sort_and_count_segments(self, starts, ends, points): # Cons: needs lot of memeory space lst = [] for i in range(len(starts)): lst.append(range(starts[i], ends[i]+1)) # store all the items in list lst_2 = [] for sublist in lst...
[ "def count_segments_naive(self, starts, ends, points):\r\n count = [0] * len(points)\r\n \r\n for i in range(len(points)):\r\n for j in range(len(starts)):\r\n if starts[j] <= points[i] <= ends[j]:\r\n count[i] += 1\r\n \r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The span of the genome covered by this interval, simply ``rightleft``.
def span(self) -> float | int: return self.right - self.left
[ "def span(self):\n return self.right - self.left", "def interval(self):\n return self._ll_tree.get_left(), self._ll_tree.get_right()", "def _rect_right(self):\n\treturn max(self.x, self.x + self.w)", "def get_right(self):\n return self._right", "def rightFrame(self):\n if self.ov...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns True if this node is a sample. This value is derived from the ``flag`` variable.
def is_sample(self): return self.flags & NODE_IS_SAMPLE
[ "def is_sample(sample):\n return type(sample).__name__ == \"Sample\"", "def check_is_sample(cls) -> bool:\n return str(cls.check_package_path()).startswith('plugin/samples/')", "def sample(self, span):\n # type: (Span) -> bool\n if self.sample_rate == 1:\n return True\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the span of this edge, i.e., the right position minus the left position
def span(self): return self.right - self.left
[ "def span(self) -> float | int:\n return self.right - self.left", "def get_rightmost_edge(self):\n return self.offset + sum(self.get_screen_widths())", "def _rect_right(self):\n\treturn max(self.x, self.x + self.w)", "def neighbour_right(self) -> Position:\n return self.end() + self.direc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the set of all the alleles defined at this site
def alleles(self) -> set[str]: return {self.ancestral_state} | {m.derived_state for m in self.mutations}
[ "def __all_Algs_ ( self ) :\n _algs = self.algorithms()\n\n algs = []\n for _a in _algs :\n algs += [ self.algorithm ( _a ) ]\n return algs", "def get_known_alleles(allele_dir):\n known_alleles = {}\n\n alleles = [f for f in os.listdir(allele_dir) if '.f' in f]\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the tree sequence that this tree is from.
def tree_sequence(self): return self._tree_sequence
[ "def seq(self):\n return self._seq", "def sequence(self):\n return self._seqname", "def parsimony(self):\n self.root._forwardParsimony(self.aln) # setup and compute scores for all nodes\n self.root._backwardParsimony(self.aln) # use scores to determine sequences\n return sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Seeks to the first tree in the sequence. This can be called whether the tree is in the null state or not.
def first(self): self._ll_tree.first()
[ "def first(self) -> Optional[MappingTree]:\n self._parent_current_key_idx = 0\n return self._current_node()", "def _subtree_first_position(self, p):\n walk = p\n while self.left(walk) is not None:\n walk = self.left(walk) # keep walking left\n ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Seeks to the last tree in the sequence. This can be called whether the tree is in the null state or not.
def last(self): self._ll_tree.last()
[ "def last(self) -> Optional[MappingTree]:\n if len(self._parent_keys) == 0:\n self._parent_current_key_idx = 0\n else:\n self._parent_current_key_idx = len(self._parent_keys) - 1\n return self._current_node()", "def moveToNodeAfterTree (self):\n \n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the state to represent the tree at the specified index in the parent tree sequence. Negative indexes following the standard Python conventions are allowed, i.e., ``index=1`` will seek to the last tree in the sequence.
def seek_index(self, index): num_trees = self.tree_sequence.num_trees if index < 0: index += num_trees if index < 0 or index >= num_trees: raise IndexError("Index out of bounds") self._ll_tree.seek_index(index)
[ "def set_parent(self, index):\n self.add_parent(self[index])", "def seek_index(self, index):\n num_trees = self.tree_sequence.num_trees\n if index < 0:\n index += num_trees\n if index < 0 or index >= num_trees:\n raise IndexError(\"Index out of bounds\")\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the state to represent the tree that covers the specified position in the parent tree sequence. After a successful return of this method we have ``tree.interval.left`` <= ``position`` < ``tree.interval.right``.
def seek(self, position): if position < 0 or position >= self.tree_sequence.sequence_length: raise ValueError("Position out of bounds") self._ll_tree.seek(position)
[ "def before_insert(self, mapper, connection, node):\n options = self._tree_options\n\n params, session_objs = getattr(node, options.delayed_op_attr)\n target, position = params\n\n self._reload_tree_parameters(connection, node, target)\n\n if target is None:\n # Easy: n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Produce the rank of this tree in the enumeration of all leaflabelled
def rank(self) -> tskit.Rank: return combinatorics.RankTree.from_tsk_tree(self).rank()
[ "def rank(self, value):\n i = 0\n n = len(self._tree)\n rank = 0\n count = 0\n while i < n:\n cur = self._tree[i]\n if value < cur:\n i = 2 * i + 1\n continue\n elif value > cur:\n rank += self._counts[i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }