code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def run_wsgi_app(application): <NEW_LINE> <INDENT> run_bare_wsgi_app(add_wsgi_middleware(application))
Runs your WSGI-compliant application object in a CGI environment. Compared to wsgiref.handlers.CGIHandler().run(application), this function takes some shortcuts. Those are possible because the app server makes stronger promises than the CGI standard. Also, this function may wrap custom WSGI middleware around the app...
625941cb1f037a2d8b9462c5
def test_basic_invalid_person(): <NEW_LINE> <INDENT> bob = Person("Bob B. Johnson") <NEW_LINE> bob.add_source(url='foo') <NEW_LINE> bob.validate() <NEW_LINE> bob.name = None <NEW_LINE> @raises(ValidationError) <NEW_LINE> def _(): <NEW_LINE> <INDENT> bob.validate() <NEW_LINE> <DEDENT> _()
Test that we can create an invalid person, and validation will fail
625941cbdc8b845886cb55fc
def check_team_rank(teamrank): <NEW_LINE> <INDENT> neededkeys = ( "id", "name", "coachTeamPoints", "points", "tdFor", "tdAgainst", "netTd", "casualtiesFor", "casualtiesAgainst", "netCasualties", "completionsFor", "completionsAgainst", "netCompletions", "foulsFor", "foulsAgainst", "netFouls", "opponentIdArray", "opponen...
Test <teamrank> if a valid team rank
625941cbf548e778e58cd645
def collect_data(args): <NEW_LINE> <INDENT> app_profiler_args = [sys.executable, os.path.join(SCRIPTS_PATH, "app_profiler.py"), "-nb"] <NEW_LINE> if args.app: <NEW_LINE> <INDENT> app_profiler_args += ["-p", args.app] <NEW_LINE> <DEDENT> elif args.native_program: <NEW_LINE> <INDENT> app_profiler_args += ["-np", args.nat...
Run app_profiler.py to generate record file.
625941cbcc40096d61595a18
def test_is_valid(self): <NEW_LINE> <INDENT> numbers = [ '1234567890', '123-456-7890', '123.456.7890', '(123)456-7890', '(123) 456-7890', '456-7890', '123-45-6789', '123:4567890', '123/456-7980', ] <NEW_LINE> result = [phonenumber.PhoneNumber(nr).is_valid() for nr in numbers] <NEW_LINE> expected = [True]*6 + [False]*3 ...
Test method :meth:`plugins.phonenumber.PhoneNumber.is_valid` **Tested:** - The returned boolean correctly indicates a phone number's validity.
625941cb3617ad0b5ed67fbf
def get_queryset(self): <NEW_LINE> <INDENT> return super(SubscriptionTypeManager, self).get_queryset().select_related('status')
Prefetch foreign key status
625941cb0a366e3fb873e8e2
@user_log(log=True) <NEW_LINE> def list_leases(caller_id, network_id): <NEW_LINE> <INDENT> user = User.get(caller_id) <NEW_LINE> try: <NEW_LINE> <INDENT> user_network = UserNetwork.objects.filter(user=user).get(id=network_id) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise CMException('network_not_found') <NEW_LI...
Returns all Leases in specified UserNetwork @cmview_user @param_post{network_id} id of the UserNetwork which Leases should be listed from @response{list(dict)} Lease.dict property for each Lease in specified UserNetwork
625941cb26238365f5f0ef35
def get_file_format(self): <NEW_LINE> <INDENT> if self._file_fmt is not None: <NEW_LINE> <INDENT> return self._file_fmt <NEW_LINE> <DEDENT> desc = AudioStreamBasicDescription() <NEW_LINE> size = ctypes.c_int(ctypes.sizeof(desc)) <NEW_LINE> check(_coreaudio.ExtAudioFileGetProperty( self._obj, PROP_FILE_DATA_FORMAT, ctyp...
Get the file format description. This describes the type of data stored on disk.
625941cbbaa26c4b54cb11e8
def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.axes = [] <NEW_LINE> for key in kwargs: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> setattr(self, key, epics.Motor(kwargs[key])) <NEW_LINE> self.axes.append(key) <NEW_LINE> <DEDENT> except MotorException: <NEW_LINE> <INDENT> setattr(self, key, epics.PV(kwargs[key]...
keywords should be name=epics_motor_pv
625941cb187af65679ca51e6
def __init__(self, xid=None, vendor=None): <NEW_LINE> <INDENT> super().__init__(xid) <NEW_LINE> self.vendor = vendor
The constructor takes the parameters below. Args: xid (int): xid to be used on the message header. vendor (int): Vendor ID: MSB 0: low-order bytes are IEEE OUI. MSB != 0: defined by OpenFlow consortium.
625941cb6e29344779a626da
def itkMinimumMaximumImageCalculatorIUL3_cast(*args): <NEW_LINE> <INDENT> return _itkMinimumMaximumImageCalculatorPython.itkMinimumMaximumImageCalculatorIUL3_cast(*args)
itkMinimumMaximumImageCalculatorIUL3_cast(itkLightObject obj) -> itkMinimumMaximumImageCalculatorIUL3
625941cb0fa83653e4657083
def copy_citation(dst_path): <NEW_LINE> <INDENT> citation_path = os.path.join(dst_path, "citation.json") <NEW_LINE> if os.path.isfile(citation_path): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> log(f"Copying citation to {citation_path}") <NEW_LINE> now = time.localtime() <NEW_LINE> data = [ { "id": "https://www2.cen...
Write citation.json
625941cbb830903b967e99d3
def incluirRawY(self,Incluir): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> Incluir=bool(Incluir) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> raise Exception(e) <NEW_LINE> <DEDENT> self.__Yu=Incluir
!
625941cb7d847024c06be383
def min_value(self,gameState,depth): <NEW_LINE> <INDENT> if self.time_left() < self.TIMER_THRESHOLD: <NEW_LINE> <INDENT> raise SearchTimeout() <NEW_LINE> <DEDENT> if self.cut_off_test(gameState,depth): <NEW_LINE> <INDENT> return self.score(gameState,self) <NEW_LINE> <DEDENT> legal_moves = gameState.get_legal_moves() <N...
Return the value for a win (+1) if the game is over, otherwise return the minimum value over all legal child nodes.
625941cbcb5e8a47e48b7b73
def read_grid_function(open_file, mesh): <NEW_LINE> <INDENT> return GridFunction(np.genfromtxt(open_file, skip_header=5), mesh)
Reads a grid function from opened mfem grid_function file and maps it to mesh. Use: with open(filename) as f: read_grid_function(f, mesh) :param mesh: :param open_file: :return: GridFunction
625941cb82261d6c526ab566
def dragdrop(self, fitsimage, urls): <NEW_LINE> <INDENT> for url in urls: <NEW_LINE> <INDENT> to_chname = self.get_channelName(fitsimage) <NEW_LINE> if self._is_thumb(url): <NEW_LINE> <INDENT> self.move_image_by_thumb(url, to_chname) <NEW_LINE> continue <NEW_LINE> <DEDENT> self.nongui_do(self.load_file, url, chname=to_...
Called when a drop operation is performed on our main window. We are called back with a URL and we attempt to load it if it names a file.
625941cbf8510a7c17cf97c4
@app.route("/api/skill/set_weight/<int:project_id>/<skill_name>/<weight>") <NEW_LINE> def set_skill_weight(project_id, skill_name, weight): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> weight = max(0.0, min(5.0, float(weight))) <NEW_LINE> weighted_skill_obj = Weighted_Skill(project_id, database.get_skill_by_name(skill_...
Sets the skill weight for a project with a certain skill. @param project_id: Project ID. @type project_id: C{int} @param skill_name: The skill name. @type skill_name: C{str} @param weight: Skill weight, which will be bounded between 0.0 and 5.0. @type weight: C{float} @return: The skill weight object as JSON, or an err...
625941cb460517430c39424e
def __abs__(self): <NEW_LINE> <INDENT> return math.hypot(self.x, self.y)
Return the vector's magnitude.
625941cb15fb5d323cde0bd7
def testSort2(self): <NEW_LINE> <INDENT> self.assertRowsEqual(self.ROW0, self._table[0]) <NEW_LINE> self.assertRowsEqual(self.ROW1, self._table[1]) <NEW_LINE> self.assertRowsEqual(self.ROW2, self._table[2]) <NEW_LINE> def sorter(row): <NEW_LINE> <INDENT> return (row[self.COL0], row[self.COL1]) <NEW_LINE> <DEDENT> self....
Test multiple key sort.
625941cb435de62698dfdd14
def set_termination_func(self, termination_func): <NEW_LINE> <INDENT> self.termination_func = termination_func <NEW_LINE> if termination_func and not self.tail_thread: <NEW_LINE> <INDENT> self._start_thread()
Set the termination_func attribute. See __init__() for details. :param termination_func: Function to call when the process terminates. Must take a single parameter -- the exit status.
625941cb3539df3088e2e413
def countSmaller(self, nums): <NEW_LINE> <INDENT> def mergeList(list1, list2): <NEW_LINE> <INDENT> res = [] <NEW_LINE> idx1, idx2, add_count = 0, 0, 0 <NEW_LINE> while idx1 < len(list1) or idx2 < len(list2): <NEW_LINE> <INDENT> v1 = list1[idx1][0] if idx1 < len(list1) else float('inf') <NEW_LINE> v2 = list2[idx2][0] if...
:type nums: List[int] :rtype: List[int]
625941cb67a9b606de4a7f82
def AddMacros(self, macros): <NEW_LINE> <INDENT> for name, callback in macros.items(): <NEW_LINE> <INDENT> self.AddMacro(name, callback)
Adds some macros to this context. Args: macros: (string -> callable dict) The macros to add.
625941cb1f037a2d8b9462c6
def drawBackground( self, painter, rect ): <NEW_LINE> <INDENT> if ( self._dirty ): <NEW_LINE> <INDENT> self.rebuild() <NEW_LINE> <DEDENT> if ( self.showGrid() ): <NEW_LINE> <INDENT> self.drawGrid(painter)
Draws the backgrounds for the different chart types. :param painter | <QPainter> rect | <QRect>
625941cb8c3a873295158482
def __init__(self, settings, data): <NEW_LINE> <INDENT> self.settings = settings <NEW_LINE> self.data = data <NEW_LINE> self.init_printer() <NEW_LINE> self.create_fonts() <NEW_LINE> self.preview()
:param yaml_file: yaml file with report configuration data :param data: Actual data to be reported
625941cba8ecb033257d3195
def __FillDisks__(self): <NEW_LINE> <INDENT> sDiskIDs = set([]) <NEW_LINE> lAllDisks = [l.strip() for l in self.__sFromArray__('lsdrive -bytes -delim {}'.format(SEP)).split('\n') if len(l.strip()) > 0] <NEW_LINE> sHdr = lAllDisks.pop(0) <NEW_LINE> oDisksTable = TabbedValues(sHdr) <NEW_LINE> for sDsk in lAllDisks: <NEW_...
Fills list of disks
625941cb435de62698dfdd15
def __resolve_default_lang_args(self): <NEW_LINE> <INDENT> if self.type in HeavyLangObject._HEAVY_LANG_DICT: <NEW_LINE> <INDENT> for arg in self._obj_desc["args"]: <NEW_LINE> <INDENT> if arg["name"] not in self.args: <NEW_LINE> <INDENT> if not arg["required"]: <NEW_LINE> <INDENT> self.args[arg["name"]] = arg["default"]...
Resolves missing default arguments. Also checks to make sure that all required arguments are present. Does nothing if the object is IR.
625941cbb545ff76a8913edf
def current(self, setCurrent = 'None'): <NEW_LINE> <INDENT> initialPortState = self.portOpen <NEW_LINE> if initialPortState == False: <NEW_LINE> <INDENT> self.openPort() <NEW_LINE> <DEDENT> if setCurrent != 'None': <NEW_LINE> <INDENT> setCurrent *= 1e3 <NEW_LINE> current=str('%05.1f' % setCurrent) <NEW_LINE> out = self...
If no arguments are passed this function queries the current and returns it. otherwise it will try to set the current of the powersupply and return a None type. This is very similar to the voltage() function but has slightly differet formatting. The current is set in AMPS with four digits after the decimal (minimum pr...
625941cb6fb2d068a760f165
def was_pressed(self): <NEW_LINE> <INDENT> return self.__wasPressed
Checks to see if this button was pressed. :return: True if the button was pressed, false if not.
625941cb29b78933be1e5775
def __init__(self, parent, d): <NEW_LINE> <INDENT> self._base_diagram = tuple(sorted(tuple(sorted(i)) for i in d)) <NEW_LINE> super(AbstractPartitionDiagram, self).__init__(parent, self._base_diagram)
Initialize ``self``. EXAMPLES:: sage: import sage.combinat.diagram_algebras as da sage: pd = da.AbstractPartitionDiagrams(2) sage: pd1 = da.AbstractPartitionDiagram(pd, ((-2,-1),(1,2)) )
625941cbadb09d7d5db6c858
def __init__(self, board): <NEW_LINE> <INDENT> super().__init__(board) <NEW_LINE> self.states = [] <NEW_LINE> self.states.append(self.board.string_repr())
Initialize the board, the stack, the archive, and the string representation of the parent board.
625941cbd7e4931a7ee9dfe6
def getReplicasForJobs(self, lfns, diskOnly=False, printOutput=False): <NEW_LINE> <INDENT> ret = self._checkFileArgument(lfns, "LFN") <NEW_LINE> if not ret["OK"]: <NEW_LINE> <INDENT> return ret <NEW_LINE> <DEDENT> lfns = ret["Value"] <NEW_LINE> start = time.time() <NEW_LINE> dm = DataManager() <NEW_LINE> repsResult = d...
Obtain replica information from file catalogue client. Input LFN(s) can be string or list. Example usage: >>> print dirac.getReplicasForJobs('/lhcb/data/CCRC08/RDST/00000106/0000/00000106_00006321_1.rdst') {'OK': True, 'Value': {'Successful': {'/lhcb/data/CCRC08/RDST/00000106/0000/00000106_00006321_1.rdst': {'CERN-RD...
625941cb26068e7796caeda7
def _inferSchema(self, rdd: RDD, samplingRatio: Optional[float] = None) -> StructType: <NEW_LINE> <INDENT> return self.sparkSession._inferSchema(rdd, samplingRatio)
Infer schema from an RDD of Row or tuple. Parameters ---------- rdd : :class:`RDD` an RDD of Row or tuple samplingRatio : float, optional sampling ratio, or no sampling (default) Returns ------- :class:`pyspark.sql.types.StructType`
625941cb925a0f43d2549f3f
def find_ge(self, k): <NEW_LINE> <INDENT> j = self._find_index(k, 0, len(self._table) - 1) <NEW_LINE> if j < len(self._table): <NEW_LINE> <INDENT> return (self._table[j]._key, self._table[j]._value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None
Return (k, v) pair with least key >= k.
625941cb1f5feb6acb0c4c1a
def process_concert_cuts_cfg(concertcuts, configuration): <NEW_LINE> <INDENT> err_invalid_variable = _( ) % concertcuts <NEW_LINE> err_invalid_segment_number = _( ) % concertcuts <NEW_LINE> err_invalid_segment_filename = _( ) % concertcuts <NEW_LINE> err_invalid_format = _( ) % concertcuts <NEW_LINE> configuration[...
Input variables from a segment.cfg file used to specify "-C" Concert Cut variables return nothing
625941cb8c3a873295158483
def p_cespecial(p): <NEW_LINE> <INDENT> pass
Cespecial : BackBackForward | DownDownUp
625941cb23e79379d52ee62d
def renameTag(self, oldTag, newTag): <NEW_LINE> <INDENT> self.stub.RenameTag( host_pb2.HostRenameTagRequest(host=self.data, old_tag=oldTag, new_tag=newTag), timeout=Cuebot.Timeout)
Renames a tag. :type oldTag: str :param oldTag: The old tag to rename :type newTag: str :param newTag: The new name for the tag
625941cb7cff6e4e81117a4e
def _get_z(dsr, zeta=None, h=None, vgrid='r', hgrid='r', vtrans=None, tindex=None): <NEW_LINE> <INDENT> ds = dsr if tindex is None else dsr.isel(t=tindex) <NEW_LINE> N = len(ds['s_r']) <NEW_LINE> hc = ds.hc <NEW_LINE> _h = ds.h if h is None else h <NEW_LINE> _zeta = ds.ssh if zeta is None else zeta <NEW_LINE> _h = _h.f...
compute vertical coordinates zeta should have the size of the final output vertical coordinate is first in output
625941cb91f36d47f21ac5bb
def enable_btnSave(self): <NEW_LINE> <INDENT> self.btnSave.state(["!disabled"]) <NEW_LINE> self.controller.get_frame(puc.Main).btnSave.state(["!disabled"])
Enables button `Save`.
625941cb2c8b7c6e89b35889
def findBiases(self, night): <NEW_LINE> <INDENT> match = night.find( wordstolookfor = self.wordstosearchfor['bias'], placetolook = self.keytosearch) <NEW_LINE> return match
Identify the bias exposures.
625941cb1b99ca400220ab7a
def test_comment(self): <NEW_LINE> <INDENT> self.assertEqual(self.troe.comment, self.comment)
Test that the Troe comment property was properly set.
625941cb596a897236089b89
def mark_as_duplicate(self, duplicated_cid, master_cid, msg=''): <NEW_LINE> <INDENT> content_id_from = self.get_post(duplicated_cid)["id"] <NEW_LINE> content_id_to = self.get_post(master_cid)["id"] <NEW_LINE> params = { "cid_dupe": content_id_from, "cid_to": content_id_to, "msg": msg } <NEW_LINE> return self._rpc.conte...
Mark the post at ``duplicated_cid`` as a duplicate of ``master_cid`` :type duplicated_cid: int :param duplicated_cid: The numeric id of the duplicated post :type master_cid: int :param master_cid: The numeric id of an older post. This will be the post that gets kept and ``duplicated_cid`` post will be concatinat...
625941cb55399d3f0558877c
def day_to_full_date(d:str): <NEW_LINE> <INDENT> return "{} 00:00:00".format(d)
Convert a day str 'yyyy-mm-dd' to a full date str 'yyyy-mm-dd 00:00:00' :param d: 'yyyy-mm-dd' :return: 'yyyy-mm-dd 00:00:00'
625941cbb830903b967e99d4
def load_build(self, print_error: bool) -> BuildEnviroment: <NEW_LINE> <INDENT> return load_build_from_file(self.get_path_to_settings(), print_error)
load the build environment from the settings file
625941cbf9cc0f698b1406c4
def __save_df(self, path, df, file_name): <NEW_LINE> <INDENT> params = { 'csv': {'encoding': 'utf-8', 'sep': ',', 'index': False}, 'json': {'orient': 'records'} } <NEW_LINE> write_methods = {"csv": df.to_csv, "json": df.to_json} <NEW_LINE> kwargs = params[self.file_type] <NEW_LINE> write_method = write_methods[self.fil...
Salva um objeto DataFrame Params: path (pathlib.Pah): caminho onde o arquivo deve ser salvo df (DataFrame): objeto DataFrame file_name (str): nome do arquivo
625941cb7047854f462a14d3
def check_feed_info( feed: "Feed", *, as_df: bool = False, include_warnings: bool = False ) -> List: <NEW_LINE> <INDENT> table = "feed_info" <NEW_LINE> problems = [] <NEW_LINE> if feed.feed_info is None: <NEW_LINE> <INDENT> return problems <NEW_LINE> <DEDENT> f = feed.feed_info.copy() <NEW_LINE> problems = check_for_re...
Analog of :func:`check_agency` for ``feed.feed_info``.
625941cb442bda511e8be4e1
def load_jquery(self, force=False): <NEW_LINE> <INDENT> jscode = '' <NEW_LINE> if self.embed_jquery or force: <NEW_LINE> <INDENT> if not self.is_jquery_loaded(): <NEW_LINE> <INDENT> jscode += self.jquery <NEW_LINE> if self.want_compat or (self.jslib != '$'): <NEW_LINE> <INDENT> jscode += "\nvar %s = jQuery.noConflict()...
Load jquery in the current frame
625941cb50485f2cf553ce62
def on_action_basic_problem(self): <NEW_LINE> <INDENT> problem_type = 'basic' <NEW_LINE> if self.set_output_dir(problem_type): <NEW_LINE> <INDENT> self.common_solver_setup(problem_type) <NEW_LINE> self.centralWidget.add_basic_problem_tabs() <NEW_LINE> self.set_toolbar_solve_actions() <NEW_LINE> self.action_solve.setTex...
slot for action basic problem signal prepares all necesities for basic solver problem
625941cb76d4e153a657ebf9
def update_indexes(document): <NEW_LINE> <INDENT> warnings = [] <NEW_LINE> eval_dict = {} <NEW_LINE> document_metadata_dict = dict([(metadata.metadata_type.name, metadata.value) for metadata in document.metadata.all() if metadata.value]) <NEW_LINE> eval_dict['document'] = document <NEW_LINE> eval_dict['metadata'] = Met...
Update or create all the index instances related to a document
625941cb4e696a04525c9514
def Execute(self, request, timeout, metadata=None, with_call=False, protocol_options=None): <NEW_LINE> <INDENT> raise NotImplementedError()
Executes a command on the worker, returning the latencies of the operations. Since some commands consist of multiple operations (i.e. pulls contain many received messages with different end to end latencies) a single command can have multiple latencies returned.
625941cbcc0a2c11143dcf59
def test_page_title_is_community_name(self): <NEW_LINE> <INDENT> self.assertTitleEquals(self.darmok.title)
The page's title should the Community's Name.
625941cb5fdd1c0f98dc02fc
def player_game_shot_chart(game_id, team_id, player_id): <NEW_LINE> <INDENT> endpoint = 'http://stats.nba.com/stats/shotchartdetail' <NEW_LINE> payload = { "LeagueID": "00", "Season": "2014-15", "SeasonType": "Regular Season", "TeamID": team_id, "PlayerID": player_id, "GameID": game_id, "Outcome": None, "Location": Non...
return player tracking information for a given game args: game_id (int) #TODO get team_id from player_id team_id (int) player_id (int) returns: shots (list): shots a player attempted during a game each player is a dict with the following available keys ["GRID_TYPE","GAME_ID","GAME_EVENT_ID","PLAYER...
625941cbeab8aa0e5d26dc20
def find_usable_exits(room, stuff): <NEW_LINE> <INDENT> usable = [] <NEW_LINE> for exit in room['exits']: <NEW_LINE> <INDENT> if exit.get("hidden", False): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> usable.append(exit) <NEW_LINE> <DEDENT> return usable
Given a room, and the player's stuff, find a list of exits that they can use right now. That means the exits must not be hidden, and if they require a key, the player has it. RETURNS - a list of all exits that are visible (not hidden)
625941cba79ad161976cc20e
def __init__(self, nodes, base, graph, async_order=None): <NEW_LINE> <INDENT> super().__init__(nodes, graph, async_order=async_order) <NEW_LINE> self.base = base <NEW_LINE> lambdas_probabilities, lambdas = get_fuzzy_lambdas(min,max,lambda x:1-x) <NEW_LINE> self.lambdas_probabilities = lambdas_probabilities <NEW_LINE> s...
Create a Fuzzy Boolean Network with n nodes and base b. The structure of the networks is given by graph. Input: n (number of nodes), b (fuzzy base), graph (structure of the network)
625941cbf9cc0f698b1406c5
def test_get_keywords(): <NEW_LINE> <INDENT> keywords = get_keywords('Gorilla Glue') <NEW_LINE> assert 'gorilla' in keywords and 'glue' in keywords
Test get keywords.
625941cb498bea3a759b9b78
def _create_mock_oai_xsl_template(): <NEW_LINE> <INDENT> mock_oai_xsl_template = Mock(spec=OaiXslTemplate) <NEW_LINE> return mock_oai_xsl_template
Return a mock Oai XSL Template Returns:
625941cb97e22403b379d062
def romrom(word): <NEW_LINE> <INDENT> word = normalize_double_n(word) <NEW_LINE> word = hk_re.sub(lambda m: m.groups()[0] + romroms[m.groups()[1]], word) <NEW_LINE> return word
romrom(string) -> string Normalizes romaji string into hepburn. >>> romrom('kannzi') 'kanji' >>> romrom('hurigana') 'furigana' >>> romrom('utukusii') 'utsukushii' >>> romrom('tiezo') 'chiezo'
625941cbd486a94d0b98e20e
def magnitude(self): <NEW_LINE> <INDENT> return distance((self.x, self.y), (0,0))
magnitude of this vector)
625941cb566aa707497f4632
def notify_message_observers(self, message, *args, **opts): <NEW_LINE> <INDENT> if not self.notification_enabled: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> observers = self.message_observers.get(message, ()) <NEW_LINE> for method in observers: <NEW_LINE> <INDENT> method(*args, **opts)
Pythonic signals and slots.
625941cb60cbc95b062c660c
def __init__(self, device_id, setup_sim, update_sim, output_var_shape): <NEW_LINE> <INDENT> self.device_id = device_id <NEW_LINE> self.setup_sim = setup_sim <NEW_LINE> self.update_sim = update_sim <NEW_LINE> self._shared_output_var = Array( ctypes.c_double, int(np.prod(output_var_shape))) <NEW_LINE> self._output_var = ...
Args: - device_id (int): GPU device to use for rendering (0-indexed) - setup_sim (callback): callback that is given a device_id and returns a MjSim. It is responsible for making MjSim render to given device. - update_sim (callback): callback given a sim and device_id, and should return a numpy array of shap...
625941cb377c676e91272272
def __init__(self, dim, kxx, kyy=None, kzz=None, kxy=None, kxz=None, kyz=None): <NEW_LINE> <INDENT> if dim > 3 or dim < 0: <NEW_LINE> <INDENT> raise ValueError('Dimension should be between 1 and 3') <NEW_LINE> <DEDENT> self.dim = dim <NEW_LINE> Nc = kxx.size <NEW_LINE> perm = np.zeros((3, 3, Nc)) <NEW_LINE> if not np.a...
Initialize permeability Parameters: dim (int): Dimension, should be between 1 and 3. kxx (double): Nc array, with cell-wise values of kxx permeability. kyy (optional, double): Nc array of kyy. Default equal to kxx. kzz (optional, double): Nc array of kzz. Default equal to kxx. Not used if dim <...
625941cb656771135c3eb937
def userName(self) -> str: <NEW_LINE> <INDENT> return self.latest_revision.user
Return name or IP address of last user to edit page.
625941cb627d3e7fe0d68f18
def searchTitle(self, title, pagenumber, pagelen): <NEW_LINE> <INDENT> if 1 == pagenumber: <NEW_LINE> <INDENT> pagenumber = "" <NEW_LINE> <DEDENT> result = self.getSearchResults(title, pagenumber, pagelen) <NEW_LINE> if not result: <NEW_LINE> <INDENT> raise YouTubeVideoNotFound("No YouTube Video matches found for searc...
Key word video search of the YouTube web site return an array of matching item dictionaries return
625941cb442bda511e8be4e2
@collectorsdb.retryOnTransientErrors <NEW_LINE> def queryLastEmittedNonMetricSequence(key): <NEW_LINE> <INDENT> sel = sql.select([schema.emittedNonMetricTracker.c.last_seq]).where( schema.emittedNonMetricTracker.c.key == key) <NEW_LINE> return collectorsdb.engineFactory().execute(sel).scalar()
:param str key: caller's key in schema.emittedNonMetricTracker :returns: last emitted sequence number for non-metric source; None if one hasn't been saved yet. :rtype: int if not None
625941cb01c39578d7e74f04
def deleteIngestJob(self, job_id): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ingest_job = NDIngestJob.fromId(job_id) <NEW_LINE> nd_proj = NDIngestProj(ingest_job.project, ingest_job.channel, ingest_job.resolution) <NEW_LINE> UploadQueue.deleteQueue(nd_proj, endpoint_url=ndingest_settings.SQS_ENDPOINT) <NEW_LINE> Ing...
Delete an ingest job based on job id
625941cb73bcbd0ca4b2c13f
def get_data(self, current_datetime: Optional[datetime] = None): <NEW_LINE> <INDENT> seconds = self._seconds_since_init(current_datetime) <NEW_LINE> if (self.dead_frequency != 0) and ( seconds % (1 / self.dead_frequency) < self.dead_period ): <NEW_LINE> <INDENT> return 0.0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ...
Get the data including the noise. :param current_datetime: Use given timestamp of initialization of generator.
625941cb63f4b57ef00011e3
def get_lookup_info(self, request_info, lookup_file=None, namespace="lookup_editor", **kwargs): <NEW_LINE> <INDENT> return { 'payload': str(lookup_file), 'status': 200 }
Get information about a lookup file (owner, size, etc.)
625941cba17c0f6771cbe119
def _name_default(self): <NEW_LINE> <INDENT> name = camel_case_to_words(type(self).__name__) <NEW_LINE> logger.warning( "plugin {} has no name - using <{}>".format( object.__repr__(self), name) ) <NEW_LINE> return name
Trait initializer.
625941cb8e7ae83300e4b095
def __init__(self, source=None, source_path=None, encoding=None, error_handler='strict', autoclose=True, mode='rU', **kwargs): <NEW_LINE> <INDENT> Input.__init__(self, source, source_path, encoding, error_handler) <NEW_LINE> self.autoclose = autoclose <NEW_LINE> self._stderr = ErrorOutput() <NEW_LINE> for key in kwargs...
:Parameters: - `source`: either a file-like object (which is read directly), or `None` (which implies `sys.stdin` if no `source_path` given). - `source_path`: a path to a file, which is opened and then read. - `encoding`: the expected text encoding of the input file. - `error_handler`: the encodin...
625941cb236d856c2ad448a3
def set_array_storage(self, arr, array_storage): <NEW_LINE> <INDENT> block = self.blocks[arr] <NEW_LINE> self.blocks.set_array_storage(block, array_storage)
Set the block type to use for the given array data. Parameters ---------- arr : numpy.ndarray The array to set. If multiple views of the array are in the tree, only the most recent block type setting will be used, since all views share a single block. array_storage : str Must be one of: - ``inte...
625941cb956e5f7376d70f37
def __cmp__(self, other): <NEW_LINE> <INDENT> if self is other: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> if not isinstance(other, free_module.FreeModule_generic): <NEW_LINE> <INDENT> return cmp(type(self), type(other)) <NEW_LINE> <DEDENT> if isinstance(other, free_module.FreeModule_ambient): <NEW_LINE> <INDENT>...
Compare self and other. Modules are ordered by their ambient spaces, then by dimension, then in order by their echelon matrices. EXAMPLES: We compare rank three free modules over the integers and rationals:: sage: QQ^3 < CC^3 True sage: CC^3 < QQ^3 False sage: CC^3 > QQ^3 True sage: Q = ...
625941cb3c8af77a43ae3869
def __lt__(self, other): <NEW_LINE> <INDENT> return self.size < other.size
Overridden '<' operator. The comparison is based on the size of the entry and allows for instances to be sorted.
625941cb4e4d5625662d44a1
def display_dfs(dfs, return_df=False, axis=1, formatters=None, style_class=None): <NEW_LINE> <INDENT> dfs = map(lambda df: df.reset_index(drop=True), dfs) <NEW_LINE> df = pd.concat(dfs, axis=axis) <NEW_LINE> return display_or_return_df(df, return_df=return_df, style_class=style_class, formatters=formatters)
여러개의 DataFrame 을 묶어서 화면에 보여준다. note. 강제로 concat 하기 위해서 index 를 초기화한다. Parameters ---------- dfs : list-like of DataFrame return_df : boolean * true : display 하지 않고 DataFrame 을 반환한다. * false : display 하고 None 을 반환한다. axis : {0, 1}
625941cbde87d2750b85fe5c
def post_listing_to_slack(sc, listing, slack_channel): <NEW_LINE> <INDENT> if listing["price"] is None: <NEW_LINE> <INDENT> listing["price"] = "Free" <NEW_LINE> <DEDENT> print(listing["url"].find('zip',0,len(listing["url"]))) <NEW_LINE> if listing["url"].find('zip',0,len(listing["url"])) != -1: <NEW_LINE> <INDENT> desc...
Posts the listing to slack. :param sc: A slack client. :param listing: A record of the listing.
625941cb6e29344779a626db
def mean_portion_answers_correct(self, field): <NEW_LINE> <INDENT> if self.any_occurs[field] > 0: <NEW_LINE> <INDENT> return float(sum(self.occurs_correct_pqp[field])) / self.any_occurs[field] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 0
Return average % of answers per question carrying the feature that are correct. This counts only questions where the feature has been generated for some answer.
625941cbb5575c28eb68e0c9
def test_dimension_deletion_forward(self, trials): <NEW_LINE> <INDENT> new_param = Trial.Param(name='second_normal_prior', type='integer', value=1) <NEW_LINE> dimension_deletion_adapter = DimensionDeletion(new_param) <NEW_LINE> sampler = DimensionBuilder().build('random', 'uniform(10, 100, discrete=True)') <NEW_LINE> f...
Test :meth:`orion.core.evc.adapters.DimensionDeletion.forward` with valid param and valid trials
625941cb2eb69b55b151c978
def __setstate_pre_1_0__(self, state): <NEW_LINE> <INDENT> for d in state: <NEW_LINE> <INDENT> for k, v in d.items(): <NEW_LINE> <INDENT> setattr(self, k, v)
In 1.0 we move to a dict save. Before, it was a tuple save, like ({'id': 11}, {'poller_tag': 'None', 'reactionner_tag': 'None', 'command_line': u'/usr/local/nagios/bin/rss-multiuser', 'module_type': 'fork', 'command_name': u'notify-by-rss'})
625941cb7c178a314d6ef528
def build_map_file_to_catalog(dir_all_ctalogs): <NEW_LINE> <INDENT> map_catalog_to_files = defaultdict(list) <NEW_LINE> for dir_name in os.listdir(dir_all_ctalogs): <NEW_LINE> <INDENT> dir_path = os.path.join(dir_all_ctalogs, dir_name) <NEW_LINE> if os.path.isdir(dir_path): <NEW_LINE> <INDENT> files = [TFile(get_hash(o...
строим отбражение для хеш от файла в кактлог - откуда этот файл :param dir_all_ctalogs: путь до базы с папками-каталогами :return: словарь
625941cbb545ff76a8913ee0
def plusOne(self, digits): <NEW_LINE> <INDENT> re = [] <NEW_LINE> pre = 0 <NEW_LINE> digits[-1] += 1 <NEW_LINE> print(digits) <NEW_LINE> for c in reversed(digits): <NEW_LINE> <INDENT> if c+pre >= 10: <NEW_LINE> <INDENT> pre = 1 <NEW_LINE> re.insert(0, 0) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> re.insert(0, c+pre)...
:type digits: List[int] :rtype: List[int]
625941cb99fddb7c1c9de45a
def serialize(self, buff): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _x = self <NEW_LINE> buff.write(_get_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> <INDENT> _x...
serialize message into buffer :param buff: buffer, ``StringIO``
625941cb91af0d3eaac9bae2
def __init__(self, nrows, ncols): <NEW_LINE> <INDENT> self.rows = nrows <NEW_LINE> self.cols = ncols <NEW_LINE> self.matrix = list() <NEW_LINE> for i in range(0,self.rows): <NEW_LINE> <INDENT> matrix = list() <NEW_LINE> for j in range(0,self.cols): <NEW_LINE> <INDENT> matrix.append(random.randint(0,9)) <NEW_LINE> <DEDE...
Construct a (nrows X ncols) matrix
625941cbbaa26c4b54cb11e9
def create_snapshot(self, volume_id, **kwargs): <NEW_LINE> <INDENT> post_body = {'volume_id': volume_id} <NEW_LINE> post_body.update(kwargs) <NEW_LINE> post_body = json.dumps({'snapshot': post_body}) <NEW_LINE> resp, body = self.post('snapshots', post_body) <NEW_LINE> body = json.loads(body) <NEW_LINE> return resp, bod...
Creates a new snapshot. volume_id(Required): id of the volume. force: Create a snapshot even if the volume attached (Default=False) display_name: Optional snapshot Name. display_description: User friendly snapshot description.
625941cb23849d37ff7b3159
def __init__(self, rpc, post): <NEW_LINE> <INDENT> super(PostModule, self).__init__(rpc, 'post', post)
Initializes the use of a post exploitation module. Mandatory Arguments: - rpc : the rpc client used to communicate with msfrpcd - post : the name of the post exploitation module.
625941cbd99f1b3c44c67658
def get_critical_tasks(self) -> list: <NEW_LINE> <INDENT> active_tasks = self.filter('in_progress') <NEW_LINE> critical_tasks = [] <NEW_LINE> for task in active_tasks: <NEW_LINE> <INDENT> if task.remaining <= datetime.timedelta(3): <NEW_LINE> <INDENT> critical_tasks.append(task) <NEW_LINE> <DEDENT> <DEDENT> return crit...
function docstring
625941cb4a966d76dd5510d8
def __sortDiscoveredLinks(self): <NEW_LINE> <INDENT> new_links = [link for link in self.discovered if not link in self.visited] <NEW_LINE> if self.log: <NEW_LINE> <INDENT> with open("discovered.txt", "a+") as log_file: <NEW_LINE> <INDENT> log_file.writelines("\n".join(new_links)) <NEW_LINE> <DEDENT> <DEDENT> self.front...
Sort discovered tags between frontier and visited
625941cb097d151d1a222f23
def andymark_item(partnumber): <NEW_LINE> <INDENT> url = 'http://www.andymark.com/product-p/am-'+str(product)+'.htm' <NEW_LINE> r = urllib.urlopen(url).read() <NEW_LINE> soup = BeautifulSoup(r) <NEW_LINE> price = soup.find_all("span", itemprop="price") <NEW_LINE> if soup.title.get_text()=="AndyMark Robot Parts Kits Mec...
Looks up an Andymark part. Takes in a part ID (a string), returns an array listing URL, part name, and price.
625941cb1f037a2d8b9462c7
def assert_no_unused_pixel_test_references(self): <NEW_LINE> <INDENT> if not (Image and self.pixels_label): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> all = set(glob.glob(os.path.join(TEST_DIR, "reference", self.pixels_label + "*-pixels.png"))) <NEW_LINE> unused = all - self.used_pixel_references <NEW_LINE> for u i...
Check whether all reference images in test/reference have been used.
625941cb99fddb7c1c9de45b
def describe(self, type=None, name=None): <NEW_LINE> <INDENT> if type == 'table' and name is not None: <NEW_LINE> <INDENT> info = self.table_info(name) <NEW_LINE> stdout.write('%-15s %15s\n' % ('column', 'type')) <NEW_LINE> stdout.write('-'*32+'\n') <NEW_LINE> for row in info: <NEW_LINE> <INDENT> stdout.write('%-15s %1...
Name: describe Purpose: Print a visually appealing description of the database or an object in the database, such as a table or index. This just calls the .info or .table_info method and prints the results. Calling Sequence: describe(type=None, name=None) Inputs/Keywords: type: e.g. 'table',...
625941cb0a366e3fb873e8e3
def adapt_in_domain_for_dclm(in_file_xml, in_file_processed, out_file_dclm, num_concat, rid_func, stem_text): <NEW_LINE> <INDENT> tree = et.parse(in_file_xml) <NEW_LINE> root = tre...
(1) add document boundaries, (2) remove function words and punctuations, (3) lemmatize/stem the text params: in_file_xml: input file in the original xml format in_file_processed: input file with tokenized and recased sentences out_file_dclm: output file with document boundaries num_concat: number of se...
625941cb4c3428357757c3f1
def __init__(self, sources, dbfile=":memory:"): <NEW_LINE> <INDENT> self.sources = [('Time', lambda: self.tnow)] + list(sources) <NEW_LINE> if dbfile: <NEW_LINE> <INDENT> self.db = TagDB(dbfile) <NEW_LINE> self.db.new_session() <NEW_LINE> self.session = self.db.session <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self...
sources: an iterable of (name, callable) tuples - name (str) is the name of a signal and the - callable is evaluated to obtain the value. Example: >>> a = 1 >>> def getvalue(): ... return a >>> h = Historian([('a', getvalue)]) >>> h.update(0) >>> h.log [(0, 1)] Sometimes, multiple values are obtained fr...
625941cbd164cc6175782e17
@refDoc(__doi__, [6]) <NEW_LINE> def f_wood(Re, eD): <NEW_LINE> <INDENT> a = 0.094*eD**0.225+0.53*eD <NEW_LINE> b = 88*eD**0.44 <NEW_LINE> c = -1.62*eD**0.134 <NEW_LINE> f = a + b*Re**c <NEW_LINE> return Dimensionless(f)
Calculates friction factor `f` with Wood correlation (1966) .. math:: f_d = 0.094\left(\epsilon/D\right)^{0.225} + 0.53\left( \epsilon/D\right) + 88\left(\epsilon/D\right)^{0.4}Re^{-A_1} .. math:: A_1 = 1.62\left(\epsilon/D\right)^{0.134} Parameters ------------ Re : float Reynolds number, [-] eD : f...
625941cb3317a56b86939d23
def flop_strategy(self): <NEW_LINE> <INDENT> flop_percentile = self.percentiles['flop'] <NEW_LINE> potodds_ratio = 0.50 <NEW_LINE> pot_size = self.pot <NEW_LINE> for action in self.legal: <NEW_LINE> <INDENT> if isinstance(action, Bet): <NEW_LINE> <INDENT> if flop_percentile < 1: <NEW_LINE> <INDENT> value_bet = int(roun...
Returns an action after the flop, based on the table and the player
625941cb29b78933be1e5776
def __init__(self, gens): <NEW_LINE> <INDENT> Functor.__init__(self, Groups(), Groups()) <NEW_LINE> self._gens = gens
EXAMPLES:: sage: from sage.categories.pushout import PermutationGroupFunctor sage: PF = PermutationGroupFunctor([PermutationGroupElement([(1,2)])]); PF PermutationGroupFunctor[(1,2)]
625941cbd7e4931a7ee9dfe7
def remove_all(link , value): <NEW_LINE> <INDENT> if link is Link.empty or link.rest is Link.empty: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> elif link.rest.first == value : <NEW_LINE> <INDENT> link.rest = link.rest.rest <NEW_LINE> remove_all(link,value) <NEW_LINE> return None <NEW_LINE> <DEDENT> else : <NEW_...
Remove all the nodes containing value. Assume there exists some nodes to be removed and the first element is never removed. >>> l1 = Link(0, Link(2, Link(2, Link(3, Link(1, Link(2, Link(3))))))) >>> print(l1) <0 2 2 3 1 2 3> >>> remove_all(l1, 2) >>> print(l1) <0 3 1 3> >>> remove_all(l1, 3) >>> print(l1) <0 1>
625941cbec188e330fd5a869
def read_csv_noheader(filepath): <NEW_LINE> <INDENT> df = pd.read_csv(filepath, header=None, low_memory=False) <NEW_LINE> colnames = {i:'col'+str(i) for i in df.columns} <NEW_LINE> df = df.rename(columns=colnames) <NEW_LINE> return df
Read a csv file with no header :param str filepath: file path name :return pandas.DataFrame with header 'col1', 'col2', ... :rtype pandas.DataFrame
625941cb097d151d1a222f24
def forward(self, x, src_seq): <NEW_LINE> <INDENT> self_attn_mask = get_attn_padding_mask(src_seq, src_seq, self.pad) <NEW_LINE> position_embedding = Variable(positional_embedding(x), requires_grad=False) <NEW_LINE> x = x + position_embedding <NEW_LINE> encoder_inputs = self.W(self.dropout(x)) <NEW_LINE> enc_outputs = ...
input include attend words
625941cb167d2b6e31218c60
@register.filter <NEW_LINE> def donation_percentage(ticket): <NEW_LINE> <INDENT> if ticket.feature.donation_goal == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> return (float(ticket.feature.total_donations)/float(ticket.feature.donation_goal)) * 100
Gets the percentage value of the donations earned in relation to donations goal :param ticket: The ticket requested to get the donation percentage of :return: percentage value of donations earned
625941cb0fa83653e4657085
def delete(event, context): <NEW_LINE> <INDENT> job_definition = get_job_definition_name_by_arn(event["ResourceProperties"]["JobDefinitionMNPArn"]) <NEW_LINE> logger.info("Job definition %s deletion: STARTED" % job_definition) <NEW_LINE> deregister_job_definition_revisions(job_definition) <NEW_LINE> logger.info("Job de...
Deregister all mnp job definitions.
625941cb63b5f9789fde71af
def test_blocketteStartsAfterRecord(self): <NEW_LINE> <INDENT> b010 = b"0100042 2.4082008,001~2038,001~2009,001~~~" <NEW_LINE> blockette = Blockette010(strict=True, compact=True) <NEW_LINE> blockette.parseSEED(b010) <NEW_LINE> self.assertEqual(b010, blockette.getSEED()) <NEW_LINE> b054 = b"0540240A0400300300000009" + (...
'... 058003504 1.00000E+00 0.00000E+0000 000006S*0543864 ... ' ' 0543864' -> results in Blockette 005
625941cb090684286d50edaf
def getFieldDataType(self, name): <NEW_LINE> <INDENT> annotation = self.annotationTable.get(name, None) <NEW_LINE> if annotation is not None: <NEW_LINE> <INDENT> return annotation.getDataType() <NEW_LINE> <DEDENT> return "String"
Return data type for the given field name. :param name: field name (or, unmapped field ID) :return: data type
625941cb4e4d5625662d44a2
def custom_score_2(game, player): <NEW_LINE> <INDENT> if game.is_loser(player): <NEW_LINE> <INDENT> return float("-inf") <NEW_LINE> <DEDENT> if game.is_winner(player): <NEW_LINE> <INDENT> return float("inf") <NEW_LINE> <DEDENT> own_moves = len(game.get_legal_moves(player)) <NEW_LINE> opp_moves = len(game.get_legal_move...
Calculate the heuristic value of a game state from the point of view of the given player. Note: this function should be called from within a Player instance as `self.score()` -- you should not need to call this function directly. Parameters ---------- game : `isolation.Board` An instance of `isolation.Board` enco...
625941cb16aa5153ce362542