code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def characterReplacement(self, s: str, k: int) -> int: <NEW_LINE> <INDENT> first, last = 0, 0 <NEW_LINE> L = len(s) <NEW_LINE> counter = Counter() <NEW_LINE> output = 0 <NEW_LINE> for last in range(L): <NEW_LINE> <INDENT> c = s[last] <NEW_LINE> counter[c] += 1 <NEW_LINE> windowsize = last - first + 1 <NEW_LINE> many = ... | AAABBBBBC -> 9 - 5 = 4 B, 5 | 625941ee50812a4eaa59c87c |
def get_xpath(url, xpath): <NEW_LINE> <INDENT> sleep(0.075) <NEW_LINE> htmlparser = etree.HTMLParser() <NEW_LINE> page = etree.parse(url, htmlparser) <NEW_LINE> return page.xpath(xpath) | htmlparser = html5lib.HTMLParser( tree=html5lib.treebuilders.getTreeBuilder("lxml"), namespaceHTMLElements=False) | 625941ee566aa707497f4ac1 |
def __getattr__(self, stat): <NEW_LINE> <INDENT> log.error("Attribute %s did not exist" % stat) <NEW_LINE> return "" | Catch message if attribute did not exist | 625941eed4950a0f3b08c8a7 |
def detect_enc(byte_sring): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ret = cchardet.detect(byte_sring) <NEW_LINE> <DEDENT> except NameError: <NEW_LINE> <INDENT> ret = None <NEW_LINE> <DEDENT> if not ret or 'encoding' not in ret or not ret['encoding'] or ret['encoding'] == '': <NEW_LINE> <INDENT> try: <NE... | Try to detect a encoding.
It uses the ``cchardet`` and ``chardet`` modules to detect the encoding.
If none of them are installed, it returns None.
Args:
byte_string (str | bytes): the byte string to detect.
Return:
dict: with at least the 'encoding' informed as returned by
:py:func:`cchardet.detect` ... | 625941ee4d74a7450ccd4726 |
def init_field(self): <NEW_LINE> <INDENT> self.game_field = [] <NEW_LINE> for y in self.ys: <NEW_LINE> <INDENT> game_field_row = [] <NEW_LINE> for x in self.xs: <NEW_LINE> <INDENT> is_my_square = self.is_mine(x, y) <NEW_LINE> game_square = GameSquare(self, owner=is_my_square, command=lambda x_=x, y_=y: self.on_click(x_... | Initialize the playing field | 625941eec432627299f051aa |
def espera_bch(entrada, autom): <NEW_LINE> <INDENT> autom.buffer.append(entrada) <NEW_LINE> return ESTADOS['ESPERA_BCL'] | Espera BCH | 625941ee167d2b6e312190f5 |
def update_vnfr_after_scale(self, func_id): <NEW_LINE> <INDENT> error = None <NEW_LINE> vnfr = self.functions[func_id]['vnfr'] <NEW_LINE> vnfr_id = func_id <NEW_LINE> old_version = int(vnfr['version']) <NEW_LINE> cur_version = old_version + 1 <NEW_LINE> vnfr['version'] = str(cur_version) <NEW_LINE> vnfr["id"] = vnfr_id... | This method updates the vnfr after a vnf scale event | 625941eef8510a7c17cf9c61 |
def rm(path): <NEW_LINE> <INDENT> ssh.run('rm ' + path) | Remove a file given by the path. | 625941eec432627299f051ab |
def __call__(self, x, y, vx, vy, **kwargs): <NEW_LINE> <INDENT> guesskeys = self.guess() <NEW_LINE> params = self.params.copy() <NEW_LINE> for key in self.params.keys(): <NEW_LINE> <INDENT> if key in kwargs.keys() and key is not "XY": <NEW_LINE> <INDENT> params[key].value = kwargs[key] <NEW_LINE> <DEDENT> else: <NEW_LI... | The call function will fit the 2D vector field [vx, vy]
to the fit function specified in the object.
fig,ax=plt.subplots()
qmag=np.hypot(qxs[w],qys[w])
ax.scatter(qmag,vecmags[w]) Need to specify components and vectors.
Parameters
---------
x : 2D np.ndarray
... | 625941eee8904600ed9f2497 |
def delete(self, user_id): <NEW_LINE> <INDENT> query = 'DELETE FROM execution WHERE user_id=%s' <NEW_LINE> self.cursor.execute(query, (user_id,)) <NEW_LINE> query = 'DELETE FROM "user" WHERE id = %s' <NEW_LINE> self.cursor.execute(query, (user_id,)) <NEW_LINE> self.sql_manager.commit() | Delete a user from the state. | 625941ee2eb69b55b151ce18 |
def register_dll(search_paths=None): <NEW_LINE> <INDENT> if search_paths is None: <NEW_LINE> <INDENT> search_paths = [] <NEW_LINE> <DEDENT> search_paths = list(search_paths) <NEW_LINE> search_paths.append(_DEFAULT_DLL_PATH) <NEW_LINE> loaded = _register_dll(search_paths) <NEW_LINE> if not loaded: <NEW_LINE> <INDENT> ms... | Register the location of the Thermo RawFileReader DLL bundle with
the Common Language Runtime interop system and load the .NET symbols
used by this feature.
Parameters
----------
search_paths: list
The paths to check along for the ThermoRawFileReader DLL bundle. | 625941ee45492302aab5e82a |
def hasAlleleSubset(mvarDict, totDepth, tumorTotDepth): <NEW_LINE> <INDENT> s1 = mvarDict['allele1Seq'] <NEW_LINE> s2 = mvarDict['allele2Seq'] <NEW_LINE> lenS1 = len(s1) <NEW_LINE> lenS2 = len(s2) <NEW_LINE> acc, accTumor = 0, 0 <NEW_LINE> if mvarDict['allele1ReadCount']: <NEW_LINE> <INDENT> acc += int(mvarDict['allele... | ex TG/CGC/CG
ref/allele1/allele2
not all nested result in alt sums greater than the total
not all un-nested are safe from having the sum be greater
This is now just a test of the sum of allele counts being greater than the total
read count. | 625941ee596a89723608a019 |
def push(self, x: int) -> None: <NEW_LINE> <INDENT> self.stack_copy.clear() <NEW_LINE> count = len(self.stack) <NEW_LINE> while count>0: <NEW_LINE> <INDENT> self.stack_copy.append(self.stack.pop()) <NEW_LINE> count -= 1 <NEW_LINE> <DEDENT> self.stack_copy.append(x) <NEW_LINE> count = len(self.stack_copy) <NEW_LINE> whi... | Push element x to the back of queue. | 625941ee5f7d997b87174ffd |
def __init__(self, widget, tag='stdout'): <NEW_LINE> <INDENT> self.widget = widget <NEW_LINE> self.tag = tag | Initialize widget which stdout and stderr were redirected to. | 625941ee26068e7796caf248 |
def dfs(maze_game, start, goal): <NEW_LINE> <INDENT> stack = [(start, [start])] <NEW_LINE> possible_path = PriorityQueue() <NEW_LINE> while stack: <NEW_LINE> <INDENT> (vertex, path) = stack.pop() <NEW_LINE> legal_cells = set(maze_game.legal_directions(*vertex)) - set(path) <NEW_LINE> for next in legal_cells: <NEW_LINE>... | depth-first-search
:param maze_game: the GameMaze instance
:param start: tuple (x,y) of start position
:param goal: tuple (x,y) of the goal position
:return: list containing the path | 625941ee287bf620b61d3fc1 |
def dot(self,A): <NEW_LINE> <INDENT> return matmul(self,A) | Right multiply the current matrix with another :class:`block_sparse` matrix, :class:`symmetric_block_sparse` matrix, or
:class:`~numpy:numpy.array`, A.
Parameters
----------
A : matrix
matrix A with compatible dimensions and block structure: i.e. the row blocks of A must match the column blocks of the
cur... | 625941eeff9c53063f47c751 |
def run(self, vm): <NEW_LINE> <INDENT> binop(operator.add, vm) | Push (TOS-1) + TOS | 625941eebe7bc26dc91cdb56 |
def terminate_run_with_http_info(self, run_id, **kwargs): <NEW_LINE> <INDENT> local_var_params = locals() <NEW_LINE> all_params = [ 'run_id' ] <NEW_LINE> all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) <NEW_LINE> for key, val in six.iteritems(local_var_params['kwar... | Terminates an active run. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.terminate_run_with_http_info(run_id, async_req=True)
>>> result = thread.get()
:param run_id: The ID of the run to be terminated. (require... | 625941eed7e4931a7ee9e480 |
def set_blade_length(length): <NEW_LINE> <INDENT> if isinstance(length, int) or length.replace('.','').isdigit() is True: <NEW_LINE> <INDENT> dt.energy_details.update_variable('blade_length', length) | Sets the blade length of the windmill to a given value. | 625941eed8ef3951e3243a9e |
def name_for_signal(self, signal): <NEW_LINE> <INDENT> signal_name = list(self.keys())[list(self.values()).index(signal)] <NEW_LINE> return signal_name | get the name of a signal number as a string | 625941ee3cc13d1c6d3c78d8 |
@node.commandWrap <NEW_LINE> def SelectMaskToolMarkingMenuPopDown(*args, **kwargs): <NEW_LINE> <INDENT> u <NEW_LINE> return cmds.SelectMaskToolMarkingMenuPopDown(*args, **kwargs) | :rtype: list|str|basestring|DagNode|AttrObject|ArrayAttrObject|Components1Base | 625941eeb545ff76a8914376 |
def setUp(self): <NEW_LINE> <INDENT> AssetType.objects.create(name='flying-wing', description='RPAS that are only a wing') <NEW_LINE> AssetType.objects.create(name='boat', description='Sea-going vessel') <NEW_LINE> get_user_model().objects.create_user('test', password='password') | Prepares 2 asset types
also, a user for the web based tests | 625941eed164cc61757832b0 |
def abbrev_id(self): <NEW_LINE> <INDENT> return self.PULSAR_LIMS_PREFIX + self.MODEL_ABBR + "-" + str(self.id) | This method is called when posting to the ENCODE Portal to grab an alias for the record
being submitted. The alias here is composed of the record ID in Pulsar (i.e. B-1 for the Biosample
with ID 1). However, the record ID is prefexed with a 'p' to designate that this record was
submitted from Pulsar. This is used to ge... | 625941eead47b63b2c50a4e0 |
def testFlagPostUnsafeNext(self): <NEW_LINE> <INDENT> comments = self.createSomeComments() <NEW_LINE> pk = comments[0].pk <NEW_LINE> self.client.login(username="normaluser", password="normaluser") <NEW_LINE> response = self.client.post("/flag/%d/" % pk, {'next': "http://elsewhere/bad"}) <NEW_LINE> self.assertRedirects(... | POSTing to the flag view with an unsafe next url will ignore the
provided url when redirecting. | 625941ee16aa5153ce3629da |
def deleteAllClasses(person): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> if len(person.classes.all()) > 0: <NEW_LINE> <INDENT> person.classes.remove(person.classes.first()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> break | Deletes all classes from passed object | 625941ee8e7ae83300e4b52f |
def reducer(self, key, values): <NEW_LINE> <INDENT> values = reduce(add, values, []) <NEW_LINE> values = list(set(values)) <NEW_LINE> number = self.options.number <NEW_LINE> words = sorted(values, key=len, reverse=True) <NEW_LINE> max_word = words[:number] <NEW_LINE> yield None, '\n'.join(max_word) + '\n' | This is a reducer function of the job, which will be applied to all the lists of words returned by all of the
mappers and will return the --number longest of them as a single text (one word per line). | 625941ee0c0af96317bb8748 |
def test_model_has_custom_str_method(self): <NEW_LINE> <INDENT> assert HousingSupply.__str__ is not models.Model.__str__, "__str__ method should have been overridden" | Test __str__ method of HousingSupply model is different than models.Model.__str__ | 625941ee8e71fb1e9831dd08 |
def _add_graph(self, graph_name=None, graph_uri=None, prefixes=None): <NEW_LINE> <INDENT> if graph_name is not None: <NEW_LINE> <INDENT> if len(graph_name) <= 0: <NEW_LINE> <INDENT> raise Exception("Graph name cannot be an empty string.") <NEW_LINE> <DEDENT> elif graph_uri is not None: <NEW_LINE> <INDENT> self.graphs[g... | add a knowledge graph URI or a set of prefixes to this KnowledgeGraph instance.
:param graph_name: graph user defined name
:type graph_name: string
:param graph_uri: graph URI
:type graph_uri: string
:param prefixes: a dictionary of the prefixes to use in this graph. Keys
are the prefixes and values are the URIs.
:... | 625941eef548e778e58cdae1 |
def on_update_index_unlock_clicked(self, widget): <NEW_LINE> <INDENT> self.update_index_active = True <NEW_LINE> if not SudoDialog.prefer_pkexec() and not SudoDialog.passwordless_sudo(): <NEW_LINE> <INDENT> sudo_dialog = SudoDialog.SudoDialog( parent=self.update_index_dialog, icon='catfish', name=_("Catf... | Unlock admin rights and perform 'updatedb' query. | 625941ee460517430c3946d7 |
def test_simple_tier(self): <NEW_LINE> <INDENT> product = Product.objects.get(slug='PY-Rocks') <NEW_LINE> set_current_user(None) <NEW_LINE> self.assertEqual(product.unit_price, Decimal("19.50")) | Check quantity price for a standard product using the default price | 625941effbf16365ca6f6730 |
def download_pdb_structure( pdb_id: str, directory: Union[str, Path] = user_cache_dir() ) -> Union[Path, bool]: <NEW_LINE> <INDENT> from pathlib import Path <NEW_LINE> from ..utils import LocalFileStorage, FileDownloader <NEW_LINE> directory = Path(directory) <NEW_LINE> pdb_path = LocalFileStorage.rcsb_structure_pdb(pd... | Download a PDB structure. If the structure is not available in PDB format, it will be download
in CIF format.
Parameters
----------
pdb_id: str
The PDB ID of interest.
directory: str or Path, default=user_cache_dir
The directory for saving the downloaded structure.
Returns
-------
: Path or False
The path... | 625941ef293b9510aa2c37f1 |
def test_eight(self): <NEW_LINE> <INDENT> import ast <NEW_LINE> def user_target_property(user): <NEW_LINE> <INDENT> return user['email'] <NEW_LINE> <DEDENT> def record_target_property(record): <NEW_LINE> <INDENT> return Document.objects.get(pk=record['document_id']).title <NEW_LINE> <DEDENT> target_property_mappings = ... | TC 08 | 625941ef4c3428357757c885 |
def __len__(self): <NEW_LINE> <INDENT> if self._is_join: <NEW_LINE> <INDENT> return len(self._buffer) <NEW_LINE> <DEDENT> return super(GlobalSearch, self).__len__() | Returns the total number of results returned in a query. It is the
number of items you can iterate over.
In contrast to count(), the result does take into account any limit
given. In SQL it is like:
SELECT COUNT(*) FROM (
SELECT * FROM <table> [WHERE condition] [LIMIT number]
) | 625941ef15fb5d323cde1079 |
def __init__(self, safe_dist:float, goal_radius:float, rule:str = 'rule_00' ): <NEW_LINE> <INDENT> self.curr_reward = 0 <NEW_LINE> self.info = {} <NEW_LINE> self.goal_radius = goal_radius <NEW_LINE> self.last_goal_dist = None <NEW_LINE> self.safe_dist = safe_dist <NEW_LINE> self._cal_funcs = {'rule_00': RewardCalculato... | A class for calculating reward based various rules.
Args:
safe_dist (float): The minimum distance to obstacles or wall that robot is in safe status.
if the robot get too close to them it will be punished. Unit[ m ]
goal_radius (float): The minimum distance to goal that goal position is considered to be... | 625941ef0a366e3fb873ed80 |
def test_can_speak(self): <NEW_LINE> <INDENT> self.assertEqual(True, True) | Animals that can speak are correctly identified | 625941ef56ac1b37e6264726 |
def updateProcessHasBusinessCapability(self, ID, relationID, **kwargs): <NEW_LINE> <INDENT> allParams = ['ID', 'relationID', 'body'] <NEW_LINE> params = locals() <NEW_LINE> for (key, val) in params['kwargs'].iteritems(): <NEW_LINE> <INDENT> if key not in allParams: <NEW_LINE> <INDENT> raise TypeError("Got an unexpected... | Update relation by a given relationID
Args:
ID, str: Unique ID (required)
relationID, str: Unique ID of the Relation (required)
body, ProcessHasBusinessCapability: Message-Body (optional)
Returns: ProcessHasBusinessCapability | 625941ef57b8e32f52483a00 |
def draw_tutorial(self, *args): <NEW_LINE> <INDENT> self._highlight(self.scoreboard) <NEW_LINE> self.manager._reset_scoring() <NEW_LINE> for i in range(4): <NEW_LINE> <INDENT> self.gameboard._score_match(self.scoreboard, self.scoreboard.scoreboard, i) <NEW_LINE> <DEDENT> self.show_dealer(dealer_index=0, start=(self.siz... | Show the dealer text. | 625941ef94891a1f4081c00d |
def __init__(self, graph, rdf_type=None, **kwargs): <NEW_LINE> <INDENT> self.type = rdf_type <NEW_LINE> self.propObj = kwargs <NEW_LINE> super(PropertyBundle, self).__init__( graph, bnode=True, rdf_type=rdf_type, **kwargs) | Initializes and adds a node to the graph.
NOTE: At least the type or a property must be supplied for the Node
to exist in the graph.
Args:
graph: The graph to add this node to. (instance of rdflib.Graph)
rdf_type: The RDF type to set this node to.
properties: Extra properties to add to this node.
(More... | 625941ef4e4d5625662d4931 |
def _select_clips(self, path, start, end): <NEW_LINE> <INDENT> clips = list() <NEW_LINE> for i in np.linspace(start, end, self.clip_num + 2)[1:self.clip_num + 1]: <NEW_LINE> <INDENT> clip_start = int(i) - 8 <NEW_LINE> clip_end = int(i) + 8 <NEW_LINE> if clip_start < start: <NEW_LINE> <INDENT> clip_end = clip_end - clip... | Select self.batch_size clips for video. Each clip has 16 frames.
Args:
path: Path of frames of qa data.
start: start frame
end: end frame
Returns:
clips: list of clips. | 625941ef7b25080760e399b7 |
def generate_jieba_cut_file(file, cut_all=False, hmm=False, search=False): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if not os.path.exists(file): <NEW_LINE> <INDENT> raise Exception("file not exists") <NEW_LINE> <DEDENT> file_open = open(file, 'r', encoding='utf-8') <NEW_LINE> contents = file_open.read() <NEW_LINE> ... | 以文件作为分词处理对象
:param file:
:param cut_all: 是否全模式
:param hmm: 是否开启新词发现
:param search: 是否搜索模式
:return: | 625941ef091ae356686674b6 |
def tearDown(self): <NEW_LINE> <INDENT> pass | no file or database to close | 625941efaad79263cf390fab |
def remove(feature): <NEW_LINE> <INDENT> out = _srvmgr('Remove-WindowsFeature -Name {0} -erroraction silentlycontinue | format-list'.format(feature)) <NEW_LINE> return _parse_powershell_list(out) | Remove an installed feature
.. note::
Some features require a reboot after installation/uninstallation. If
one of these features are modified, then other features cannot be
installed until the server is restarted. Additionally, some features
take a while to complete installation/uninstallation, so it i... | 625941ef97e22403b379d4fd |
def _checkDrbdStatus(self): <NEW_LINE> <INDENT> local_disk_state, remote_disk_state = self._drbdGetDiskState() <NEW_LINE> self._checkStateType('DISK', local_disk_state) <NEW_LINE> connection_state = self._drbdGetConnectionState() <NEW_LINE> self._checkStateType('CONNECTION', connection_state) <NEW_LINE> local_role_stat... | Checks the status of the Drbd volume and returns the states. | 625941efff9c53063f47c752 |
def get_br_case_family_tab(self): <NEW_LINE> <INDENT> return self.br.get("case_family_tab", True) | Case file use tab to track family members | 625941efb57a9660fec33dee |
def _save_field_blobs_to_db_file(self, net): <NEW_LINE> <INDENT> net.Save( self.ds.get_blobs(), [], db=self.db_path, db_type=self.db_type, blob_name_overrides=self.ds.field_names(), absolute_path=True, ) | Save dataset field blobs to a DB file at db_path | 625941efe8904600ed9f2498 |
def __neg__(self): <NEW_LINE> <INDENT> self = self.copy() <NEW_LINE> self.values = -self.values <NEW_LINE> return self | Negate values.
Examples
--------
>>> r = Rle([1, 2, 3], [5, -20, 1])
>>> r
+--------+-----+-------+-----+
| Runs | 1 | 2 | 3 |
|--------+-----+-------+-----|
| Values | 5.0 | -20.0 | 1.0 |
+--------+-----+-------+-----+
Rle of length 6 containing 3 elements (avg. length 2.0)
>>> -r
+--------+------+------+-... | 625941efb5575c28eb68e567 |
def u16ToByteArray(u16): <NEW_LINE> <INDENT> return array.array('B', ( u16 % 256, (u16 // 256) % 256) ); | Encodes the u16 value as a little endian byte (B) array. | 625941ef236d856c2ad44d44 |
def test_alive2Response(self): <NEW_LINE> <INDENT> def cb(res): <NEW_LINE> <INDENT> self.assertEqual(res, 1) <NEW_LINE> <DEDENT> self.proto.factory._connectDeferred.addCallback(cb) <NEW_LINE> self.proto.dataReceived("y") <NEW_LINE> self.proto.dataReceived("\x00") <NEW_LINE> self.proto.dataReceived("\x00\x01") <NEW_LINE... | Test an successful alive2 response. | 625941ef60cbc95b062c6aa5 |
def finished(self): <NEW_LINE> <INDENT> return self['Status'] in ('Done', 'Canceled') | Check if this ticket count as finished working. | 625941ef507cdc57c630724a |
def link(self, k, v, row=None): <NEW_LINE> <INDENT> if row: <NEW_LINE> <INDENT> inspection_id = row.cr_shelter_inspection.id <NEW_LINE> if inspection_id: <NEW_LINE> <INDENT> return A(v, _href=URL(c = "cr", f = "shelter_inspection", args = [inspection_id], ), ) <NEW_LINE> <DEDENT> <DEDENT> return v | Link inspection flag representations to the inspection record
Args:
k: the inspection flag ID
v: the representation
row: the row from lookup_rows | 625941ef1b99ca400220b015 |
def prep_all(path): <NEW_LINE> <INDENT> if os.path.isfile("prepped_traces_dict.pickle"): <NEW_LINE> <INDENT> with open("prepped_traces_dict.pickle", "rb") as myfile: <NEW_LINE> <INDENT> prepped_traces_dict = pickle.load(myfile) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> prepped_traces_dict = {} <NEW_LINE> <... | For all text files in path, extract ramps, let the user select good ramps and set res_tot_0 and store the
resulting DFs and res_tot_0's in a pickled dict. | 625941ef8da39b475bd654dd |
def max_depth1(root): <NEW_LINE> <INDENT> if not root: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> return 1 + max(max_depth1(root.left), max_depth1(root.right)) | 递归实现
:param root: (TreeNode)
:return: (int) | 625941efbd1bec0571d90b91 |
def manage_addShibRoleManager(self, id='shibrole', title='', REQUEST=None): <NEW_LINE> <INDENT> rm = ShibRoleManager(id, title) <NEW_LINE> self._setObject(rm.getId(), rm) <NEW_LINE> if REQUEST is not None: <NEW_LINE> <INDENT> REQUEST['RESPONSE'].redirect('%s/manage_workspace' '?manage_tabs_message=' 'ShibRoleManager+ad... | Add a to a Pluggable Auth Service.
| 625941ef3cc13d1c6d3c78d9 |
def _construct_layer(name): <NEW_LINE> <INDENT> if name in self.layers: <NEW_LINE> <INDENT> return self.layers[name] <NEW_LINE> <DEDENT> if name not in net_dict: <NEW_LINE> <INDENT> if name == "data": <NEW_LINE> <INDENT> layer_desc = {"class": "source", "from": []} <NEW_LINE> <DEDENT> elif name.startswith("data:"): <NE... | :param str name:
:param dict[str] layer_desc:
:rtype: LayerBase | 625941ef046cf37aa974d2a4 |
def __init__(self, pin_rs=4, pin_e=17, pins_db=[18, 22, 23, 24]): <NEW_LINE> <INDENT> self.pin_rs=pin_rs <NEW_LINE> self.pin_e=pin_e <NEW_LINE> self.pins_db=pins_db <NEW_LINE> GPIO.setmode(GPIO.BCM) <NEW_LINE> GPIO.setup(self.pin_e, GPIO.OUT) <NEW_LINE> GPIO.setup(self.pin_rs, GPIO.OUT) <NEW_LINE> for pin in self.pins_... | Initialise GPIO | 625941ef379a373c97cfb0a8 |
def login_required(handler_method): <NEW_LINE> <INDENT> def check_login(self): <NEW_LINE> <INDENT> user = self.get_current_user() <NEW_LINE> if user is None: <NEW_LINE> <INDENT> self.error(403) <NEW_LINE> return <NEW_LINE> <DEDENT> self.user = user <NEW_LINE> handler_method(self) <NEW_LINE> <DEDENT> return check_login | A decorator to validate request for /api/diary and /api/notes | 625941efa17c0f6771cbe5b1 |
def addDeleteDhcpServerOptionIDL(self, sessionId, poolName, ipList, option, action): <NEW_LINE> <INDENT> pass | Parameters:
- sessionId
- poolName
- ipList
- option
- action | 625941ef10dbd63aa1bd3104 |
def __init__(self, results=None): <NEW_LINE> <INDENT> self.swagger_types = { 'results': 'list[ShopOrder]' } <NEW_LINE> self.attribute_map = { 'results': 'results' } <NEW_LINE> self._results = results | InlineResponse2007D - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition. | 625941efcc0a2c11143dd3f3 |
def _search(self, query_obj, num, after, reverse, count=0, type=None, skip_deleted_authors=True, sr_detail=False): <NEW_LINE> <INDENT> builder = SearchBuilder(query_obj, after=after, num=num, reverse=reverse, count=count, wrap=ListingController.builder_wrapper, skip_deleted_authors=skip_deleted_authors, sr_detail=sr_de... | Helper function for interfacing with search. Basically a
thin wrapper for SearchBuilder. | 625941ef9f2886367277adeb |
def __init__(self, database, options, user): <NEW_LINE> <INDENT> Report.__init__(self, database, options, user) <NEW_LINE> self.map = {} <NEW_LINE> menu = options.menu <NEW_LINE> self.max_generations = menu.get_option_by_name('maxgen').get_value() <NEW_LINE> self.pgbrk = menu.get_option_by_name('pagebbg').get_value() <... | Create the AncestorReport object that produces the Ahnentafel report.
The arguments are:
database - the GRAMPS database instance
options - instance of the Options class for this report
user - a gen.user.User() instance
This report needs the following parameters (class variables)
that come i... | 625941ef5fcc89381b1e1c25 |
def test_make_archive_negtive_archive_name_is_required(self): <NEW_LINE> <INDENT> self.assertRaises(Exception, archive.make_archive, '', self.relative_dir) | Test if first parameter: file path is empty | 625941efa934411ee3751bf7 |
def h_levelsum(self) -> int: <NEW_LINE> <INDENT> level_sum = 0 <NEW_LINE> for goal in self.problem.goal: <NEW_LINE> <INDENT> goal_s=PgNode_s(goal,True) <NEW_LINE> for level_counter,s_state in enumerate(self.s_levels): <NEW_LINE> <INDENT> if goal_s in s_state: <NEW_LINE> <INDENT> level_sum+=level_counter <NEW_LINE> brea... | The sum of the level costs of the individual goals (admissible if goals independent)
:return: int | 625941ef8c0ade5d55d3ef22 |
def transformEvent(self, ev): <NEW_LINE> <INDENT> data = { 'timestamp': int(ev.time * 1000), 'metric': ev.service.replace(' ', '_'), 'value': ev.metric, 'tags': { 'host': ev.hostname, 'state': ev.state, } } <NEW_LINE> if ev.tags: <NEW_LINE> <INDENT> data['tags'] = ",".join(ev.tags) <NEW_LINE> <DEDENT> if ev.attributes:... | Convert an event object into OpenTSDB format
| 625941ef67a9b606de4a8418 |
def availablePremises( self ): <NEW_LINE> <INDENT> assert isinstance( self._env, Env ) <NEW_LINE> assert isinstance( self._steps, list ) <NEW_LINE> return self._env.availableSteps( ) | Return a list of valid step citations for a next step. .
Category: Pure Function
Returns: (list)
Side Effects: None.
Preconditions: None. | 625941efbaa26c4b54cb167c |
def _assert_path(self,*path): <NEW_LINE> <INDENT> if len(path)==1 and isinstance(path[0],tuple): <NEW_LINE> <INDENT> path = path[0] <NEW_LINE> <DEDENT> _handles_dict_keys = self._handles_dict.keys() <NEW_LINE> for i,path_partial in enumerate(path): <NEW_LINE> <INDENT> if not isinstance(path_partial,str): <NEW_LINE> <IN... | Test if path is valid. If not, returns the relevant Exception
(which you need to raise yourself)
See method possible_paths for more information about path. | 625941ef63d6d428bbe44a53 |
def getRandom(self): <NEW_LINE> <INDENT> idx = random.randint(0, len(self.nums) - 1) <NEW_LINE> return self.nums[idx] | Get a random element from the set.
:rtype: int | 625941efe64d504609d74da2 |
def rotate_points(self, base_pt_id: int, angle: float, pt_id_list: Iterable[int]) -> None: <NEW_LINE> <INDENT> for pt in [Point.find_by_id(pt_id) for pt_id in pt_id_list]: <NEW_LINE> <INDENT> pt.rotate(base_pt_id, angle) | Rotate all points in a list by a given angle about a base point, counter-clockwise. | 625941ef50485f2cf553d2fe |
def handle(self, *args, **options): <NEW_LINE> <INDENT> super(Command, self).handle(*args, **options) <NEW_LINE> html_list = glob.glob(os.path.join(self.html_dir, "candidates/*.html")) <NEW_LINE> election_list = [] <NEW_LINE> candidate_list = [] <NEW_LINE> for html_path in html_list: <NEW_LINE> <INDENT> with open(html_... | Make it happen. | 625941ef498bea3a759ba010 |
def read_calculated_magnetometer_calibration(self): <NEW_LINE> <INDENT> return _libvncxx.VnSensor_read_calculated_magnetometer_calibration(self) | read_calculated_magnetometer_calibration(VnSensor self) -> CalculatedMagnetometerCalibrationRegister | 625941efab23a570cc2506e9 |
def __init__( self, anchor_time=None, client_id=None, client_secret=None, cron_expression=None, frequency_in_minutes=None, quota_user=None, refresh_token=None, report_definitions=None, start_date=None, local_vars_configuration=None, ): <NEW_LINE> <INDENT> if local_vars_configuration is None: <NEW_LINE> <INDENT> local_v... | GoogleAnalyticsSourceFormProperties - a model defined in OpenAPI | 625941ef97e22403b379d4fe |
def as_dict(self) -> dict: <NEW_LINE> <INDENT> time_zone = dt_util.UTC.zone <NEW_LINE> if self.time_zone and getattr(self.time_zone, "zone"): <NEW_LINE> <INDENT> time_zone = getattr(self.time_zone, "zone") <NEW_LINE> <DEDENT> return { "latitude": self.latitude, "longitude": self.longitude, "elevation": self.elevation, ... | Create a dictionary representation of the configuration.
Async friendly. | 625941ef99cbb53fe6793147 |
def itkExpImageFilterIUC3IUC3_Superclass_cast(*args): <NEW_LINE> <INDENT> return _itkExpImageFilterPython.itkExpImageFilterIUC3IUC3_Superclass_cast(*args) | itkExpImageFilterIUC3IUC3_Superclass_cast(itkLightObject obj) -> itkExpImageFilterIUC3IUC3_Superclass | 625941ef6fece00bbac2dca7 |
def testMatchXyMatchControl(self): <NEW_LINE> <INDENT> for closest in (True, False): <NEW_LINE> <INDENT> for includeMismatches in (True, False): <NEW_LINE> <INDENT> mc = afwTable.MatchControl() <NEW_LINE> mc.findOnlyClosest = closest <NEW_LINE> mc.includeMismatches = includeMismatches <NEW_LINE> matches = afwTable.matc... | Test using MatchControl to return all matches
Also tests closest==False at the same time | 625941ef283ffb24f3c55e5e |
def to_dictionary(self): <NEW_LINE> <INDENT> rec_dict = {} <NEW_LINE> rec_dict["id"] = self.id <NEW_LINE> rec_dict["width"] = self.width <NEW_LINE> rec_dict["height"] = self.height <NEW_LINE> rec_dict["x"] = self.x <NEW_LINE> rec_dict["y"] = self.y <NEW_LINE> return rec_dict | this PUBLIC method returns dictionary rep of Rectangle | 625941ef1f5feb6acb0c50ac |
def get_categories(): <NEW_LINE> <INDENT> return VIDEOS.keys() | Get the list of video categories.
Here you can insert some parsing code that retrieves
the list of video categories (e.g. 'Movies', 'TV-shows', 'Documentaries' etc.)
from some site or server.
.. note:: Consider using `generator functions <https://wiki.python.org/moin/Generators>`_
instead of returning lists.
:re... | 625941ef3c8af77a43ae3d09 |
@cross_domain_ajax <NEW_LINE> def map_aux_reports_bounds_notifs(request, bounds, date_start, date_end, hashtag, municipalities, mynotifs, notif_types): <NEW_LINE> <INDENT> if not userIsValid(request.user): <NEW_LINE> <INDENT> mynotifs = 'N' <NEW_LINE> notif_types = 'N' <NEW_LINE> <DEDENT> qs = MapAuxReports.objects.ext... | Get Unclustered Data to Show on Map With Filters. | 625941ef73bcbd0ca4b2c5d8 |
def ds_versions(self): <NEW_LINE> <INDENT> return [ 'v'+x.json['version'] for x in self.ctx.search()] | return list of versions for datasets in search result | 625941efa8370b7717052e00 |
def get_turing_text(self,text): <NEW_LINE> <INDENT> turing_url_data = dict( key = '6b8d0fae75a64ecb81aeed6695831d74', info = text, userid = '101270', ) <NEW_LINE> self.request = Request(self.turing_url + urlencode(turing_url_data)) <NEW_LINE> try: <NEW_LINE> <INDENT> w_data = urlopen(self.request) <NEW_LINE> <DEDENT> e... | 请求方式: HTTP POST
请求参数: 参数 是否必须 长度 说明
key 必须 32 APIkey
info 必须 1-32 请求内容,编码方式为"utf-8"
userid 必须 32 MAC地址或ID | 625941ef8a43f66fc4b545c1 |
def update_position_and_clean(self): <NEW_LINE> <INDENT> new_position = self.position.get_new_position(self.get_robot_direction(), self.speed) <NEW_LINE> if self.room.is_position_valid(new_position): <NEW_LINE> <INDENT> self.position = new_position <NEW_LINE> if self.gets_faulty(): <NEW_LINE> <INDENT> self.set_robot_di... | Simulate the passage of a single time-step.
Check if the robot gets faulty. If the robot gets faulty,
do not clean the current tile and change its direction randomly.
If the robot does not get faulty, the robot should behave like
StandardRobot at this time-step (checking if it can move to a new position,
move there i... | 625941ef711fe17d825428c1 |
def func(self): <NEW_LINE> <INDENT> caller = self.caller <NEW_LINE> if not self.args: <NEW_LINE> <INDENT> caller.msg("Say what?") <NEW_LINE> return <NEW_LINE> <DEDENT> speech = self.args <NEW_LINE> speech = caller.at_before_say(speech) <NEW_LINE> if not speech: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> caller.at_s... | Run the say command | 625941efbf627c535bc13732 |
def setup(bot): <NEW_LINE> <INDENT> bot.add_cog(Twitter(bot)) | Required for cogs.
:param bot: The Discord bot. | 625941efcdde0d52a9e5359a |
def test_hfss_high_port_number(self): <NEW_LINE> <INDENT> _3ports = rf.Network(self.hfss_18dot2) <NEW_LINE> self.assertTrue(_3ports.s.shape[1:] == (3,3)) <NEW_LINE> self.assertTrue(_3ports.z0.shape[1] == 3) <NEW_LINE> self.assertTrue(_3ports.gamma.shape[1] == 3) <NEW_LINE> _8ports = rf.Network(self.hfss_8ports) <NEW_LI... | Check dimensions s, gamma and z0 of Network from HFSS .sNp files
HFSS exports .sNp files with N > 4 with Gamma and Z0 as comments and
written on multiple lines. The additional lines start with a '!' that
need to be escaped to avoid numerical conversion error. | 625941ef3539df3088e2e8ae |
@bp_rack.route('/ajax/get_rack_choices', methods=['GET', 'POST']) <NEW_LINE> @login_required <NEW_LINE> def ajax_get_rack_choices(): <NEW_LINE> <INDENT> warehouse_id = request.args.get('warehouse_id', 0, type=int) <NEW_LINE> rack_choices = get_rack_choices(warehouse_id) <NEW_LINE> return jsonify(rack_choices) | 货架选项
:return: | 625941eff8510a7c17cf9c63 |
def setServer(self): <NEW_LINE> <INDENT> return self._server.setServer() | Sets this server as the one to use for new objects when using
the embedded device. | 625941ef71ff763f4b549bf8 |
def maxProfit(self, prices): <NEW_LINE> <INDENT> if len(prices) == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> max_profit = 0 <NEW_LINE> min_prices = prices[0] <NEW_LINE> for i in range(1, len(prices)): <NEW_LINE> <INDENT> min_prices = min(min_prices, prices[i]) <NEW_LINE> max_profit = max(max_profit, prices[i]... | :type prices: List[int]
:rtype: int | 625941ef57b8e32f52483a01 |
def fix_length(self): <NEW_LINE> <INDENT> if self._tube_length is not None: <NEW_LINE> <INDENT> if self._fmt == 'xyz': <NEW_LINE> <INDENT> xyzreader = XYZReader(self._output) <NEW_LINE> atoms = xyzreader.atoms <NEW_LINE> atoms.clip_bounds(abs_limit=self._tube_length / 2 + 0.1, r_indices=[2]) <NEW_LINE> XYZWriter.write(... | Crop nanotube ends for correct length. | 625941efd10714528d60024c |
def load_all_provider_templates(self): <NEW_LINE> <INDENT> sel.force_navigate('{}_provider'.format(self.page_name), context={'provider': self}) <NEW_LINE> if details_page.infoblock.text("Relationships", self.template_name) == "0": <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sel.click(... | Loads the list of images that are available under the provider.
If it could click through the link in infoblock, returns ``True``. If it sees that the
number of images is 0, it returns ``False``. | 625941ef7047854f462a1966 |
def build_s(data): <NEW_LINE> <INDENT> s = {} <NEW_LINE> for lexelt, attributes in data.iteritems(): <NEW_LINE> <INDENT> word_set = set() <NEW_LINE> for attribute in attributes: <NEW_LINE> <INDENT> word_set.update(nltk.word_tokenize(attribute[1][-10:])) <NEW_LINE> word_set.update(nltk.word_tokenize(attribute[3][:10])) ... | Compute the context vector for each lexelt(word.postag)
:param data: dic with the following structure:
lexelt(word.postag): [(instance_id, left_context, head, right_context, sense_id), ...]
:return: dic s with the following structure:
lexelt(word.postag): [w1,w2,w3, ...], | 625941ef4428ac0f6e5bad5a |
def test_softmax_model(): <NEW_LINE> <INDENT> config = Config() <NEW_LINE> np.random.seed(1234) <NEW_LINE> inputs = np.random.rand(config.n_samples, config.n_features) <NEW_LINE> labels = np.zeros((config.n_samples, config.n_classes), dtype=np.int32) <NEW_LINE> labels[:, 0] = 1 <NEW_LINE> with tf.Graph().as_default(): ... | Train softmax model for a number of steps. | 625941ef26068e7796caf24a |
def load_schema(self): <NEW_LINE> <INDENT> path = pkg_resources.resource_filename('clacks.agent', 'data/objects') <NEW_LINE> schema_paths = [] <NEW_LINE> for f in [n for n in os.listdir(path) if n.endswith(os.extsep + 'xml')]: <NEW_LINE> <INDENT> schema_paths.append(os.path.join(path, f)) <NEW_LINE> <DEDENT> path = os.... | This method reads all object defintion files (xml) and combines
into one single xml-dump.
This combined-xml-dump will then be forwarded to
:meth:`clacks.agent.objects.factory.ObjectFactory.__parse_schema`
to generate meta-classes for each object.
This meta-classes can then be used to instantiate those objects. | 625941ef287bf620b61d3fc3 |
def waiting_for(self, user): <NEW_LINE> <INDENT> return super(QuestManager, self).get_query_set().filter(relation__quester=user).filter(status='M') | Returns the set of quests the provided user is waiting for. | 625941efa05bb46b383ecd7f |
def __draw_back(self): <NEW_LINE> <INDENT> self.setAutoFillBackground(True) <NEW_LINE> palette = QPalette() <NEW_LINE> palette.setColor(QPalette.Window, QColor('#000000')) <NEW_LINE> self.setPalette(palette) | 初始化背景为黑色 | 625941efd4950a0f3b08c8aa |
def __expect(self, expected, timeout=5, endswith=False): <NEW_LINE> <INDENT> print('[%s] Expecting [%s]' % (self.port, expected)) <NEW_LINE> deadline = time.time() + timeout <NEW_LINE> while True: <NEW_LINE> <INDENT> line = self._cliReadLine() <NEW_LINE> if line is not None: <NEW_LINE> <INDENT> self.log("readline: %s",... | Find the `expected` line within `times` tries.
Args:
expected str: the expected string
times int: number of tries | 625941efbe383301e01b59dd |
def area_circle(r): <NEW_LINE> <INDENT> check_positive(r) <NEW_LINE> area = np.pi*r*r <NEW_LINE> return area | calculate area of a circle | 625941ef0c0af96317bb874a |
def get_n_splits(self, X=None, y=None, groups=None): <NEW_LINE> <INDENT> if not isinstance(X, pd.DataFrame): <NEW_LINE> <INDENT> raise ValueError('X is not a pandas.DataFrame') <NEW_LINE> <DEDENT> if not isinstance(X.index, pd.DatetimeIndex): <NEW_LINE> <INDENT> raise ValueError("X's index is not a DatetimeIndex") <NEW... | Returns the number of splitting iterations in the cross-validator | 625941ef5e10d32532c5f488 |
def resizeGL(self, width=0, height=0): <NEW_LINE> <INDENT> if height==0: <NEW_LINE> <INDENT> height=1 <NEW_LINE> <DEDENT> glViewport(0, 0, width, height) <NEW_LINE> glMatrixMode(GL_PROJECTION) <NEW_LINE> glLoadIdentity() <NEW_LINE> gluPerspective(45, 1.0*width/height, 0.1, 100.0) <NEW_LINE> glMatrixMode(GL_MODELVIEW) <... | Resize the GL window | 625941efbe383301e01b59de |
def mtsls(function, sol, fitness, lower, upper, maxevals, SR): <NEW_LINE> <INDENT> dim = len(sol) <NEW_LINE> improved_dim = zeros(dim, dtype=bool) <NEW_LINE> check = partial(clip, a_min=lower, a_max=upper) <NEW_LINE> current_best = EAresult(solution=sol, fitness=fitness, evaluations=0) <NEW_LINE> totalevals = 0 <NEW_LI... | Implements the MTS LS
parameters
:function: to optimize.
:sol: solution to improves.
:lower: lower domain.
:upper: upper domain.
:maxevals: maximum evaluations.
:SR: step size.
:improved: indicate the ratio of previous improvement. | 625941ef851cf427c661aa6d |
def mode_passive(self): <NEW_LINE> <INDENT> return self.send_cmd(create.OP_PASSIVE) | Set mode to passive. | 625941efe1aae11d1e74a220 |
def permute(self, nums): <NEW_LINE> <INDENT> c = Counter(nums) <NEW_LINE> vals = sorted(c.keys()) <NEW_LINE> cnts = [c[v] for v in vals] <NEW_LINE> res = [0]*len(nums) <NEW_LINE> ans = [] <NEW_LINE> def dfs(vals, cnts, res, pos): <NEW_LINE> <INDENT> if pos >= len(nums): <NEW_LINE> <INDENT> ans.append(res[:]) <NEW_LINE>... | :type nums: List[int]
:rtype: List[List[int]] | 625941ef711fe17d825428c2 |
def render_all_source_files(source_db_path, output_dir): <NEW_LINE> <INDENT> conn = sqlite3.connect(source_db_path) <NEW_LINE> cur = conn.cursor() <NEW_LINE> cur.execute('SELECT column_id, column_title, had_sub, update_frequency FROM columns ORDER BY column_id') <NEW_LINE> columns = cur.fetchall() <NEW_LINE> cur.close(... | :param source_db_path: sqlite db url
:param output_dir: output directory of the source files
:return: | 625941ef21a7993f00bc825d |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.