code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def _add_filters(self, params): <NEW_LINE> <INDENT> if params.get('filters', None): <NEW_LINE> <INDENT> filters = parse_kv_as_dict(params['filters'], True) <NEW_LINE> params['filters'] = filters <NEW_LINE> <DEDENT> return params | Update kwargs if filters are present.
:param params: dict
:return dict | 625941e2435de62698dfe018 |
def output(self,fname=""): <NEW_LINE> <INDENT> out = "" <NEW_LINE> if not fname: <NEW_LINE> <INDENT> hashcode = hash(self)%(10**6) <NEW_LINE> if hashcode < 0: <NEW_LINE> <INDENT> hashcode *= -1 <NEW_LINE> <DEDENT> out = open("puzzle"+str(hashcode), "w") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> out = open(fname, "w... | Writes the puzzle and list of words to a text file
:return: None | 625941e2fbf16365ca6f6595 |
def test_get_extension(self) -> None: <NEW_LINE> <INDENT> given = "example.org" <NEW_LINE> self.checker.subject = given <NEW_LINE> expected = "org" <NEW_LINE> actual = self.checker.get_extension() <NEW_LINE> self.assertEqual(expected, actual) | Tests the method which let us get the extension of the currently
loaded subject. | 625941e2ff9c53063f47c5bc |
def _find(self, curNode, word, tol): <NEW_LINE> <INDENT> if curNode == None: return [] <NEW_LINE> curDist = self.LevenshteinDistance(curNode.getWord(),word) <NEW_LINE> if curDist <= tol: retList = [[curDist,curNode.getWord()]] <NEW_LINE> else: retList = [] <NEW_LINE> for i in xrange(max(curDist - tol,1), curDist + tol)... | This is a "private" function that recursively finds words within the tolerance | 625941e2b57a9660fec33c54 |
def param_projection(self, x_param, y_param, metric): <NEW_LINE> <INDENT> return param_projection(self.estimator.cv_results_, x_param, y_param, metric) | Projects the grid search results onto 2 dimensions.
The wrapped GridSearch object is assumed to be fit already.
The display value is taken as the max over the non-displayed dimensions.
Parameters
----------
x_param : string
The name of the parameter to be visualized on the horizontal axis.
y_param : string
T... | 625941e266673b3332b9245c |
def __init__(self, *args): <NEW_LINE> <INDENT> this = _loris.new_MarkerVector(*args) <NEW_LINE> try: self.this.append(this) <NEW_LINE> except: self.this = this | __init__(self) -> MarkerVector
__init__(self, arg0) -> MarkerVector
__init__(self, size) -> MarkerVector
__init__(self, size, value) -> MarkerVector | 625941e28e05c05ec3eea742 |
def decay(self): <NEW_LINE> <INDENT> self.life[self.cells] -= (time.time() - self.last_update) <NEW_LINE> self.clear_cells(np.sum(self.life < 0, axis=2) > 0) <NEW_LINE> self.update_all_cells() <NEW_LINE> self.life[self.life < 0] = 0 <NEW_LINE> self.last_update = time.time() | Removes expired cells. | 625941e2bf627c535bc1359a |
def toop(op): <NEW_LINE> <INDENT> op= op.lower() <NEW_LINE> if op == 'x' or op == '*': <NEW_LINE> <INDENT> return operator.mul <NEW_LINE> <DEDENT> if op == '+': return operator.add <NEW_LINE> if op == '-': return operator.sub <NEW_LINE> if op == '/': return operator.div | >>> toop('X')
<built-in function mul> | 625941e2c432627299f05013 |
def is_in_menu(self): <NEW_LINE> <INDENT> return self.url.find("/") == -1 | Returns True if URL does not contain a slash so it is not a subpage. | 625941e207d97122c4178c5e |
def filter_0_items(inventory): <NEW_LINE> <INDENT> for k,v in inventory.copy().items(): <NEW_LINE> <INDENT> if inventory[k] == 0: <NEW_LINE> <INDENT> inventory.pop(k) <NEW_LINE> <DEDENT> <DEDENT> return inventory | Removes items that have a value of 0 from a dictionary of inventories
inventory: dictionary with:
key:tring that is the name of the inventory item
value:integer that equals the number of that item currently on hand
Returns: the same inventory_dict with any item that had 0 quantity removed | 625941e232920d7e50b2859e |
def extend(self, config_dict): <NEW_LINE> <INDENT> cfg = FrozenConfigParser( dict_type=self._dict_type, allow_no_value=self._allow_no_value, optionxform=self._config_parser.optionxform, interpolate=self._interpolate) <NEW_LINE> with contextlib.closing(StringIO()) as buf: <NEW_LINE> <INDENT> self._config_parser.write(bu... | Returns a copy of the frozen config self and modify the options
based on config_dict so you can tweak their values | 625941e27047854f462a17d0 |
def detect(self, image, scaleFactor = 1.1, minNeighbors = 5, minSize = (30, 30)): <NEW_LINE> <INDENT> rects = self.faceCascade.detectMultiScale(image, scaleFactor = scaleFactor, minNeighbors = minNeighbors, minSize = minSize) <NEW_LINE> return rects | rects = self.faceCascade.detectMultiScale(image,
scaleFactor = scaleFactor, minNeighbors = minNeighbors,
minSize = minSize, flags = cv2.cv.CV_HAAR_SCALE_IMAGE) | 625941e26fece00bbac2db0d |
def test_registers(self): <NEW_LINE> <INDENT> self.assertEqual(self.ctx.registers.r0.getName(), "r0") <NEW_LINE> self.assertEqual(self.ctx.getParentRegister(self.ctx.registers.r0).getName(), "r0") | Check Arm32 specific registers exists. | 625941e2d6c5a10208144418 |
def recv(): <NEW_LINE> <INDENT> assert active is not None, "Messaging is not setup." <NEW_LINE> LOGGER.debug("Attempting to receive ZMQ message") <NEW_LINE> message = active.recv_json() <NEW_LINE> LOGGER.info("Received ZMQ message: %s", message) <NEW_LINE> return message | Receives the incomming JSON object.
:return: python onject. | 625941e2a934411ee3751a5f |
def get_stockpile_height(volume, core_length): <NEW_LINE> <INDENT> pi_sq_3_vol = 3.0 * pow(pi, 2.0) * volume <NEW_LINE> two_3r = pow(2.0, 1.0 / 3.0) <NEW_LINE> l_cu = pow(core_length, 3.0) <NEW_LINE> inner = (pi_sq_3_vol - 4.0 * l_cu) * volume <NEW_LINE> part = pow(sqrt(3.0) * pi * np.sqrt(np.array(inner, dtype=complex... | Compute the height of a stockpile given the volume and core length
https://www.wolframalpha.com/input/?i=solve+v%3Dpi%2F3*h%5E3%2Bl*h%5E2+for+h
h = (sqrt(3) π sqrt(3 π^2 v^2 - 4 l^3 v) - 2 l^3 + 3 π^2 v)^(1/3)/(2^(1/3) π)
+ (2^(1/3) l^2)/(π (sqrt(3) π sqrt(3 π^2 v^2 - 4 l^3 v) - 2 l^3 + 3 π^2 v)^(1/3)) - l/π
:pa... | 625941e299fddb7c1c9de75a |
def test_context_manager_failure(self): <NEW_LINE> <INDENT> self.cursor.execute("create table t1(n int)") <NEW_LINE> self.cursor.execute("insert into t1 values (1)") <NEW_LINE> self.cnxn.commit() <NEW_LINE> def _fail(): <NEW_LINE> <INDENT> with self.cnxn: <NEW_LINE> <INDENT> self.cursor.execute("insert into t1 values (... | Ensure `with` rolls back if an exception is raised | 625941e291af0d3eaac9bde7 |
def doctest_modules(): <NEW_LINE> <INDENT> yield "openage.util.math" <NEW_LINE> yield "openage.util.strings" <NEW_LINE> yield "openage.util.system" | Yields the names of all Python modules that shall be tested during doctest. | 625941e25fdd1c0f98dc05ff |
def __load_preprocessed(self): <NEW_LINE> <INDENT> with open(self._vocab_file, 'rb') as f: <NEW_LINE> <INDENT> self._vocab = pickle.load(f) <NEW_LINE> <DEDENT> self.vocab_size = len(self._vocab) <NEW_LINE> load_dict = np.load(self._preprocessed_file) <NEW_LINE> self._lengths = load_dict['lengths'] <NEW_LINE> self._tens... | Loads intermediate files, avoiding data preprocess | 625941e244b2445a3393245e |
def set_bytes(self, size): <NEW_LINE> <INDENT> if size is 0: <NEW_LINE> <INDENT> exponent = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> exponent = math.floor(math.log(size, 1024)) <NEW_LINE> <DEDENT> display_size = size / (1024 ** exponent) <NEW_LINE> self._entry.set_value(display_size) <NEW_LINE> self._set_exponen... | Set the current number of displayed bytes | 625941e223e79379d52ee929 |
@app.route('/wikieats/recipe/<recipeid>/reviewrecipe', methods=['POST']) <NEW_LINE> def reviewrecipe(recipeid): <NEW_LINE> <INDENT> conn = psycopg2.connect("dbname=wikieats user=aaronadd password="+conf['aaronadd']+"") <NEW_LINE> cur = conn.cursor() <NEW_LINE> cmd = "INSERT INTO reviews (recipeid,reviewtitle,reviewtext... | Putting the review of the recipe of recipeid into the database | 625941e20c0af96317bb85b2 |
def _find_old_new_index(self, alias): <NEW_LINE> <INDENT> es = self._init_connection() <NEW_LINE> iter_indices = self._iter_padded_index_names() <NEW_LINE> for old_name in iter_indices: <NEW_LINE> <INDENT> if es.indices.exists_alias(name=alias, index=old_name): <NEW_LINE> <INDENT> new_name = next(iter_indices) <NEW_LIN... | use the index after the current alias for the new index/alias | 625941e28e71fb1e9831db72 |
@pytest.mark.redismod <NEW_LINE> @skip_ifmodversion_lt("2.2.0", "search") <NEW_LINE> def test_json_with_multipath(client): <NEW_LINE> <INDENT> definition = IndexDefinition(prefix=["king:"], index_type=IndexType.JSON) <NEW_LINE> client.ft().create_index( (TagField("$..name", as_name="name")), definition=definition ) <NE... | Create definition with IndexType.JSON as index type (ON JSON),
and use json client to test it. | 625941e23317a56b8693a01a |
def list_fonts(directory, extensions): <NEW_LINE> <INDENT> extensions = ["." + ext for ext in extensions] <NEW_LINE> return [os.path.join(dirpath, filename) for dirpath, _, filenames in os.walk(directory) for filename in filenames if Path(filename).suffix.lower() in extensions] | Return a list of all fonts matching any of the extensions, found
recursively under the directory. | 625941e27c178a314d6ef830 |
def fixup_axes(self, second=False): <NEW_LINE> <INDENT> axes_to_change = self.axes <NEW_LINE> if second: <NEW_LINE> <INDENT> if self.ax2 is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> axes_to_change = self.ax2 <NEW_LINE> <DEDENT> <DEDENT> if not self.restrict_to_month: <NEW_LINE> <IND... | Fix up the axes by limiting the amount of items. | 625941e2ec188e330fd5ab62 |
def test_fault_source_full_polygon(self): <NEW_LINE> <INDENT> self.limits = {"polygon": Polygon([Point(14.9, 14.9), Point(14.9, 15.1), Point(15.1, 15.1), Point(15.1, 14.9)]), "upper_depth": 0.0, "lower_depth": 20.0} <NEW_LINE> model1 = RatePolygon(self.limits, [SIMPLE_FAULT], area_discretisation=4.0) <NEW_LINE> model1.... | Tests the rates when the whole fault is inside the polygon | 625941e2377c676e91272571 |
def simple_get(url): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with closing(get(url, stream=True)) as resp: <NEW_LINE> <INDENT> if is_good_response(resp): <NEW_LINE> <INDENT> return resp.content <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> log_error(f"Error: bad response at {url}") <NEW_LINE> return None <NEW_LINE>... | Attempts to get the content at a url by making an HTTP GET request.
If the content-type of response is some kind of HTML/XML, return the
text content, otherwise return None. | 625941e2d6c5a10208144419 |
def videoTags(self, title: '视频标题', filename: "上传后的视频名称", typeid="", desc="", cover="", groupid=1, vfea=""): <NEW_LINE> <INDENT> from urllib.parse import quote <NEW_LINE> url = f'https://member.bilibili.com/x/web/archive/tags?typeid={typeid}&title={quote(title)}&filename=filename&desc={desc}&cover={cover}&groupid={group... | 上传视频后获得推荐标签 | 625941e25166f23b2e1a5524 |
def mark_failed(self, vid, key, tnode): <NEW_LINE> <INDENT> hashtable = self.hashtables[vid] | @func: callback with mark failed vnode | 625941e20a50d4780f667260 |
def pie(request): <NEW_LINE> <INDENT> xdata = ["$1-10,000", "$10,000-25,000", "$25,000-30,000", "$30,000-40,000", "$40,000-55,000", "$55,000-70,000", "$70,000-85,000", "$85,000-100,000", "$100,000-150,000", "$150,000-190,000"] <NEW_LINE> ydata = [ SiteLocation.objects.filter(income__gt=0).filter(income__lte=10000).co... | pieChart page | 625941e23cc13d1c6d3c7743 |
@api.route("/orders/<int:order_id>/comment", methods=["PUT"]) <NEW_LINE> @log_required <NEW_LINE> def save_order_comment(order_id): <NEW_LINE> <INDENT> user_id = g.user_id <NEW_LINE> req_data = request.get_json() <NEW_LINE> comment = req_data.get("comment") <NEW_LINE> if not comment: <NEW_LINE> <INDENT> return jsonify(... | 保存订单评论信息 | 625941e245492302aab5e692 |
def figure2(SE): <NEW_LINE> <INDENT> fontsi = 12 <NEW_LINE> plt.figure(num=None, figsize=(9,3.7), dpi=80, facecolor='w', edgecolor='k') <NEW_LINE> axa = plt.subplot2grid((2,2), (0, 0), rowspan=2) <NEW_LINE> axa.text(55, 0.27, r'(a)', fontsize=fontsi+2, fontweight='bold') <NEW_LINE> responsePlots() <NEW_LINE> axb = plt.... | Makes figure 2 from paper. | 625941e2009cb60464c6377a |
def findUniqFreq(pdffiles): <NEW_LINE> <INDENT> df_single = pd.read_csv(pdffiles[0], skiprows=5, names=['freq', 'db', 'hits'], dtype={'freq':'str'}) <NEW_LINE> freq_u = df_single.freq.unique() <NEW_LINE> for i in range(1,len(pdffiles)): <NEW_LINE> <INDENT> df_single = pd.read_csv(pdffiles[i], skiprows=5, names=['freq'... | Find unique frequency values as *strings*
for quick lookup in calcMegaPDF. | 625941e24428ac0f6e5babc0 |
def _ldap_dn(self): <NEW_LINE> <INDENT> if self._olddn: <NEW_LINE> <INDENT> return self._olddn <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.dn | Return current object dn in LDAP, always returns dn that should be
used for searches, dn can change when setting new parent dn or setting
new value to rdn attributes so we need this | 625941e224f1403a92600f2d |
def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.__dict__.update(**kwargs) <NEW_LINE> self.__iter__ = self.__dict__.__iter__ <NEW_LINE> self.__contains__ = self.__dict__.__contains__ <NEW_LINE> self.iteritems = self.__dict__.iteritems <NEW_LINE> self.iterkeys = self.__dict__.iterkeys <NEW_LINE> self.itervalues = ... | kwargs are turned into attrs | 625941e2a8370b7717052c68 |
def test_Bridge_assertOK_all_bad_values(self): <NEW_LINE> <INDENT> self.bridge.updateFromNetworkStatus(self.networkstatus) <NEW_LINE> self.bridge.updateFromServerDescriptor(self.serverdescriptor) <NEW_LINE> self.bridge.orAddresses.append(('999.999.999.999', -1, 5)) <NEW_LINE> self.assertRaises(bridges.MalformedBridgeIn... | If an orAddress has an IP address of 999.999.999.999 and a port of
-1 and claims to be IPv5, then everything about it is bad and it should
fail all the checks in assertOK(), then a MalformedBridgeInfo should be
raised. | 625941e2ab23a570cc250550 |
def __intraday_cache_files(self, symbol): <NEW_LINE> <INDENT> prefix = self.__intraday_cache_file_prefix(symbol) <NEW_LINE> cached_files = [] <NEW_LINE> cache_folder = StorageFolder(self.cache) <NEW_LINE> for f in cache_folder.files: <NEW_LINE> <INDENT> if f.basename.startswith(prefix): <NEW_LINE> <INDENT> cached_files... | Gets all temporary cache data file for intraday data.
Args:
symbol (str): The symbol of the equity/stock.
Returns:
list: A list of StorageFile objects. | 625941e2566aa707497f492e |
def db_drop_and_create_all(): <NEW_LINE> <INDENT> db.drop_all() <NEW_LINE> db.create_all() | Drop the database tables and starts fresh.
It can be used to initialize a clean database.
!!NOTE you can change the database_filename variable
to have multiple verisons of a database
:return: | 625941e2cc0a2c11143dd25c |
@invoke.task(pre=list(namespace_clean.tasks.values()), default=True) <NEW_LINE> def clean_all(_): <NEW_LINE> <INDENT> pass | Run all clean tasks | 625941e238b623060ff0b1b8 |
def dra818_high_power(enabled): <NEW_LINE> <INDENT> if enabled: <NEW_LINE> <INDENT> GPIO.setup(DRA818_HL, GPIO.IN) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> GPIO.setup(DRA818_HL, GPIO.OUT, initial=GPIO.LOW) | Set the DRA818 to high power by floating the HL input | 625941e2091ae35668667322 |
def test_calendar_association(self): <NEW_LINE> <INDENT> response = self.query_region("stop_points/stop1/stop_schedules?" "calendar=week_cal&from_datetime=20120615T080000") <NEW_LINE> assert "stop_schedules" in response <NEW_LINE> is_valid_stop_schedule(response["stop_schedules"], self.tester, only_time=True) <NEW_LINE... | Same test as departure_board_test.cpp/test_calendar_week
but after jormungandr | 625941e2b7558d58953c52d7 |
def _jumble_label(unique_labels, changed_label): <NEW_LINE> <INDENT> if switch_dict is None: <NEW_LINE> <INDENT> possible_labels = copy.deepcopy(unique_labels) <NEW_LINE> possible_labels_removed = np.asarray([x for x in possible_labels if x != changed_label]) <NEW_LINE> assert possible_labels.shape[0] == possible_label... | Internal helper to add noise to labels | 625941e231939e2706e4d22f |
def call_c(): <NEW_LINE> <INDENT> raise ZeroDivisionError | Used in order to test deep stack trace output. | 625941e231939e2706e4d230 |
def test_deserialize_remote_exception_cannot_recreate(self): <NEW_LINE> <INDENT> self.config(allowed_rpc_exception_modules=[self.__class__.__module__]) <NEW_LINE> failure = { 'class': 'FakeIDontExistException', 'module': self.__class__.__module__, 'tb': ['raise FakeIDontExistException'], } <NEW_LINE> serialized = jsonu... | Ensure a RemoteError is returned on initialization failure.
If an exception cannot be recreated with it's original class then a
RemoteError with the exception informations should still be returned. | 625941e2cb5e8a47e48b7e70 |
def get_income(start_time, end_time): <NEW_LINE> <INDENT> orders = OrderLog.objects.filter( created_at__gte=start_time, created_at__lte=end_time, refunded_at=None ) <NEW_LINE> income = Decimal('0.00') <NEW_LINE> for order in orders: <NEW_LINE> <INDENT> income += order.cash_spent <NEW_LINE> <DEDENT> return income | 获取一段时间内的新增收入 | 625941e2379a373c97cfaf12 |
def getInstalledOfferings(self): <NEW_LINE> <INDENT> d = {} <NEW_LINE> installed = self._siteStore.query(InstalledOffering) <NEW_LINE> for installation in installed: <NEW_LINE> <INDENT> offering = installation.getOffering() <NEW_LINE> if offering is not None: <NEW_LINE> <INDENT> d[offering.name] = offering <NEW_LINE> <... | Return a mapping from the name of each L{InstalledOffering} in
C{self._siteStore} to the corresponding L{IOffering} plugins. | 625941e263d6d428bbe448bc |
def pathChecker(path): <NEW_LINE> <INDENT> if os.path.exists(path): <NEW_LINE> <INDENT> os.remove(path) | Checks if a file path exists, if yes it removes it | 625941e27d847024c06be68b |
@cli.command() <NEW_LINE> @click.argument('master-site', type=click.Path()) <NEW_LINE> @click.argument('sites', type=click.Path(), nargs=-1) <NEW_LINE> @click.option('-u', '--unify-sites', is_flag=True, help=UNIFY_HELP) <NEW_LINE> def run(master_site, sites, unify_sites): <NEW_LINE> <INDENT> merge.run_merge(master_site... | Executes the site merging.
MASTER_SITE: base site of the merge.
SITES: sites to merge into the base site. | 625941e2187af65679ca54ec |
def serialize_numpy(self, buff, numpy): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _x = self <NEW_LINE> buff.write(_struct_3I.pack(_x.header.seq, _x.header.stamp.secs, _x.header.stamp.nsecs)) <NEW_LINE> _x = self.header.frame_id <NEW_LINE> length = len(_x) <NEW_LINE> if python3 or type(_x) == unicode: <NEW_LINE> <IND... | serialize message with numpy array types into buffer
:param buff: buffer, ``StringIO``
:param numpy: numpy python module | 625941e2f548e778e58cd94b |
@contextmanager <NEW_LINE> def atomic_writing(path): <NEW_LINE> <INDENT> fileobj = NamedTemporaryFile( prefix=os.path.abspath(path) + "-tmp-", mode="w", delete=False ) <NEW_LINE> try: <NEW_LINE> <INDENT> with fileobj as f: <NEW_LINE> <INDENT> yield f <NEW_LINE> <DEDENT> os.replace(fileobj.name, path) <NEW_LINE> <DEDENT... | Write temp file before copying it into place
Avoids a partial file ever being present in `path`,
which could cause traefik to load a partial routing table. | 625941e2dd821e528d63b571 |
def set_events(self): <NEW_LINE> <INDENT> if not self.stop_event.is_set(): <NEW_LINE> <INDENT> self.stop_event.set() | Stop all schedules | 625941e24e696a04525c9818 |
def apoptosis(monolayer, manager, **kwargs): <NEW_LINE> <INDENT> apoptosis_spec = default_apoptosis_spec <NEW_LINE> apoptosis_spec.update(**kwargs) <NEW_LINE> cell = apoptosis_spec["cell_id"] <NEW_LINE> if cell == -1: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> done = False <NEW_LINE> cell_to_face = monolayer.get_or... | Apoptotic behavior
Parameters
----------
monolayer : a :cass:`Monolayer` object
manager : a :class:`EventManager` object
Optional Parameters
-------------------
cell_id : int
id of the apoptotic cell
contract_rate : float, default 2.
critical_area : float, default 1e-2,
shrink_rate : float, default 0.4,
critical_v... | 625941e28e05c05ec3eea743 |
def __init__(self, layer, checkpoint_loader): <NEW_LINE> <INDENT> self.layer = layer <NEW_LINE> self.prefix_param_name = layer.get_absolute_name_scope_prefix() <NEW_LINE> self.checkpoint_param_names = [] <NEW_LINE> prefix = self.prefix_param_name <NEW_LINE> for name in list(checkpoint_loader.var_ckpt_names): <NEW_LINE>... | :param LayerBase layer:
:param CustomCheckpointLoader checkpoint_loader: | 625941e263b5f9789fde74b2 |
def tokenize_doc(): <NEW_LINE> <INDENT> tokenizer = nltk.tokenize.RegexpTokenizer(r'\w+') <NEW_LINE> new_docs = [] <NEW_LINE> for doc in documents: <NEW_LINE> <INDENT> tokens = [] <NEW_LINE> ids = [] <NEW_LINE> for tweet in doc['text_array']: <NEW_LINE> <INDENT> t_tokens = tokenizer.tokenize((tweet[0].lower())) <NEW_LI... | Tokenizes the raw text of each document | 625941e24e4d5625662d479e |
def __init__(self, path, fam): <NEW_LINE> <INDENT> Bcfg2.Server.Plugin.EntrySet.__init__(self, os.path.basename(self.certpath), path, PulpCertificateData, "UTF-8") <NEW_LINE> self.metadata = dict(owner='root', group='root', mode='0644', secontext='__default__', important='true', sensitive='true', paranoid=self.metadata... | :param path: The path to the directory where Pulp consumer
certificates will be stored
:type path: string | 625941e2bf627c535bc1359b |
def __init__(self, jsondict=None, strict=True, **kwargs): <NEW_LINE> <INDENT> self.adjustment = None <NEW_LINE> self.adjustmentReason = None <NEW_LINE> self.amount = None <NEW_LINE> self.date = None <NEW_LINE> self.identifier = None <NEW_LINE> self.type = None <NEW_LINE> super(ExplanationOfBenefitPayment, self).__init_... | Initialize all valid properties.
:raises: FHIRValidationError on validation errors, unless strict is False
:param dict jsondict: A JSON dictionary to use for initialization
:param bool strict: If True (the default), invalid variables will raise a TypeError | 625941e238b623060ff0b1b9 |
def find(self, x0, y0, x1, y1): <NEW_LINE> <INDENT> game_map = self._map <NEW_LINE> adjacent = False <NEW_LINE> if game_map[x1, y1] in self.obstacle_tiles: <NEW_LINE> <INDENT> adjacent = True <NEW_LINE> <DEDENT> start = (x0, y0, 0, None) <NEW_LINE> queue = HeapQueue() <NEW_LINE> visited = [(x0, y0)] <NEW_LINE> queue.pu... | Find a path between (x0, y0) and (x1, y1).
Args:
x0 (int): initial position in X.
y0 (int): initial position in Y.
x1 (int): goal position in X.
y1 (int): goal position in Y.
Returns:
(list) if the path has been found, e.g. ``[(0, 1), (0, 2), ...]``.
Notice that, it does not include the init... | 625941e2099cdd3c635f1025 |
@pytest.mark.parametrize( "query", [ ( "HGNC:123", "MONDO:1", { "id": "HGNC:123-biolink:related_to-MONDO:1", "subject": "A:123", "object": "X:1", "predicate": "biolink:related_to", }, True, ), ( "HGNC:123", "MONDO:1", { "id": "HGNC:123-biolink:related_to-MONDO:1", "subject": "A:123", "object": "X:1", "predicate": "rela... | Test validate_edge_predicate in Validator. | 625941e24e696a04525c9819 |
def p_static_constructor_declaration(p): <NEW_LINE> <INDENT> pass | static_constructor_declaration : attributes_opt static_constructor_modifiers identifier L_PAREN R_PAREN static_constructor_body
| static_constructor_modifiers
| extern_opt STATIC
| STATIC extern_opt | 625941e23d592f4c4ed1d42f |
def test_users_listed(self): <NEW_LINE> <INDENT> url = reverse("admin:core_user_changelist") <NEW_LINE> res = self.client.get(url, follow=True) <NEW_LINE> print(f'Response is: {res}') <NEW_LINE> self.assertContains(res, self.user.name) <NEW_LINE> self.assertContains(res, self.user.email) | Test that user are listed in user function | 625941e2cad5886f8bd273a5 |
def apply_to(self, repository): <NEW_LINE> <INDENT> repository.add_amount(self.__account, -self.__amount) | :type repository: TransactionRepository | 625941e2b7558d58953c52d8 |
def on_clear(self, evt=None): <NEW_LINE> <INDENT> if evt: evt.Skip() <NEW_LINE> if self.select(None): <NEW_LINE> <INDENT> my_evt = ClearEvent(self.GetId()) <NEW_LINE> my_evt.SetEventObject(self) <NEW_LINE> wx.PostEvent(self, my_evt) | Clear editor with user verification if unsaved changes | 625941e2a05bb46b383ecbea |
def create_mouse_up_event(self, element_id): <NEW_LINE> <INDENT> return self.sf_api_commands.do_flex_mouse_up(element_id) | Dispatches a MouseEvent.MOUSE_UP event to element
Args:
element_id: target element | 625941e21f5feb6acb0c4f16 |
def __len__(self): <NEW_LINE> <INDENT> return int(np.floor(len(self.X) / self.batch_size)) | Denotes the number of batches per epoch | 625941e267a9b606de4a8283 |
def __getitem__(self, index): <NEW_LINE> <INDENT> wfm = self.waveform <NEW_LINE> return wfm[index] | Return waveform at index. | 625941e2442bda511e8be7df |
def __init__(self, response): <NEW_LINE> <INDENT> self.error_message = response.reason or '' <NEW_LINE> if response.content: <NEW_LINE> <INDENT> content = response.json() <NEW_LINE> self.error_message = content.get('message', self.error_message) <NEW_LINE> <DEDENT> self.status_code = response.status_code <NEW_LINE> sup... | :param :class:`requests.Response` response: HTTP response | 625941e2460517430c394548 |
def browse_to(self, *args, **kwargs): <NEW_LINE> <INDENT> if kwargs.get("browser"): <NEW_LINE> <INDENT> browser = kwargs.get("browser") <NEW_LINE> del kwargs["browser"] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> browser = self.browser <NEW_LINE> <DEDENT> if args: <NEW_LINE> <INDENT> assert "dest_url" not in kwargs <... | When testing, we have to make sure that the page has loaded before
testing the resulting page.
Three ways to specify the url to browse to:
1. First positional argument
2. dest_url keyword argument
3. reverse lookup of url_name argument. | 625941e20a50d4780f667261 |
def get_node_for_mac(mac): <NEW_LINE> <INDENT> if not settings.ALLOW_UNSAFE_METADATA_ACCESS: <NEW_LINE> <INDENT> raise PermissionDenied( "Unauthenticated metadata access is not allowed on this MAAS.") <NEW_LINE> <DEDENT> match = get_one(MACAddress.objects.filter(mac_address=mac)) <NEW_LINE> if match is None: <NEW_LINE>... | Identify node being queried based on its MAC address.
This form of access is a security hazard, and thus it is permitted only
on development systems where ALLOW_UNSAFE_METADATA_ACCESS is enabled. | 625941e2b57a9660fec33c55 |
def GetNAIntI(self, *args): <NEW_LINE> <INDENT> return _snap.TNEANet_GetNAIntI(self, *args) | GetNAIntI(TNEANet self, TStr attr, int const & NId) -> TNEANet::TAIntI
Parameters:
attr: TStr const &
NId: int const & | 625941e245492302aab5e693 |
def cmsNametoCE(self, cmsName): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> sitenames = filter(lambda x: x['type']=='cms' and x['alias']==cmsName, self._sitenames())[0] <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> siteresources = filter(lambda x: x['site_name']==sitenames['s... | Convert CMS name to list of CEs | 625941e2f7d966606f6aa3d5 |
def match(): <NEW_LINE> <INDENT> process = Process() <NEW_LINE> process.match_car_source() | 匹配车源数据 | 625941e215baa723493c4344 |
def storage_node_update(context, storage_id, values): <NEW_LINE> <INDENT> return IMPL.storage_node_update(context, storage_id, values) | Updates an existing Storage Node in the Database. | 625941e25f7d997b87174e67 |
def start_encryption(self): <NEW_LINE> <INDENT> self._logger.info('Start to encrypt instance %s' % self._instance.id) <NEW_LINE> for device in self._instance.block_device_mappings: <NEW_LINE> <INDENT> if 'Ebs' not in device: <NEW_LINE> <INDENT> msg = '%s: Skip %s not an EBS device' % (self._instance.id, device['VolumeI... | Launch encryption process | 625941e221a7993f00bc80c2 |
def posiciona(self, x, y): <NEW_LINE> <INDENT> self.x = x <NEW_LINE> self.y = y - (self.imatge.get_height()/2) | Posiciona el jugador en les coordenades
:param x: Coordenada X
:param y: Coordenada Y
:return: | 625941e2627d3e7fe0d6921d |
@graphic_templates.route('/<slug>/css/<filename>.less') <NEW_LINE> def _templates_less(slug, filename): <NEW_LINE> <INDENT> template_path = '%s/%s' % (app_config.TEMPLATES_PATH, slug) <NEW_LINE> less_path = '%s/css/%s.less' % (template_path, filename) <NEW_LINE> base_less_path = '%s/_base/css/base.less' % app_config.TE... | Compiles LESS for a graphic. | 625941e285dfad0860c3b228 |
def process_IN_CREATE(self, event): <NEW_LINE> <INDENT> if (event.mask & pyinotify.IN_ISDIR): <NEW_LINE> <INDENT> self._watched_dirs.update(self._watchManager.add_watch(event.pathname, self._tmask)) <NEW_LINE> <DEDENT> if self._cmd_filename and os.path.abspath( event.pathname) != self._cmd_filename: <NEW_LINE> <INDENT>... | On closing after linking. | 625941e2bd1bec0571d909fb |
def testNoOpUpdate(self): <NEW_LINE> <INDENT> follower = self._RunAsync(Follower.Query, self._client, self._user.user_id, self._new_vp_id, None) <NEW_LINE> self._tester.UpdateFollower(self._cookie, self._new_vp_id, labels=list(follower.labels)) <NEW_LINE> self._tester.UpdateFollower(self._cookie, self._new_vp_id, label... | Update follower attribute to same value as it had before. | 625941e299cbb53fe6792fb2 |
def arrayPairSum(self, nums): <NEW_LINE> <INDENT> count = [0] * 20001 <NEW_LINE> for num in nums: <NEW_LINE> <INDENT> count[num + 10000] += 1 <NEW_LINE> <DEDENT> sum = 0 <NEW_LINE> odd = True <NEW_LINE> for i in range(len(count)): <NEW_LINE> <INDENT> while count[i] > 0: <NEW_LINE> <INDENT> if odd: <NEW_LINE> <INDENT> s... | :type nums: List[int]
:rtype: int | 625941e2e8904600ed9f22fe |
def match(self, passage_encodes, question_encodes, p_length, q_length): <NEW_LINE> <INDENT> with tf.variable_scope('match_lstm', reuse=tf.AUTO_REUSE): <NEW_LINE> <INDENT> cell_fw = MatchLSTMAttnCell(self.hidden_size, question_encodes) <NEW_LINE> cell_bw = MatchLSTMAttnCell(self.hidden_size, question_encodes) <NEW_LINE>... | Match the passage_encodes with question_encodes using Match-LSTM algorithm | 625941e2a05bb46b383ecbeb |
def bee_costumes(self): <NEW_LINE> <INDENT> result = [] <NEW_LINE> image_list = ['bee1.gif', 'bee2.gif', 'bee3.gif', 'bee4.gif'] <NEW_LINE> for image in image_list: <NEW_LINE> <INDENT> bee_costume = PhotoImage(file = image) <NEW_LINE> bee_sample = bee_costume.subsample(5, 5) <NEW_LINE> result.append(bee_sample) <NEW_LI... | creates the costume list | 625941e28a43f66fc4b5442d |
def add_cluster_role_env(parser): <NEW_LINE> <INDENT> parser.add_argument( 'cluster/[role]/[env]', help='Topologies location', type=str, metavar='CLUSTER/[ROLE]/[ENV]') <NEW_LINE> return parser | add argument that specifies topologies location | 625941e2046cf37aa974d110 |
def limit_sequence_gap(size=0): <NEW_LINE> <INDENT> gap_size = size + 1 <NEW_LINE> def inner(typ, idx, depth, *all_prev): <NEW_LINE> <INDENT> ancestor_markers = ancestors(all_prev) <NEW_LINE> if depth < len(ancestor_markers): <NEW_LINE> <INDENT> prev_typ, prev_idx, prev_depth = ancestor_markers[depth] <NEW_LINE> types ... | We've loosened the rules around sequences of paragraphs so that
paragraphs can be skipped. This allows arbitrary tightening of that rule,
effectively allowing gaps of a limited size | 625941e2fbf16365ca6f6598 |
def check_prerequisites(self, build): <NEW_LINE> <INDENT> if self.cached_check is None: <NEW_LINE> <INDENT> log.debug("PREREQ check for %s" % self.name) <NEW_LINE> self.cached_check = self.cached_check_prerequisites(build) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> log.debug("PREREQ check for %s (cached)" % self.nam... | Check prerequisites
The check should cover all dependencies needed for the extension to
be built and run. The method can do the following:
- return a false value: the extension will be built
- return a true value: the extension will be skipped. This is useful
for optional extensions
- raise an exception. This is us... | 625941e291af0d3eaac9bde9 |
def test_esm_flatfile_parser(self): <NEW_LINE> <INDENT> parser = ESMFlatfileParser.autobuild("000", "ESM Test", self.db_file, self.datafile) <NEW_LINE> with open(os.path.join(self.db_file, "metadatafile.pkl"), "rb") as f: <NEW_LINE> <INDENT> db = pickle.load(f) <NEW_LINE> <DEDENT> self.assertEqual(len(db), 100) <NEW_LI... | Tests the parsing of the ESM flatfile | 625941e2c4546d3d9de72e03 |
def _get_stock_all_tables(self, baseurl_str, pause_single_table=0.01): <NEW_LINE> <INDENT> p = 1 <NEW_LINE> table_list = [] <NEW_LINE> while p < 200: <NEW_LINE> <INDENT> url = baseurl_str.format(page_num=p) <NEW_LINE> df_table = self._get_stock_single_table(url) <NEW_LINE> if len(df_table) == 0: <NEW_LINE> <INDENT> bre... | 複数のダウンロードページから順次テーブルデータをダウンロードしてdfにし、結合してから返す。
- baseurl_str: str, yahooファイナンス株価データページのurl(pege_numのみフォーマットされていない状態)
- pause_single_table: int, page_numを1足すときの待ち時間
Returns: pandas dataframe, 1つの銘柄のデータ。複数ページのデータを全て結合済み。 | 625941e25fdd1c0f98dc0601 |
def _plan(self): <NEW_LINE> <INDENT> self._mvgroup.clear_pose_targets() <NEW_LINE> pose_target = self._set_sample_pose() <NEW_LINE> self._mvgroup.set_pose_target(pose_target) <NEW_LINE> plan = self._mvgroup.plan() <NEW_LINE> rospy.loginfo(' plan: '.format(plan)) <NEW_LINE> return plan | Run `clear_pose_targets` at the beginning.
@rtype: RobotTrajectory http://docs.ros.org/api/moveit_msgs/html/msg/RobotTrajectory.html | 625941e223e79379d52ee92b |
def wrapper(string, tty_only=True): <NEW_LINE> <INDENT> if tty_only and not sys.stdout.isatty(): <NEW_LINE> <INDENT> return string <NEW_LINE> <DEDENT> return '{color}{string}{reset}'.format( color=color, string=string, reset=reset, ) | Return colorized string.
Takes an optional tty_only argument (defaults to True). When tty_only
is set, colors will only be applied if stdout is a tty. This is useful
when you don't want color output (e.g. if redirecting to a file). | 625941e2cdde0d52a9e53402 |
@app.route('/statistics/popular') <NEW_LINE> def stats_popular(): <NEW_LINE> <INDENT> info = {'header': 'Popular Top-10', 'text': 'Below is the list of 10 most visited snapshots among public ones.'} <NEW_LINE> return __top_stats('visits', 0, info=info) | Route to a view page of 10 most visited snapshots among public ones. | 625941e2be7bc26dc91cd9c5 |
def __init__(self, feature_matrix=None): <NEW_LINE> <INDENT> if feature_matrix is None: <NEW_LINE> <INDENT> self.N = 0 <NEW_LINE> self.mean = 0 <NEW_LINE> self.S1 = 0 <NEW_LINE> self.S2 = 0 <NEW_LINE> self.std = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.mean = numpy.mean(feature_matrix, axis=0) <NEW_LINE> se... | __init__ method.
Parameters
----------
feature_matrix : numpy.ndarray [shape=(frames, number of feature values)] or None
Feature matrix to be used in the initialization | 625941e2b830903b967e9cd4 |
def save(self): <NEW_LINE> <INDENT> result = IMProvNode("data") <NEW_LINE> result.attrs['version'] = '2' <NEW_LINE> dbs = IMProvNode("dbs") <NEW_LINE> dbs.attrs['name'] = self.dbs <NEW_LINE> dbs.attrs['dls'] = 'dbs' <NEW_LINE> result.addNode(dbs) <NEW_LINE> for dataset in self.datasetPaths.values(): <NEW_LINE> <INDENT>... | _save_
serialise object into PhEDEx injection XML format | 625941e255399d3f05588a83 |
def set_values(self, values): <NEW_LINE> <INDENT> self.values = values | Set spreadsheet cell values.
:param values: values to set
:type values: container, e.g. list | 625941e2379a373c97cfaf13 |
def getElementsByTag(self, tagName: str) -> List[Tuple[int, str]]: <NEW_LINE> <INDENT> nonN: List[str] = [] <NEW_LINE> with open(self.fileName, "r+") as f: <NEW_LINE> <INDENT> html: List[str] = f.readlines() <NEW_LINE> for line in html: <NEW_LINE> <INDENT> nonN.append(line.replace("\n", "")) <NEW_LINE> <DEDENT> <DEDENT... | Returns all matching tags from an HTML/XML document | 625941e20383005118ecf9ae |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, V2beta1MPIJobList): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.to_dict() == other.to_dict() | Returns true if both objects are equal | 625941e271ff763f4b549a5f |
def build_state(self): <NEW_LINE> <INDENT> waypoint = self.planner.next_waypoint() <NEW_LINE> inputs = self.env.sense(self) <NEW_LINE> deadline = self.env.get_deadline(self) <NEW_LINE> state = tuple([waypoint] + [i for i in inputs.values()]) <NEW_LINE> return state | The build_state function is called when the agent requests data from the
environment. The next waypoint, the intersection inputs, and the deadline
are all features available to the agent. | 625941e245492302aab5e694 |
def is_set_max_noutput_items(self): <NEW_LINE> <INDENT> return _filter_swig.pfb_arb_resampler_ccc_sptr_is_set_max_noutput_items(self) | is_set_max_noutput_items(pfb_arb_resampler_ccc_sptr self) -> bool | 625941e20a366e3fb873ebea |
def getkey(self): <NEW_LINE> <INDENT> if self.stack: <NEW_LINE> <INDENT> page, ix = self.stack[-1] <NEW_LINE> return unpackkey(page.branches[ix].key) | Returns the key tuple for the current item | 625941e263d6d428bbe448bd |
def request(host, path, bearer_token, url_params=None): <NEW_LINE> <INDENT> url_params = url_params or {} <NEW_LINE> url = '{0}{1}'.format(host, quote(path.encode('utf8'))) <NEW_LINE> headers = { 'Authorization': 'Bearer %s' % bearer_token, } <NEW_LINE> print(u'Querying {0} ...'.format(url)) <NEW_LINE> response = reque... | Given a bearer token, send a GET request to the API.
Args:
host (str): The domain host of the API.
path (str): The path of the API after the domain.
bearer_token (str): OAuth bearer token, obtained using client_id and client_secret.
url_params (dict): An optional set of query parameters in the request.
... | 625941e24f6381625f114e08 |
def cache_expires(self, seconds): <NEW_LINE> <INDENT> self._response.cache_expires(seconds) | Set the response to expire in the specified seconds. | 625941e2851cf427c661a8d9 |
def _check_accessed_members(self, node, accessed): <NEW_LINE> <INDENT> for attr, nodes in accessed.iteritems(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> node.local_attr(attr) <NEW_LINE> continue <NEW_LINE> <DEDENT> except astroid.NotFoundError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> n... | check that accessed members are defined | 625941e297e22403b379d368 |
def encode_categorical_column(dataframe, columns, suffix='_enc'): <NEW_LINE> <INDENT> encoder = LabelEncoder() <NEW_LINE> for col in columns: <NEW_LINE> <INDENT> dataframe[col + suffix] = encoder.fit_transform(dataframe[col]) <NEW_LINE> <DEDENT> return dataframe | Encodes a column of the dataframe
Attributes:
- dataframe: (pandas.DataFrame)
- column: (list[string]) name/s of the column/s to encode
- suffix: (string, default='_enc') suffix to add at the name of the original column for the encoded one | 625941e224f1403a92600f2f |
def __init__(self): <NEW_LINE> <INDENT> self.StartTime = None <NEW_LINE> self.Type = None <NEW_LINE> self.EndTime = None <NEW_LINE> self.ID = None <NEW_LINE> self.ExtSecond = None <NEW_LINE> self.Engine = None <NEW_LINE> self.Isp = None <NEW_LINE> self.From = None <NEW_LINE> self.Level = None <NEW_LINE> self.Brand = No... | :param StartTime: 开始时间
:type StartTime: int
:param Type: allcount:性能视图,day:14天数据,condition:条件列表,ckuv:获取uv趋势,ckpv:获取pv趋势,nettype/version/platform/isp/region/device/browser/ext1/ext2/ext3/ret/status/from/url/env/:网络平台视图/Version视图/设备视图/ISP视图/地区视图/浏览器视图/ext1视图等等
:type Type: str
:param EndTime: 结束时间
:type EndTime: int
:para... | 625941e21d351010ab855ee8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.