code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def clear_clipboard(self): <NEW_LINE> <INDENT> self.clip = '' <NEW_LINE> pyperclip.copy(self.clip) | Uses pyperclip to clear the clipboard | 625941dd187af65679ca542f |
def __init__(self, specInfo, DUTObj, saveFilePath, logger): <NEW_LINE> <INDENT> self.dataQueue = queue.Queue() <NEW_LINE> self.specInfo = specInfo <NEW_LINE> self.currentSuggestion = DUTObj <NEW_LINE> self.saveFilePath = saveFilePath <NEW_LINE> self.measurementsCompleted = False <NEW_LINE> self.isActive = True <NEW_LIN... | Construct a new 'ATSProcessor' object.
:param parent: as needed
:return: returns nothing | 625941dd26238365f5f0f182 |
def toMObject(nodeName): <NEW_LINE> <INDENT> pass | Get the API MObject given the name of an existing node | 625941ddb57a9660fec33b98 |
def find_items_from_list_page(self, sel, item_urls): <NEW_LINE> <INDENT> base_url = 'http://www.chicos.com' <NEW_LINE> items_xpath = '//*[@class="sh-product-link"]/@href' <NEW_LINE> return self._find_items_from_list_page( sel, base_url, items_xpath, item_urls) | parse items in category page | 625941dd23e79379d52ee870 |
def removeElements(self, head, val): <NEW_LINE> <INDENT> if not head: <NEW_LINE> <INDENT> return None; <NEW_LINE> <DEDENT> dummy = ListNode(-1); <NEW_LINE> dummy.next = head; <NEW_LINE> prev = dummy; <NEW_LINE> curr = head; <NEW_LINE> while curr!=None: <NEW_LINE> <INDENT> if curr.val==val: <NEW_LINE> <INDENT> prev.next... | :type head: ListNode
:type val: int
:rtype: ListNode | 625941dd8da39b475bd65286 |
def RPN(expression,input_): <NEW_LINE> <INDENT> stack = [] <NEW_LINE> try: <NEW_LINE> <INDENT> for val in expression: <NEW_LINE> <INDENT> if val in list_operator: <NEW_LINE> <INDENT> op1 = stack.pop() <NEW_LINE> op2 = stack.pop() <NEW_LINE> if val=='-': result = op2 - op1 <NEW_LINE> if val=='+': result = op2 + op1 <NEW... | Evaluate a reverse polish notation | 625941dd21bff66bcd684c5f |
def start(self, ev_channel=None, rss_url=None, rss_rate=None): <NEW_LINE> <INDENT> global _SESSIONS <NEW_LINE> if not _SESSIONS: <NEW_LINE> <INDENT> from evennia.server.sessionhandler import SESSIONS as _SESSIONS <NEW_LINE> <DEDENT> if ev_channel: <NEW_LINE> <INDENT> channel = search.channel_search(ev_channel) <NEW_LIN... | Start by telling the portal to start a new RSS session
Args:
ev_channel (str): Key of the Evennia channel to connect to.
rss_url (str): Full URL to the RSS feed to subscribe to.
rss_update_rate (int): How often for the feedreader to update.
Raises:
RuntimeError: If `ev_channel` does not exist. | 625941dd091ae35668667269 |
def _first_expander(fringe, iteration, viewer): <NEW_LINE> <INDENT> current = fringe[0] <NEW_LINE> neighbors = current.expand(local_search=True) <NEW_LINE> if viewer: viewer.expanded([current], [neighbors]) <NEW_LINE> fringe.extend(neighbors) | Expander that expands only the first node on the fringe. | 625941dd627d3e7fe0d69161 |
def __init__(self, name, version=None, url=None, requires=None, depth=0): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.version = version <NEW_LINE> self.url = url <NEW_LINE> self.requires = requires <NEW_LINE> self.targets = [] <NEW_LINE> self.test_targets = [] <NEW_LINE> self.depth = depth | Initialize. | 625941dd5166f23b2e1a5469 |
def update_view(): <NEW_LINE> <INDENT> if gvars.view_state==0: <NEW_LINE> <INDENT> main_list.set_list(get_feeds_entries()) <NEW_LINE> <DEDENT> if gvars.view_state==1: <NEW_LINE> <INDENT> main_list.set_list(feeds[gvars.current_feed].get_articles()) | Updates the current view, depending on the current view state | 625941dd656771135c3ebb82 |
def get_percepts(self, invert=False): <NEW_LINE> <INDENT> mul = 1 <NEW_LINE> if invert: <NEW_LINE> <INDENT> mul = -1 <NEW_LINE> <DEDENT> return [[mul * self.m[i][j] for j in range(self.columns)] for i in range(self.rows)] | Return the percepts corresponding to the current state.
If invert is True, the sign of all values is inverted to get the view
of the other player. | 625941dd63d6d428bbe447ff |
def test_retry_build_on_compute_error(self): <NEW_LINE> <INDENT> server = dict( name='retry-test', imageRef=self.image_id, flavorRef=self.flavor_id) <NEW_LINE> server = self.admin_api.post_server({'server': server}) <NEW_LINE> self.addCleanup(self.admin_api.delete_server, server['id']) <NEW_LINE> server = self._wait_fo... | Tests the retry operation between compute nodes when one fails.
This tests the scenario that we have two compute services and we
try to build a single server. The test is setup such that the
scheduler picks the first host which we mock out to fail the claim.
This should then trigger a retry to the second host. | 625941ddbaa26c4b54cb142c |
def wheelEvent(self, event): <NEW_LINE> <INDENT> factor = 0.25 <NEW_LINE> if (event.modifiers() & QtCore.Qt.ControlModifier): <NEW_LINE> <INDENT> if event.delta() > 0: <NEW_LINE> <INDENT> self.scaleFactor += factor <NEW_LINE> self.parent.mainWindow.lineEdit_2.setText("{:3.0f}%".format(self.scaleFactor*100)) <NEW_LINE> ... | Callback method, when the mouse wheel is used.
:param event: `QtGui.wheelEvent`. | 625941dd3d592f4c4ed1d376 |
def unescape(text): <NEW_LINE> <INDENT> if not isinstance(text, Markup): <NEW_LINE> <INDENT> return text <NEW_LINE> <DEDENT> return text.unescape() | Reverse-escapes &, <, > and " and returns a `unicode` object. | 625941dd7d43ff24873a2fb1 |
def setup_ssh_auto_login(args): <NEW_LINE> <INDENT> keys_location = "~/.ssh" <NEW_LINE> pri_key_paths = ["~/.ssh/id_dsa", "~/.ssh/id_ecdsa", "~/.ssh/id_ed25519", "~/.ssh/id_rsa"] <NEW_LINE> total_keys_flag = False <NEW_LINE> pri_key_flag = False <NEW_LINE> pub_key_flag = False <NEW_LINE> for pri_key_path in pri_key_pat... | Setup SSH for auto login without a password | 625941dd5f7d997b87174daa |
def p_arg_struct(p): <NEW_LINE> <INDENT> newList = [] <NEW_LINE> newList.append(p[1]) <NEW_LINE> newList.append(AST("field-inits", [p[3]])) <NEW_LINE> p[0] = AST("struct", newList) | arg_struct : id LSQUIGBRACKET body RSQUIGBRACKET | 625941dd6fb2d068a760f3b1 |
def GetInput(self, *args): <NEW_LINE> <INDENT> return _itkImageToMeshFilterPython.itkImageToMeshFilterIUC2MD2Q_GetInput(self, *args) | GetInput(self, unsigned int idx) -> itkImageUC2 | 625941ddb7558d58953c521f |
@api.route('/user/message', methods=['GET', 'PUT', 'DELETE']) <NEW_LINE> @osr_login_required <NEW_LINE> @permission_required(use_default=False) <NEW_LINE> def api_user_message(): <NEW_LINE> <INDENT> if request.c_method == "GET": <NEW_LINE> <INDENT> data = get_user_msgs() <NEW_LINE> <DEDENT> elif request.c_method == "PU... | GET:
获取用户的消息
type:<array>,消息类型, 比如["notice", "private_letter"]
label:<array>, 消息label, 默认全部label, 比如['comment', 'audit_failure', 'sys_notice']
pre:<int>,每页获取几条数据,默认10
page:<int>,第几页,默认1
status_update:<str>,获取后的消息状态更新. 可以为: "have_read"
PUT:
更新消息状态
ids:<array>,消息id
status_update:<str>,... | 625941dd07d97122c4178ba1 |
def test_index_view_with_two_past_questions(self): <NEW_LINE> <INDENT> create_question(text="Past question 1.", days=-30) <NEW_LINE> create_question(text="Past question 2.", days=-5) <NEW_LINE> response = self.client.get(reverse('polls:index')) <NEW_LINE> self.assertQuerysetEqual( response.context['latest_question_list... | The questions index page may display multiple questions. | 625941dd9f2886367277ab9b |
def home(request): <NEW_LINE> <INDENT> today = datetime.date.today() <NEW_LINE> return render(request, 'taskbuster/index.html', {'today': today, 'now': now()}) | Index page view
:param request: HTTP request
:return: index page render | 625941dd283ffb24f3c55c0e |
def scrape_algorithm_times(json_filename): <NEW_LINE> <INDENT> results = {} <NEW_LINE> if os.path.isfile(json_filename): <NEW_LINE> <INDENT> with open(json_filename, "r") as file: <NEW_LINE> <INDENT> data = json.load(file) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return results <NEW_LINE> <DEDENT> for tim... | Scrape wall times from the timemory json.
Search for timer tags containing "algorithm='{algorithm}'" then extract
the wall times. Return a new dictionary of dictionaries
where the first key is the algorithm name and the second key is "wall time". | 625941dd4d74a7450ccd44d3 |
def testChangeView(self): <NEW_LINE> <INDENT> change_dict = {'title' : 'Ikke fordømt', 'content': '<p>edited article</p>', 'date_0': '2008-03-18', 'date_1': '10:54:39', 'section': 1} <NEW_LINE> self.client.get('/test_admin/admin/') <NEW_LINE> self.client.post('/test_admin/admin/', self.adduser_login) <NEW_LINE> request... | Change view should restrict access and allow users to edit items. | 625941dd99cbb53fe6792ef6 |
def testGetArgsForClassConstructorClassNotInDic(self): <NEW_LINE> <INDENT> dic = {'cl_2': ['clarg21', 'clarg22'], 'cl_1': ['clarg11', 'clarg12'], 'ca': ['ca_arg1'], 'cc1': ['ccarg1'], 'cc3': ['ccarg3'], 'cc2': ['ccarg2']} <NEW_LINE> cap = ConstructorArgsProvider(dic) <NEW_LINE> self.assertIsNone(cap.getArgsForClassCons... | Test case when asking ctor args for a class which is unknown from the ConstructorArgsProvider | 625941dd1f5feb6acb0c4e5c |
def test_sign_index_action_sign_success(self): <NEW_LINE> <INDENT> response = self.c.post('/sign_index_action/4/', {"phone": "23214214"}) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> self.assertIn(b"sign in success!", response.content) | guest sign successful | 625941dd55399d3f055889c5 |
def find_data_files(source, target, patterns): <NEW_LINE> <INDENT> if glob.has_magic(source) or glob.has_magic(target): <NEW_LINE> <INDENT> raise ValueError("Magic not allowed in src, target") <NEW_LINE> <DEDENT> ret = {} <NEW_LINE> for pattern in patterns: <NEW_LINE> <INDENT> pattern = os.path.join(source, pattern) <N... | Locates the specified data-files and returns the matches
in a data_files compatible format.
source is the root of the source data tree.
Use '' or '.' for current directory.
target is the root of the target data tree.
Use '' or '.' for the distribution directory.
patterns is a sequence of glob-patterns for the
files you... | 625941ddaad79263cf390d55 |
def ping(): <NEW_LINE> <INDENT> r = salt.utils.http.query(DETAILS['url']+'ping', decode_type='json', decode=True) <NEW_LINE> try: <NEW_LINE> <INDENT> return r['dict'].get('ret', False) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> return False | Is the REST server up? | 625941ddd53ae8145f87a57b |
@app.route("/api/v1.0/transit_systems") <NEW_LINE> def transit_systems(): <NEW_LINE> <INDENT> results = table_join() <NEW_LINE> results = results.all() <NEW_LINE> json_results = json_dict(results) <NEW_LINE> return json_results | Display all transit system data | 625941dd377c676e912724b7 |
def turn_off(self): <NEW_LINE> <INDENT> if self.state != STATE_OFF: <NEW_LINE> <INDENT> self._power() | Send power action if device is not off. | 625941dd56ac1b37e62644db |
def test_get_oauth2_server_validator(self): <NEW_LINE> <INDENT> client = self.new_client() <NEW_LINE> self.assertTrue( isinstance(client.get_oauth2_server().request_validator, OdooValidator)) | Check the validator of the returned server | 625941dd293b9510aa2c35a3 |
def get_fields_with_visibility(self, visibility="edit", mode="add"): <NEW_LINE> <INDENT> fields = self.get_sorted_fields() <NEW_LINE> out = [] <NEW_LINE> for field in fields: <NEW_LINE> <INDENT> v = field.widget.isVisible( self.context, mode, default='invisible', field=field) <NEW_LINE> if self.is_field_visible(field) ... | Return the fields with visibility
| 625941dd090684286d50eff9 |
def inc(self, key): <NEW_LINE> <INDENT> if key not in self.keys: <NEW_LINE> <INDENT> if len(self.count_key) == 0: <NEW_LINE> <INDENT> self.count_key.add_at_tail([1, {key}]) <NEW_LINE> self.keys[key] = self.count_key.get_at_tail() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> head = self.count_key.get_at_head() <NEW_LIN... | Inserts a new key <Key> with value 1. Or increments an existing key by 1.
:type key: str
:rtype: void | 625941dde5267d203edcdfa9 |
def canonicalize_json(obj: dict) -> bytes: <NEW_LINE> <INDENT> return json.dumps( obj, separators=(',', ':'), ensure_ascii=False, sort_keys=True).encode('utf-8') | Generate JSON output compatible with
net.sf.json.JSONObject.writeCanonical. | 625941ddd164cc617578305f |
def resolve_url(to, *args, **kwargs): <NEW_LINE> <INDENT> if hasattr(to, 'get_absolute_url'): <NEW_LINE> <INDENT> return to.get_absolute_url() <NEW_LINE> <DEDENT> if isinstance(to, Promise): <NEW_LINE> <INDENT> to = force_text(to) <NEW_LINE> <DEDENT> if isinstance(to, six.string_types): <NEW_LINE> <INDENT> if any(to.st... | Return a URL appropriate for the arguments passed.
The arguments could be:
* A model: the model's `get_absolute_url()` function will be called.
* A view name, possibly with arguments: `urlresolvers.reverse()` will
be used to reverse-resolve the name.
* A URL, which will be returned as-is. | 625941ddd6c5a1020814435d |
def test_active_game_required(self): <NEW_LINE> <INDENT> now = settings.NOW() <NEW_LINE> with self.settings(NOW=lambda:now-timedelta(5)): <NEW_LINE> <INDENT> z = Player.objects.filter(user__email=ROB_ZOMBIE["email"]).get() <NEW_LINE> z.team = "Z" <NEW_LINE> z.save() <NEW_LINE> c = Client() <NEW_LINE> c.post(reverse("lo... | No one should access the feed page before the game has started. | 625941dd8da39b475bd65287 |
@general_bp.route("/registry/value", methods=['GET']) <NEW_LINE> def socfaker_registry_value(): <NEW_LINE> <INDENT> return { 'value': socfaker.registry.value } | A random registry key value
Returns:
str: A random registry key value
| 625941dd99fddb7c1c9de6a0 |
def __mul__(self, z): <NEW_LINE> <INDENT> if isinstance(z, Complex): <NEW_LINE> <INDENT> return Complex(self.__real * z.__real - self.__imag * z.__imag, self.__imag * z.__real + self.__real * z.__imag) <NEW_LINE> <DEDENT> if isinstance(z, int): <NEW_LINE> <INDENT> return Complex(self.__real * z, self.__imag * z) <NEW_L... | Overload of the * operator that works with Complex and int parameters
Input: z - number to multiply current with
Output: The Complex number representing the product
Raises: TypeError if multiplication cannot be performed due to operator types | 625941ddadb09d7d5db6ca9e |
def get_backend_from_coredata(builddir: Path) -> str: <NEW_LINE> <INDENT> backend = coredata.load(str(builddir)).get_builtin_option('backend') <NEW_LINE> assert isinstance(backend, str) <NEW_LINE> return backend | Gets `backend` option value from coredata | 625941dda8ecb033257d33dc |
def create_index_table(self, table_name, schema_file): <NEW_LINE> <INDENT> if self.mock: <NEW_LINE> <INDENT> mock_dynamodb2(self._create_index_table(table_name, schema_file)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> waiter = self._create_index_table(table_name, schema_file) <NEW_LINE> self.wait_table_create(table_... | Method to create DynamoDB index table | 625941dd3cc13d1c6d3c7689 |
def write(self, out_file, data_source='setrun.py'): <NEW_LINE> <INDENT> self.open_data_file(out_file,data_source) <NEW_LINE> for (name,value) in self.iteritems(): <NEW_LINE> <INDENT> self.data_write(name) | Write out all data files in this ClawData object | 625941ddeab8aa0e5d26de69 |
def post(self): <NEW_LINE> <INDENT> global temp <NEW_LINE> args = request.form <NEW_LINE> run = True if args['run'] == 'true' else False <NEW_LINE> if run: <NEW_LINE> <INDENT> temp.start() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> temp.stop() <NEW_LINE> <DEDENT> return Result(data="ok") | 控制计算的开始和停止
:return: | 625941dd15fb5d323cde0e24 |
def run(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> gtk.main() <NEW_LINE> <DEDENT> except KeyboardInterrupt: <NEW_LINE> <INDENT> self.on_keyboard_interrupt() | Starts the main loop of processing events checking for Control-C.
The default implementation checks wheter a Control-C is pressed,
then calls on_keyboard_interrupt().
Use this method for starting programs. | 625941dd4f6381625f114d4c |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, InvocationMetricsUnattended): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ | Returns true if both objects are equal | 625941ddbf627c535bc134e0 |
def acquire_bucket( self, rank: Rank, maybe_old_bucket: Optional[Bucket] = None ) -> Tuple[Optional[Bucket], int]: <NEW_LINE> <INDENT> remaining = self.nparts_lhs * self.nparts_rhs - len(self.done) <NEW_LINE> locked_entities_parts: Dict[Tuple[EntityName, Partition], Rank] = {} <NEW_LINE> for bucket, other_rank in self.... | Finds a (lhs, rhs) partition pair that has not already been acquired
this epoch, and where neither the lhs nor rhs partitions are currently
locked. Locks this lhs and rhs until `release_pair` is called. Will try
to find a pair that has the same lhs (if not, rhs) as old_bucket.
If no pair is available, returns None.
R... | 625941dd76e4537e8c351985 |
def convert_to_list(self): <NEW_LINE> <INDENT> xmoves = [] <NEW_LINE> omoves = [] <NEW_LINE> for i in range(3): <NEW_LINE> <INDENT> for j in range(3): <NEW_LINE> <INDENT> element = self.layout[i][j] <NEW_LINE> if element.character_type() == 'X': <NEW_LINE> <INDENT> xmoves.append(Game.convert_position((i, j))) <NEW_LINE... | Converts the board into a list in alternating [X, O] order
:return: the list of all moves done so far | 625941dde8904600ed9f2241 |
def identity_key(*args, **kwargs): <NEW_LINE> <INDENT> if args: <NEW_LINE> <INDENT> row = None <NEW_LINE> largs = len(args) <NEW_LINE> if largs == 1: <NEW_LINE> <INDENT> class_ = args[0] <NEW_LINE> try: <NEW_LINE> <INDENT> row = kwargs.pop("row") <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> ident = kwargs.p... | Generate "identity key" tuples, as are used as keys in the
:attr:`.Session.identity_map` dictionary.
This function has several call styles:
* ``identity_key(class, ident, identity_token=token)``
This form receives a mapped class and a primary key scalar or
tuple as an argument.
E.g.::
>>> identity_key(My... | 625941dd01c39578d7e7514c |
def addoptimscaling(project, **kwargs): <NEW_LINE> <INDENT> for optim in project.optims.values(): <NEW_LINE> <INDENT> if 'budgetscale' not in optim.objectives.keys(): <NEW_LINE> <INDENT> optim.objectives['budgetscale'] = [1.] <NEW_LINE> <DEDENT> <DEDENT> return None | Migration between Optima 2.1.8 and 2.1.9. | 625941dd07f4c71912b11795 |
def flip_card(): <NEW_LINE> <INDENT> global chosen_word <NEW_LINE> canvas.itemconfig(word_text, text=chosen_word["English"], fill="white") <NEW_LINE> canvas.itemconfig(title_text, text="English", fill="white") <NEW_LINE> canvas.itemconfig(bg_card, image=new_bg) | Function to flip the card to the English translation of the word on the screen | 625941dd66673b3332b923a2 |
def test_unroll_no_loop_var(tmpdir, capsys): <NEW_LINE> <INDENT> options = Options() <NEW_LINE> options.unroll_factor = 2 <NEW_LINE> os.chdir(str(tmpdir.mkdir("tmp"))) <NEW_LINE> make_dag.dag_of_files( options, [os.path.join(BASE_PATH, "uncontrolled_loop.f90")]) <NEW_LINE> result, _ = capsys.readouterr() <NEW_LINE> ass... | Check that we generate the expected DAG when we encounter a
loop for which we have no loop variable | 625941ddc432627299f04f59 |
def set_tradeable(self, tradeable): <NEW_LINE> <INDENT> pass | tradeable
domain object containing all cards that are tradeable | 625941ddfbf16365ca6f64d9 |
def __init__( self, dist: Union[Distribution, "BaseDistribution"], metadata_name: str, ) -> None: <NEW_LINE> <INDENT> self.dist = dist <NEW_LINE> self.metadata_name = metadata_name | :param dist: A Distribution object.
:param metadata_name: The name of the metadata being accessed
(can be "METADATA" or "PKG-INFO"). | 625941dd29b78933be1e59b8 |
def main(dfile): <NEW_LINE> <INDENT> with open(dfile, 'r') as f: <NEW_LINE> <INDENT> for l in f: <NEW_LINE> <INDENT> print(count_change(int(l.strip()))) <NEW_LINE> <DEDENT> <DEDENT> return 0 | Alternative reality
@param dfile: data file path
@type of dfile: str | 625941dd76d4e153a657ee43 |
def export_xml(self): <NEW_LINE> <INDENT> self.doc = minidom.Document() <NEW_LINE> root = self.doc.createElement('qtubesexport') <NEW_LINE> root.setAttribute('version', dbversion) <NEW_LINE> self.doc.appendChild(root) <NEW_LINE> for t in self.tables: <NEW_LINE> <INDENT> e = self.doc.createElement(t.name) <NEW_LINE> roo... | Create XML doc from DB data | 625941dde1aae11d1e749fcb |
def p_vobphrase_vobphrase_uphrase_rad(p): <NEW_LINE> <INDENT> p[0] = ['vobphrase',p[1][1],p[1][2]] | vobphrase : vobphrase uphrase SYN_RAD | 625941dd91af0d3eaac9bd2c |
def __init__(self, dbfile, logfile, interface, daemon=True): <NEW_LINE> <INDENT> import socket <NEW_LINE> try: <NEW_LINE> <INDENT> SimpleXMLRPCServer.__init__(self, interface, logRequests=False, allow_none=True) <NEW_LINE> <DEDENT> except socket.error: <NEW_LINE> <INDENT> ip=socket.gethostbyname(interface[0]) <NEW_LINE... | constructor | 625941dd6fece00bbac2da52 |
def test_to_dict_dynamic_relation(self): <NEW_LINE> <INDENT> person = self.LazyPerson(name='Lincoln') <NEW_LINE> self.session.add(person) <NEW_LINE> computer = self.LazyComputer(name='lixeiro') <NEW_LINE> self.session.add(computer) <NEW_LINE> person.computers.append(computer) <NEW_LINE> self.session.commit() <NEW_LINE>... | Tests that a dynamically queried relation is resolved when getting
the dictionary representation of an instance of a model. | 625941dd287bf620b61d3d73 |
def p_checked_statement(p): <NEW_LINE> <INDENT> pass | checked_statement : CHECKED block
| 625941dd379a373c97cfae57 |
def update_position_x1y1(self, pos): <NEW_LINE> <INDENT> self.x1, self.y1, self.rotation = pos <NEW_LINE> self.rotation -= 90 <NEW_LINE> self.rotation_rad = np.deg2rad(self.rotation) <NEW_LINE> c = np.cos(self.rotation_rad) <NEW_LINE> s = np.sin(self.rotation_rad) <NEW_LINE> self.x = self.x1 - c * -self.width / 2 <NEW_... | Update position based on x1, y1 and rotation, exists for the sensors. | 625941dd4a966d76dd551323 |
def boundingbox(shp,buff=0): <NEW_LINE> <INDENT> pts = shp.points <NEW_LINE> reved = zip(*pts[::-1]) <NEW_LINE> return [min(reved[0]) - buff, max(reved[0]) + buff, min(reved[1]) - buff, max(reved[1]) + buff] | returns coordinates of the smallest possible rectangular boundary about a shape | 625941dd24f1403a92600e75 |
def main(config_path): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(config_path) as handle: <NEW_LINE> <INDENT> config = json.load(handle) <NEW_LINE> mqtt_config = config.get("mqtt", {}) <NEW_LINE> misc_config = config.get("misc", {}) <NEW_LINE> sensors = config.get("sensors") <NEW_LINE> interval_ms = int(get... | main entry point, load and validate config and call generate | 625941ddd4950a0f3b08c65c |
@pytest.fixture(scope="function", name="helpers") <NEW_LINE> def fixture_helpers() -> Helpers: <NEW_LINE> <INDENT> return Helpers() | Return a test helper object | 625941ddde87d2750b8600a6 |
def _finish_prob_for_one_fiber(self, y, x, ildj, distribution_kwargs): <NEW_LINE> <INDENT> x = self._maybe_rotate_dims(x, rotate_right=True) <NEW_LINE> prob = self.distribution.prob(x, **distribution_kwargs) <NEW_LINE> if self._is_maybe_event_override: <NEW_LINE> <INDENT> prob = math_ops.reduce_prod(prob, self._reduce_... | Finish computation of prob on one element of the inverse image. | 625941dd82261d6c526ab7b4 |
def do_gzipped_json_to_sqs_batch(args): <NEW_LINE> <INDENT> write_thread = FilterQueueDictToJsonSqsBatchThread <NEW_LINE> dohelper_gzipped_json(args, write_thread) | Read file of JSON, print to AWS SQS batch. | 625941ddff9c53063f47c503 |
def get_asset_model(obj): <NEW_LINE> <INDENT> asset_tables = ['server','networkdevice','software'] <NEW_LINE> for asset_type in asset_tables: <NEW_LINE> <INDENT> if hasattr(obj,asset_type): <NEW_LINE> <INDENT> ass_obj = getattr(obj,asset_type) <NEW_LINE> return ass_obj.model | 匹配方法
:param obj:
:return: | 625941dd796e427e537b08d9 |
def StateToHex(state): <NEW_LINE> <INDENT> return hex(int("".join(state.T.reshape(-1)),2))[2:].zfill(32) | This function operates on a single full state and return the hex value of that state in a string
Inputs:
state: A polynmial np array of shape (4,4) with each element being a polynomial of 8 bits
Outputs:
hexValue: A string containing the hex value of that state. | 625941dd50812a4eaa59c630 |
def metaWeblog_editPost(request, postid, username, password, struct, publish): <NEW_LINE> <INDENT> logger = tools.getLogger() <NEW_LINE> logger.debug("editPost %s %s %s" % (postid, struct, publish)) <NEW_LINE> authenticate(request, username, password) <NEW_LINE> config = request.getConfiguration() <NEW_LINE> ping = con... | Edit an existing post
Part of the metaWeblog API
@param request: the pyblosxom Request instance
@type request: Request
@param username: the username
@type username: string
@param password: the password
@type password: string
@param struct: the metaWeblog api struct
@type struct: dict
@param publish: to publish... | 625941ddbde94217f36830ff |
def _format_keys(self, keys): <NEW_LINE> <INDENT> out = [] <NEW_LINE> for host_key in keys: <NEW_LINE> <INDENT> if self.args.format == "short": <NEW_LINE> <INDENT> out.append({host_key.hostname: host_key.fingerprint}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> out.append({ host_key.hostname: OrderedDict([ ("fingerpr... | Format keys for the CLI output.
:param keys: Keys to format.
:return: list of dicts with the key data per each. | 625941ddbe8e80087fb20f50 |
def confd_state_internal_callpoints_actionpoint_registration_type_range_range_default(self, **kwargs): <NEW_LINE> <INDENT> config = ET.Element("config") <NEW_LINE> confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring") <NEW_LINE> internal = ET.SubElement(confd_state, "intern... | Auto Generated Code
| 625941dd046cf37aa974d056 |
def truecolor(filepath): <NEW_LINE> <INDENT> import glob <NEW_LINE> import matplotlib.pyplot as plt <NEW_LINE> hico_files = glob.glob(filepath + '*.L1B_ISS') <NEW_LINE> for file in hico_files: <NEW_LINE> <INDENT> rgb_file = glob.glob(filepath + file[-22:-8] + '_rgb.png') <NEW_LINE> if not rgb_file: <NEW_LINE> <INDENT> ... | load_HICO.truecolor - Produces an rgb "truecolor" images
Version 1.0
Created on: May, 19, 2016
Last Modified: June, 14, 2017
Author: Logan Wright, logan.wright@colorado.edu
Description:
-Will produce a true color rgb image of all HICO L1B scenes in the given
filepath.
Inputs:
filepath = string, path to a ... | 625941ddcc40096d61595c60 |
@secret_key <NEW_LINE> def save_to_db(request): <NEW_LINE> <INDENT> from django.http import HttpResponse <NEW_LINE> return HttpResponse(str(stop-start), mimetype='text/plain') | Renders the stats | 625941dd67a9b606de4a81c8 |
def match_attr_list(self, name, tag, allow_empty=True, terminator=None): <NEW_LINE> <INDENT> from .cibconfig import cib_factory <NEW_LINE> xmlid = None <NEW_LINE> if self.try_match_idspec(): <NEW_LINE> <INDENT> if self.matched(1) == '$id-ref': <NEW_LINE> <INDENT> r = xmlutil.new(tag) <NEW_LINE> ref = cib_factory.resolv... | matches [$id=<id>] [<score>:] <n>=<v> <n>=<v> ... | $id-ref=<id-ref>
if matchname is False, matches:
<n>=<v> <n>=<v> ... | 625941dd7047854f462a1717 |
def addIdentifier(self,identifierName,identifierType,controlledBy,astNode,lineNum = None): <NEW_LINE> <INDENT> if(len(self.stack) <= 1): <NEW_LINE> <INDENT> errPrint('\nBehram Error. Cannot insert into type check stack because stack is empty.\n'); <NEW_LINE> assert(False); <NEW_LINE> <DEDENT> self.stack[-1].addIdentif... | @param {String} controlledBy --- name of the endpoint that is
authoritative for this variable if it's a shared variable.
None if it's not a shared variable or if no one is
authoritative for it. | 625941dd097d151d1a223169 |
def cleanup_ingredients(ingredients): <NEW_LINE> <INDENT> ingredients = regex_non_words.sub(' ', ingredients) <NEW_LINE> cleaned_ingredients = ' '.join(split_str_on_whitespace(ingredients)).strip() <NEW_LINE> return cleaned_ingredients | Remove non-word chars and produce str of words separated by single whitespace
:param ingredients(str)
:return ingredients(str) | 625941ddd486a94d0b98e458 |
def main(): <NEW_LINE> <INDENT> seq_line = sys.stdin.read() <NEW_LINE> print(count_nucleotide(seq_line)) | Takes sequence object and prints the counts in ACGT to console | 625941ddab23a570cc250496 |
def parse(template, _settings, content): <NEW_LINE> <INDENT> settings = DEFAULT_OPTIONS.copy() <NEW_LINE> settings.update(_settings) <NEW_LINE> assert "start" in settings, "Lines start regex missing" <NEW_LINE> assert "end" in settings, "Lines end regex missing" <NEW_LINE> assert "line" in settings, "Line regex missing... | Try to extract lines from the invoice | 625941ddd53ae8145f87a57c |
def Load_wav_file(feature_npy, label_npy): <NEW_LINE> <INDENT> features = np.load(feature_npy) <NEW_LINE> labels = np.load(label_npy) <NEW_LINE> return features, labels | :description: 从.npy文件中直接获取wav文件的mfcc特征和标签(这样比重新从wav文件中获取快很多)
:param feature_npy: wav文件的mfcc特征
:param label_npy: av文件的标签
:return: wav文件的mfcc特征和标签 | 625941dd3539df3088e2e65c |
def get_string_size(tensor): <NEW_LINE> <INDENT> split = tf.string_split(tf.reshape(tensor, [-1])) <NEW_LINE> return tf.shape(split)[1] | Get the number of tokens in a string sperated by space. | 625941dd15fb5d323cde0e25 |
def validate_fields(fields_in): <NEW_LINE> <INDENT> return (set(query_fields) & set(fields_in)) - set(query_class.fields_already_filtered) | Take the intersection between the fields requested and the
query_fields. Do not keep the fields that already have a more
complex filter on query.
Eg. {name, email, etc} & {name} -> {name} | 625941dd50485f2cf553d0ac |
def compute_P(A): <NEW_LINE> <INDENT> A = np.asarray(A) <NEW_LINE> A = A.T <NEW_LINE> P = np.full_like(A, 0) <NEW_LINE> for i in range(A.shape[0]): <NEW_LINE> <INDENT> s = float(sum(A[i])) <NEW_LINE> if s != 0: <NEW_LINE> <INDENT> P[i] = A[i] / s <NEW_LINE> <DEDENT> <DEDENT> P = np.asmatrix(P.T) <NEW_LINE> return P | compute the transition matrix P from addjacency matrix A. P[j][i] represents the probability of moving from node i to node j.
Input:
A: adjacency matrix, a (n by n) numpy matrix of binary values. If there is a link from node i to node j, A[j][i] =1. Otherwise A[j][i]=0 if there is no link.
Outpu... | 625941dd7047854f462a1718 |
def limits(self, key): <NEW_LINE> <INDENT> return np.nanmin(self.table[key]), np.nanmax(self.table[key]) | Return the range of values spanned by
a particular aspect of the relation. | 625941dde8904600ed9f2242 |
def __init__(self, id=None, server_id=None, url=None, alias=None, extension=None): <NEW_LINE> <INDENT> self._id = None <NEW_LINE> self._server_id = None <NEW_LINE> self._url = None <NEW_LINE> self._alias = None <NEW_LINE> self._extension = None <NEW_LINE> self.discriminator = None <NEW_LINE> self.id = id <NEW_LINE> if ... | VoicemailRefJson - a model defined in Swagger | 625941ddb545ff76a8914127 |
def __init__(self, params, name=None): <NEW_LINE> <INDENT> super(Transformer, self).__init__(name=name) <NEW_LINE> self.params = params <NEW_LINE> self.embedding_softmax_layer = embedding_layer.EmbeddingSharedWeights( params["vocab_size"], params["hidden_size"]) <NEW_LINE> self.encoder_stack = EncoderStack(params) <NEW... | Initialize layers to build Transformer model.
Args:
params: hyperparameter object defining layer sizes, dropout values, etc.
name: name of the model. | 625941dd85dfad0860c3b16d |
def extract(self, jsontext): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> json_dict = json.loads(jsontext) <NEW_LINE> return ierror.WXBizMsgCrypt_OK, json_dict['encrypt'] <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print(e) <NEW_LINE> return ierror.WXBizMsgCrypt_ParseJson_Error, None | 提取出json数据包中的加密消息
@param jsontext: 待提取的json字符串
@return: 提取出的加密消息字符串 | 625941dd92d797404e30449d |
def loadLightGeneTable(inputFile, fields) : <NEW_LINE> <INDENT> o = dict() <NEW_LINE> with open(inputFile, "r") as fi : <NEW_LINE> <INDENT> headers = fi.next().strip("#").strip().split("\t") <NEW_LINE> headers_i = [headers.index(f) for f in fields] <NEW_LINE> geneId_i = headers.index("geneId") <NEW_LINE> for l in fi : ... | Load a light version of a gene table, as a dict indexed by geneId
Args:
inputFile (str): Gene table file name
fields (list of str): List of fields to extract from the table
Returns:
dict: Mapping between geneId and a list of values corresponding to the
requested fields | 625941dd01c39578d7e7514d |
def trim_datas(imgs, lbls, trims, iou_thresh=0.7): <NEW_LINE> <INDENT> device = imgs.device <NEW_LINE> new_imgs, new_lbls = [], [] <NEW_LINE> for img, lbl, trim in zip(imgs, lbls, trims): <NEW_LINE> <INDENT> new_img = img.clone() <NEW_LINE> new_img[:, trim[1]:trim[3], trim[0]:trim[2]] = 0 <NEW_LINE> new_imgs.append(new... | trim data function
this function trims image and label data to exclude a certain specified
box. it will trim out label data if the iou of the portion of the bounding
box that lies within the trim and the whole bounding box exceeds the iou
threshold value.
--- args ---
imgs : torch.FloatTensor like (N, 3, y, x)
the... | 625941dd23e79379d52ee872 |
def get_manageable_volumes(self, cinder_volumes, marker, limit, offset, sort_keys, sort_dirs): <NEW_LINE> <INDENT> return [] | List volumes on the backend available for management by Cinder.
Returns a list of dictionaries, each specifying a volume in the host,
with the following keys:
- reference (dictionary): The reference for a volume, which can be
passed to "manage_existing".
- size (int): The size of the volume according to the storage
... | 625941dd8da39b475bd65288 |
def search(self, office): <NEW_LINE> <INDENT> if self.db.fetch_single_item('offices', office): <NEW_LINE> <INDENT> return True | This function returns True if an office was available for election | 625941dd5166f23b2e1a546b |
def glob(tgt): <NEW_LINE> <INDENT> matcher = salt.minion.Matcher(__opts__, __salt__) <NEW_LINE> try: <NEW_LINE> <INDENT> return matcher.glob_match(tgt) <NEW_LINE> <DEDENT> except Exception as exc: <NEW_LINE> <INDENT> log.exception(exc) <NEW_LINE> return False | Return True if the minion matches the given glob target
CLI Example:
.. code-block:: bash
salt '*' match.glob '*' | 625941ddd268445f265b5180 |
def _on_close(element): <NEW_LINE> <INDENT> (validated, message, element) = element.validate() <NEW_LINE> if not validated: <NEW_LINE> <INDENT> tmp = { 'identifier': element.identifier, 'value': element.value, 'message': message, } <NEW_LINE> dialog.error(_("Field '%(identifier)s ('%(value)s') not valid\n" "... | calidate the fields and display a dialog if something is not
valid and return False, if all validated, return True | 625941dd5fcc89381b1e19d2 |
def split_words(self, text: str) -> typing.Iterator[str]: <NEW_LINE> <INDENT> bare = remove_punctuations(text).lower() <NEW_LINE> split = word_tokenize(bare.lower(), language=self.language) <NEW_LINE> return split | List constituent words of `text` via tokenizer sequentially
Arguments:
sentence {str} -- text to split
Returns:
StringList -- words in text | 625941dd7d43ff24873a2fb3 |
def _enter(path, key, value): <NEW_LINE> <INDENT> if any([_(path, key, value) for _ in iter_attrs]): <NEW_LINE> <INDENT> included_attrs = [_ for _ in dir(value) if not _.endswith("__")] <NEW_LINE> included_attrs = sorted(included_attrs, reverse=True) <NEW_LINE> return dict(), [(_, getattr(value, _)) for _ in included_a... | If any in `iter_attrs` is True, enter `value` as a dict, iterating over non-magic
attributes. Else, `default_enter` | 625941dd60cbc95b062c6855 |
def get_remote_gateway_firewall_flag(self, gateway): <NEW_LINE> <INDENT> firewall = self._redis_server.get(hub_api.create_rocon_gateway_key(gateway, 'firewall')) <NEW_LINE> if firewall is not None: <NEW_LINE> <INDENT> return True if int(firewall) else False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise GatewayUna... | Returns the value of the remote gateway's firewall (flip)
flag.
@param gateway : gateway string id
@param string
@return state of the flag
@rtype Bool
@raise GatewayUnavailableError when specified gateway is not on the hub | 625941dd82261d6c526ab7b5 |
def children_with(self, property, value): <NEW_LINE> <INDENT> matches = [] <NEW_LINE> for c in self._children: <NEW_LINE> <INDENT> if getattr(c, property) == value: <NEW_LINE> <INDENT> matches.append(c) <NEW_LINE> <DEDENT> <DEDENT> return matches | Returns a list of child node references which have the value for the property. | 625941dd3346ee7daa2b307f |
def phi3(z): <NEW_LINE> <INDENT> return 6*(np.exp(z)-1-z-z**2/2)/z**3 | Computes RKETD psi-function of the third order.
INPUTS
z - real or complex-valued input array
OUTPUT
return 3!*(exp(z)-1-z/2-z^3/6)/z^3 -> real or complex-valued RKETD function of third order | 625941dd8a43f66fc4b54374 |
def video_identity_loss(top_out, targets, model_hparams, vocab_size, weights_fn): <NEW_LINE> <INDENT> del vocab_size <NEW_LINE> logits = top_out <NEW_LINE> logits = tf.reshape(logits, [-1] + common_layers.shape_list(logits)[2:]) <NEW_LINE> targets = tf.reshape(targets, [-1] + common_layers.shape_list(targets)[2:]) <NEW... | Compute loss numerator and denominator for one shard of output. | 625941dd442bda511e8be726 |
def CDATA(text=None): <NEW_LINE> <INDENT> element = Element('![CDATA[', namespace=None) <NEW_LINE> element.text = text <NEW_LINE> return element | Adds the capability to add CDATA elements to the XML.
| 625941dd3eb6a72ae02ec7f6 |
def load_file(self, filename, key, bucket_name=None, replace=False, encrypt=False): <NEW_LINE> <INDENT> if not bucket_name: <NEW_LINE> <INDENT> (bucket_name, key) = self.parse_s3_url(key) <NEW_LINE> <DEDENT> if not replace and self.check_for_key(key, bucket_name): <NEW_LINE> <INDENT> raise ValueError("The key {key} alr... | Loads a local file to S3
:param filename: name of the file to load.
:type filename: str
:param key: S3 key that will point to the file
:type key: str
:param bucket_name: Name of the bucket in which to store the file
:type bucket_name: str
:param replace: A flag to decide whether or not to overwrite the key
if it a... | 625941dd4f88993c3716c377 |
def kepler(inbigM, inecc): <NEW_LINE> <INDENT> Marr = inbigM <NEW_LINE> eccarr = inecc <NEW_LINE> conv = 1.0e-12 <NEW_LINE> k = 0.85 <NEW_LINE> Earr = Marr + np.sign(np.sin(Marr)) * k * eccarr <NEW_LINE> fiarr = ( Earr - eccarr * np.sin(Earr) - Marr) <NEW_LINE> convd = np.abs(fiarr) > conv <NEW_LINE> nd = np.sum(convd ... | Solve Kepler's Equation
Args:
inbigM (array): input Mean annomaly
inecc (array): eccentricity
Returns:
eccentric annomaly: array | 625941dd30dc7b7665901c75 |
def bulk(self, values, rows = None, list_type = False, show_link = True, include_blank = True, ): <NEW_LINE> <INDENT> show_link = show_link and self.show_link <NEW_LINE> if show_link and not rows: <NEW_LINE> <INDENT> rows = self.lookup_rows(None, values) <NEW_LINE> <DEDENT> self._setup() <NEW_LINE> if rows and self.tab... | Represent multiple values as dict {value: representation}
Args:
values: list of values
rows: the referenced rows (if values are foreign keys)
show_link: render each representation as link
include_blank: Also include a blank value
Returns:
dict {value: representation} | 625941ddd4950a0f3b08c65d |
def learn(self): <NEW_LINE> <INDENT> raise NotImplementedError | The main method, that invokes a learning step. | 625941dd32920d7e50b284e4 |
def _parse_schema_resource(info): <NEW_LINE> <INDENT> return [SchemaField.from_api_repr(f) for f in info.get("fields", ())] | Parse a resource fragment into a schema field.
Args:
info: (Mapping[str, Dict]): should contain a "fields" key to be parsed
Returns:
Optional[Sequence[google.cloud.bigquery.schema.SchemaField`]:
A list of parsed fields, or ``None`` if no "fields" key found. | 625941dd2eb69b55b151cbc5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.