code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def train_sample(user_sample, maxlines=None, context_only=True, etl={}): <NEW_LINE> <INDENT> with open(TRAIN) as f_in: <NEW_LINE> <INDENT> train_reader = csv.DictReader(f_in, delimiter='\t') <NEW_LINE> for (k, line) in enumerate(train_reader): <NEW_LINE> <INDENT> if k == maxlines: <NEW_LINE> <INDENT> break <NEW_LINE> <...
Replaces sample_train_by_user. Reads trainSearchStream, filtering for searches by users in user_sample, then joins in fields from user_sample using a dict from field names to functions/lambda for extraction/transformation. time: ~12 min in pypy args: user_sample - a dict like {SearchID: list of features}. Se...
625941ca498bea3a759b9b67
def source(xsource, source, bozo, format): <NEW_LINE> <INDENT> xdoc = xsource.ownerDocument <NEW_LINE> createTextElement(xsource, 'id', source.get('id', source.get('link',None))) <NEW_LINE> createTextElement(xsource, 'icon', source.get('icon', None)) <NEW_LINE> createTextElement(xsource, 'logo', source.get('logo', None...
copy source information to the entry
625941ca26238365f5f0ef26
def prettyIn(self, value): <NEW_LINE> <INDENT> if isinstance(value, tuple): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> elif isinstance(value, ObjectIdentifier): <NEW_LINE> <INDENT> return tuple(value) <NEW_LINE> <DEDENT> elif octets.isStringType(value): <NEW_LINE> <INDENT> r = [] <NEW_LINE> for element in [ x for x i...
Dotted -> tuple of numerics OID converter
625941ca1f5feb6acb0c4c0a
def main(path, args, cData): <NEW_LINE> <INDENT> msg = "System shutdown." <NEW_LINE> return {"msg": msg, "code": 1}
Shutdown the system.
625941ca6fece00bbac2d7f6
def closest_pair_strip(cluster_list, horiz_center, half_width): <NEW_LINE> <INDENT> useful_list = [] <NEW_LINE> for idx in range(len(cluster_list)): <NEW_LINE> <INDENT> cluster = cluster_list[idx] <NEW_LINE> if (horiz_center + half_width) > cluster.horiz_center() > (horiz_center - half_width): <NEW_LINE> <INDENT> usefu...
Helper function to compute the closest pair of clusters in a vertical strip Input: cluster_list is a list of clusters produced by fast_closest_pair horiz_center is the horizontal position of the strip's vertical center line half_width is the half the width of the strip (i.e; the maximum horizontal distance that a clus...
625941ca596a897236089b79
@login_required <NEW_LINE> def nodeinfo(request): <NEW_LINE> <INDENT> nodelists = [] <NEW_LINE> ss_user = request.user.ss_user <NEW_LINE> user = request.user <NEW_LINE> nodes = Node.objects.filter(level__lte=user.level, show='显示').values() <NEW_LINE> for node in nodes: <NEW_LINE> <INDENT> obj = Node.objects.get(node_id...
跳转到节点信息的页面
625941ca3eb6a72ae02ec594
def get_filename(view): <NEW_LINE> <INDENT> return view.file_name() or "<untitled {}>".format(view.buffer_id())
Get view's file name. Parameters ---------- view : object A Sublime Text view. Returns ------- str File name. Note ---- Borrowed from SublimeLinter.
625941ca925a0f43d2549f2f
def create_user(self, email, password=None): <NEW_LINE> <INDENT> now = timezone.now() <NEW_LINE> if not email: <NEW_LINE> <INDENT> raise ValueError('The given username must be set') <NEW_LINE> <DEDENT> email = UserManager.normalize_email(email) <NEW_LINE> user = self.model(email=email, is_staff=False, is_active=True, i...
Creates and saves a User with the given username, email and password.
625941cad164cc6175782e06
def np_matmul(mat1, mat2): <NEW_LINE> <INDENT> return mat1 @ mat2
Performs matrix multiplication.
625941caf8510a7c17cf97b5
def makeFrame(self, sizex, sizey): <NEW_LINE> <INDENT> format=GeomVertexFormat.getV3cp() <NEW_LINE> vdata=GeomVertexData('card-frame', format, Geom.UHDynamic) <NEW_LINE> vwriter=GeomVertexWriter(vdata, 'vertex') <NEW_LINE> cwriter=GeomVertexWriter(vdata, 'color') <NEW_LINE> ringoffset = [0, 1, 1, 2] <NEW_LINE> ringbrig...
Access: private. Each texture card is displayed with a two-pixel wide frame (a ring of black and a ring of white). This routine builds the frame geometry. It is necessary to be precise so that the frame exactly aligns to pixel boundaries, and so that it doesn't overlap the card at all.
625941ca283ffb24f3c559ba
def get_all_objects(text, beginning=r'{', debug=False): <NEW_LINE> <INDENT> def _dbg_actual(st, *ar): <NEW_LINE> <INDENT> print("D: ", st % ar) <NEW_LINE> <DEDENT> _dbg = _dbg_actual if debug else (lambda *ar: None) <NEW_LINE> import yaml <NEW_LINE> class ddd(dict): <NEW_LINE> <INDENT> def __getitem__(self, key): <NEW_...
Zealous obtainer of mappings from a text, e.g. in javascript or JSON or whatever. Anything between '{' and '}' The monstrous advanced version. Not performant. Requires pyyaml. >>> st = 'a str with var stuff = {a: [{"v": 12}]} and such' >>> next(get_all_objects(st)) {'a': [{'v': 12}]}
625941caa219f33f34628a23
def Choose_IntFloatStr(s): <NEW_LINE> <INDENT> if not(type(s) == str): <NEW_LINE> <INDENT> print("BAD USAGE OF THIS FUNCTION: " "\tinput argument should be a string, not %s." % type(s)) <NEW_LINE> return s <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> float(s) <NEW_LINE> try: <NEW_LINE> <INDENT> return int(s) <NEW_LINE>...
Check and see if the input string 's' represents a number: -> if it does, then return int (default) or float version; -> else, return the same string back. Returns error if the input is not of type 'str'.
625941cafff4ab517eb2f4f5
def test_level_two_heading(self): <NEW_LINE> <INDENT> test_string = self.read_test_file(self.processor_name, 'level_two_heading.md') <NEW_LINE> processor = RemoveTitlePreprocessor(self.ext, self.md.parser) <NEW_LINE> self.assertTrue(processor.test(test_string)) <NEW_LINE> converted_test_string = markdown.markdown(test_...
Tests that a level two heading is also removed if found first.
625941ca2ae34c7f2600d1ea
def bulk_flush_backoff_delay(self, delay): <NEW_LINE> <INDENT> self._j_elasticsearch = self._j_elasticsearch.bulkFlushBackoffDelay(int(delay)) <NEW_LINE> return self
Configures how to buffer elements before sending them in bulk to the cluster for efficiency. Sets the amount of delay between each backoff attempt when flushing bulk requests (in milliseconds). Make sure to enable backoff by selecting a strategy ( :func:`pyflink.table.descriptors.Elasticsearch.bulk_flush_backoff_cons...
625941caf9cc0f698b1406b4
def load_struct(self): <NEW_LINE> <INDENT> module_name = "oes_struct_mkt_packets_md" <NEW_LINE> module = importlib.import_module(module_name) <NEW_LINE> for name in dir(module): <NEW_LINE> <INDENT> if "__" not in name: <NEW_LINE> <INDENT> self.structs[name] = getattr(module, name)
加载Struct
625941ca92d797404e304242
def statistics(l): <NEW_LINE> <INDENT> if isinstance(l, numpy.ndarray): <NEW_LINE> <INDENT> nums = l <NEW_LINE> <DEDENT> elif not isinstance(l, list) or len(l)<1: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> nums = numpy.array(l) <NEW_LINE> <DEDENT> m = nums.mean(axis=0) <NEW_LINE> medi...
Print statistics for the given list of integers @return A tuple (mean, stderr, median, min, max)
625941ca046cf37aa974ce01
def readMORPHLINESTYLE2(self, level=1): <NEW_LINE> <INDENT> return SWFMorphLineStyle2(self, level)
Read a SWFMorphLineStyle2
625941cac4546d3d9de72aec
def hide_column(self, column, hide=True): <NEW_LINE> <INDENT> self.get_range('%s1' % column).EntireColumn.Hidden = hide
Hide the specified 'column'. Specify hide=False to show the column.
625941ca0a50d4780f666f4a
def p_matrix_eye_init(p): <NEW_LINE> <INDENT> p[0] = entities.EyeMatrixInit(p[3], p.lineno(1))
matrix_init : EYE '(' expression ')'
625941ca7047854f462a14c3
def test_getblob_method_present(self): <NEW_LINE> <INDENT> self.assertClassHasMethod(pptx.packaging.ZipFileSystem, 'getblob')
ZipFileSystem class has method 'getblob'
625941cad10714528d5ffd9b
def swap_positions(initial, temp, temp_spot, empty_spot): <NEW_LINE> <INDENT> initial[temp_spot] = initial[empty_spot] <NEW_LINE> initial[empty_spot] = temp
Swaps two cars in the initial arrangement list Arguments: initial : list -- The initial arrangement list temp : int -- The car that is being replaced temp_spot : int -- The space of the car that is being replaced empty_spot : int -- The space of the empty spot
625941caab23a570cc25023b
def _validate(self): <NEW_LINE> <INDENT> if self.par is None: <NEW_LINE> <INDENT> raise SrFitError("par is None") <NEW_LINE> <DEDENT> if self.eq is None: <NEW_LINE> <INDENT> raise SrFitError("eq is None") <NEW_LINE> <DEDENT> self.par._validate() <NEW_LINE> from diffpy.srfit.equation.visitors import validate <NEW_LINE> ...
Validate my state. This validates that par is not None. This validates eq. Raises SrFitError if validation fails.
625941ca5fdd1c0f98dc02ec
def find_special_cells(tile_grid): <NEW_LINE> <INDENT> cells = {} <NEW_LINE> for loc, tile in tile_grid.items(): <NEW_LINE> <INDENT> for cell_type, cell_names in tile.cell_names.items(): <NEW_LINE> <INDENT> for cell_name, in cell_names: <NEW_LINE> <INDENT> if cell_name == "LOGIC": <NEW_LINE> <INDENT> continue <NEW_LINE...
Finds cells that occupy more than one tilegrid location.
625941ca2c8b7c6e89b3587a
def __init__(self, patch, error): <NEW_LINE> <INDENT> PatchException.__init__(self, patch) <NEW_LINE> self.inflight = error.inflight <NEW_LINE> self.error = error <NEW_LINE> self.args = (patch, error,)
Initialize the error object. Args: patch: The GitRepoPatch instance that this exception concerns. error: A PatchException object that can be stringified to describe the error.
625941ca3eb6a72ae02ec595
def mod_rule_tables(self, tables, categories, no_categories): <NEW_LINE> <INDENT> def get_t_vals(t): <NEW_LINE> <INDENT> table = t[0] <NEW_LINE> k = t[1] <NEW_LINE> e = [] <NEW_LINE> if len(t) > 2: <NEW_LINE> <INDENT> e = t[2] <NEW_LINE> <DEDENT> return table, k, e <NEW_LINE> <DEDENT> t_list = [t[0] for t in tables if ...
Test functionality of rule table widgets in a facet
625941ca4428ac0f6e5ba8ab
def get_cached(self, cache_key, func): <NEW_LINE> <INDENT> logging.debug("Using cache") <NEW_LINE> logging.debug("Cache keys: {}".format(self.cache.keys())) <NEW_LINE> if cache_key in self.cache: <NEW_LINE> <INDENT> logging.debug("Using cached data for key=\"{}\"".format(cache_key)) <NEW_LINE> return self.cache[cache_k...
Get data from cache if fresh, otherwise from `func`.
625941caf548e778e58cd636
def test_valid_address_null_region(): <NEW_LINE> <INDENT> address = copy.deepcopy(ADDRESS) <NEW_LINE> address['addressRegion'] = None <NEW_LINE> is_valid, errors = validate(address, 'address') <NEW_LINE> if errors: <NEW_LINE> <INDENT> for err in errors: <NEW_LINE> <INDENT> print(err.message) <NEW_LINE> <DEDENT> <DEDENT...
Assert that region is allowed to be null.
625941ca30bbd722463cbe7e
def addrestricted(self): <NEW_LINE> <INDENT> if self.norestrfile != 1: <NEW_LINE> <INDENT> self.addrestrict() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.status.set('Load the Restrict File first!') <NEW_LINE> self.load.flash() <NEW_LINE> self.loadr.flash() <NEW_LINE> sleep(1) <NEW_LINE> self.load.flash() <NEW_LI...
Calls the Add Restrict function if the load MLF function or Load Restrict funtion has been called befor and the Restrict file exists
625941ca66656f66f7cbc263
def items(self): <NEW_LINE> <INDENT> return [(key, self.get(key)) for key in self.keys()]
Return list of tuples of keys and values in db >>> dc = Dictator() >>> dc['l0'] = [1, 2, 3, 4] >>> dc.items() [('l0', ['1', '2', '3', '4'])] >>> del dc['l0'] :return: list of tuple
625941ca73bcbd0ca4b2c12f
def add_phrases_to_trie(trie, phrase_list, score): <NEW_LINE> <INDENT> if phrase_list is None or len(phrase_list) is 0: <NEW_LINE> <INDENT> raise ValueError('Phrase list cannot be empty') <NEW_LINE> <DEDENT> for phrase in phrase_list: <NEW_LINE> <INDENT> trie.add(phrase, score)
:param trie: :param phrase_list: :param score: :return: Add phrases to generate Trie, along with score used for indicating risk level: i.e. Low/High
625941ca8e7ae83300e4b085
def chain_funcs(funcs): <NEW_LINE> <INDENT> return lambda x: reduce(lambda f1, f2: f2(f1), funcs, x)
Compose the functions in iterable funcs
625941ca5e10d32532c5efe0
def deleteDuplicates(self, head): <NEW_LINE> <INDENT> dummy = prev = ListNode(0) <NEW_LINE> dummy.next = head <NEW_LINE> while head and head.next: <NEW_LINE> <INDENT> if head.val == head.next.val: <NEW_LINE> <INDENT> while head and head.next and head.val == head.next.val: <NEW_LINE> <INDENT> head = head.next <NEW_LINE>...
:type head: ListNode :rtype: ListNode
625941ca67a9b606de4a7f73
def __rsub__(self, other): <NEW_LINE> <INDENT> pass
c.__rsub__(d) <==> d-c Returns the result of the substraction of Color c from d if d is convertible to a Color, replace every component c[i] of c by d-c[i] if d is a scalar
625941ca32920d7e50b28288
def test_get_query_triple_www(self): <NEW_LINE> <INDENT> form = FieldStorageDict( fieldidx1='cql.anywhere', fieldrel1='all', fieldcont1='spam', fieldbool1='and', fieldidx2='cql.anywhere', fieldrel2='all', fieldcont2='eggs' ) <NEW_LINE> query = self.testObj.get_query( self.session, form, format='www' ) <NEW_LINE> self....
Test query with boolean.
625941ca7d847024c06be374
def __init__(self, total=None): <NEW_LINE> <INDENT> self.swagger_types = { 'total': 'int' } <NEW_LINE> self.attribute_map = { 'total': 'total' } <NEW_LINE> self._total = total
Meta - 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.
625941caa17c0f6771cbe10a
def scrape_source(config): <NEW_LINE> <INDENT> return list(itertools.chain(*concurrent.futures.ThreadPoolExecutor(5).map( lambda args: scrape(*args), config)))
Function to scrape data from malware sources
625941ca30c21e258bdfa556
def makeRandomLastName(maxCID): <NEW_LINE> <INDENT> min_cid = 999 <NEW_LINE> if (maxCID - 1) < min_cid: min_cid = maxCID - 1 <NEW_LINE> return makeLastName(NURand(255, 0, min_cid))
A non-uniform random last name, as defined by TPC-C 4.3.2.3. The name will be limited to maxCID.
625941cac4546d3d9de72aed
def __init__(self, xml): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> logger = logging.getLogger().getChild(__name__) <NEW_LINE> logger.info("parse Wikipedia export file %s", xml) <NEW_LINE> if xml.endswith("bz2"): <NEW_LINE> <INDENT> logger.info("unzip bz2 file") <NEW_LINE> with bz2.open(xml) as file_: <NEW_LINE> <IND...
Parse Wikipedia export file. :param str xml: Wikipedia export file
625941ca9f2886367277a947
def strB(n, base=10): <NEW_LINE> <INDENT> class BadBase(Exception): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> if base < 2 or base > 26: <NEW_LINE> <INDENT> raise BadBase <NEW_LINE> <DEDENT> <DEDENT> except BadBase: <NEW_LINE> <INDENT> print('Base must be between 2 and 26. Exiting...') <NEW_L...
PART B: strB converts n (which is in base 10) to any base between 2 and 26. This is done by checking a string containing 26 items, for the 26 possible bases the user can convert to. n is divided by base using integer division (//) and the remainder is collected (the remainder will always be less than the base) by searc...
625941ca8da39b475bd6502c
def resnet34(pretrained=False, progress=True, **kwargs): <NEW_LINE> <INDENT> return _resnet('resnet34', BasicBlock, [3, 4, 6, 3], pretrained, progress, **kwargs)
ResNet-34 model from `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_ Args: pretrained (bool): If True, returns a model pre-trained on ImageNet progress (bool): If True, displays a progress bar of the download to stderr
625941ca99cbb53fe6792ca0
def post(public, upload_files, filepath, description, facade): <NEW_LINE> <INDENT> gist = model.Gist() <NEW_LINE> if description: <NEW_LINE> <INDENT> gist.description = description <NEW_LINE> <DEDENT> gist.public = public <NEW_LINE> for upfile in upload_files: <NEW_LINE> <INDENT> gistFile = model.GistFile() <NEW_LINE> ...
Create a new Gist. Currently only support create Gist with single files. (Then you can 'update' the gist and attach more files in it, but the creation only supports one file) You are able to specify if you want to create a public or private gist and set its description. :param public: whenever new Gist should be pub...
625941cad6c5a10208144104
def opt_validate_bdgcmp ( options ): <NEW_LINE> <INDENT> logging.basicConfig(level=20, format='%(levelname)-5s @ %(asctime)s: %(message)s ', datefmt='%a, %d %b %Y %H:%M:%S', stream=sys.stderr, filemode="w" ) <NEW_LINE> options.error = logging.critical <NEW_LINE> options.warn = logging.warning <NEW_LINE> options.de...
Validate options from a OptParser object. Ret: Validated options object.
625941cade87d2750b85fe4c
def _get_subnetpool_id(self, context, subnet): <NEW_LINE> <INDENT> subnetpool_id = subnet.get('subnetpool_id', attributes.ATTR_NOT_SPECIFIED) <NEW_LINE> if subnetpool_id != attributes.ATTR_NOT_SPECIFIED: <NEW_LINE> <INDENT> return subnetpool_id <NEW_LINE> <DEDENT> cidr = subnet.get('cidr') <NEW_LINE> if attributes.is_a...
Returns the subnetpool id for this request If the pool id was explicitly set in the request then that will be returned, even if it is None. Otherwise, the default pool for the IP version requested will be returned. This will either be a pool id or None (the default for each configuration parameter). This implies th...
625941ca293b9510aa2c3350
def cos_1(a=1): <NEW_LINE> <INDENT> def lhs(x): <NEW_LINE> <INDENT> return np.exp(-a**2*x**2) <NEW_LINE> <DEDENT> def rhs(b): <NEW_LINE> <INDENT> return np.sqrt(np.pi)*np.exp(-b**2/(4*a**2))/(2*a) <NEW_LINE> <DEDENT> return Ghosh('cos', lhs, rhs)
Fourier cosine transform pair cos_1 ([Anderson_1975]_).
625941ca4f88993c3716c121
def plot_qpgaps(self, spin=None, kpoint=None, hspan=0.01, **kwargs): <NEW_LINE> <INDENT> spin_range = range(self.nsppol) if spin is None else torange(spin) <NEW_LINE> kpoints_for_plot = self.computed_gwkpoints <NEW_LINE> title = kwargs.pop("title", None) <NEW_LINE> show = kwargs.pop("show", True) <NEW_LINE> savefig = k...
Plot the QP gaps as function of the convergence parameter. Args: spin: kpoint: hspan: kwargs: Returns: `matplotlib` figure
625941ca44b2445a3393214f
def finalize(self): <NEW_LINE> <INDENT> if self._init_op is None: <NEW_LINE> <INDENT> def default_init_op(): <NEW_LINE> <INDENT> return control_flow_ops.group( variables.global_variables_initializer(), resources.initialize_resources(resources.shared_resources())) <NEW_LINE> <DEDENT> self._init_op = Scaffold.get_or_defa...
Creates operations if needed and finalizes the graph.
625941cacdde0d52a9e530ec
def _handle_key_event(self, event, ns_event, propagate): <NEW_LINE> <INDENT> event_type = ns_event.type() <NEW_LINE> key = str(ns_event.charactersIgnoringModifiers()) <NEW_LINE> key_id = ns_event.keyCode() <NEW_LINE> if event_type == Quartz.kCGEventKeyDown: <NEW_LINE> <INDENT> if self.KeyDown: <NEW_LINE> <INDENT> hotke...
Key event handler called by :paramref:`_tap_callback_inner`. This handler translates platform-specific event to cross-platform event object. And then calls `self.KeyDown` or `self.KeyUp` with the cross-platform event object. :param event: CGEvent object. :param ns_event: NSEvent object. :param propagate: Whether pr...
625941cab7558d58953c4fce
def get_package_name(filename): <NEW_LINE> <INDENT> m = PACKAGE_PATTERN.match(filename) <NEW_LINE> if m: <NEW_LINE> <INDENT> return m.group(1).lower()
通过package filename获取package_name
625941cae5267d203edcdd57
def test_iter_cai_assets(self): <NEW_LINE> <INDENT> self._add_resources() <NEW_LINE> cai_type = 'cloudresourcemanager.googleapis.com/Folder' <NEW_LINE> results = cai_temporary_storage.CaiDataAccess.iter_cai_assets( cai_temporary_storage.ContentTypes.resource, cai_type, '//cloudresourcemanager.googleapis.com/organizatio...
Validate querying CAI asset data.
625941ca3c8af77a43ae3859
def drop_collection(self, name_or_collection, session=None): <NEW_LINE> <INDENT> name = name_or_collection <NEW_LINE> if isinstance(name, Collection): <NEW_LINE> <INDENT> name = name.name <NEW_LINE> <DEDENT> if not isinstance(name, str): <NEW_LINE> <INDENT> raise TypeError("name_or_collection must be an instance of str...
Drop a collection. :Parameters: - `name_or_collection`: the name of a collection to drop or the collection object itself - `session` (optional): a :class:`~pymongo.client_session.ClientSession`. .. note:: The :attr:`~pymongo.database.Database.write_concern` of this database is automatically applied to ...
625941ca99fddb7c1c9de44a
def power_off_for_interval(self, interval=30): <NEW_LINE> <INDENT> log.info('Power off {s} for {i} seconds'.format( s=self.shortname, i=interval)) <NEW_LINE> child = self._pexpect_spawn_ipmi('power off') <NEW_LINE> child.expect('Chassis Power Control: Down/Off', timeout=self.timeout) <NEW_LINE> time.sleep(interval) <NE...
Physical power off for an interval. Wait for login when complete. :param interval: Length of power-off period.
625941ca94891a1f4081bb62
def web_imports(symbols): <NEW_LINE> <INDENT> date = pd.datetime.today().date().strftime('%Y-%m-%d') <NEW_LINE> logger.info('Start update web data: %s' % date) <NEW_LINE> for symbol in symbols: <NEW_LINE> <INDENT> for source in ('google', 'yahoo'): <NEW_LINE> <INDENT> logger.info('Web import: %s, %s, %s' % (source.uppe...
Web import data for each symbols :param symbols: list :return: None
625941ca3317a56b86939d13
def log_exceptions(exit_on_exception=False): <NEW_LINE> <INDENT> def decorator(func): <NEW_LINE> <INDENT> @functools.wraps(func) <NEW_LINE> def wrapper(*args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return func(*args, **kwargs) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> if exit_on_excepti...
Logs any exceptions raised. By default, exceptions are then re-raised. If set to exit on exception, sys.exit(1) is called instead.
625941ca99fddb7c1c9de44b
def Vperp(V,B): <NEW_LINE> <INDENT> Bnorm = np.sqrt(dotprod(B,B)) <NEW_LINE> Vperp = np.zeros(B.shape) <NEW_LINE> VdotB = dotprod(V,B) <NEW_LINE> Vpara = np.zeros(B.shape) <NEW_LINE> Vpara[0,:,:,:] = VdotB * B[0,:,:,:]/Bnorm <NEW_LINE> Vpara[1,:,:,:] = VdotB * B[1,:,:,:]/Bnorm <NEW_LINE> Vpara[2,:,:,:] = VdotB * B[2,:,...
returns the component of the velocity V that is perp to B @param V velocity vector (3,:,:) @param B magnetic field vector (3,:,:) @return: velocity perp to B vector (3,:,:) Exemple : Note : the perp part of the velocity is obtained from subtracting the parallel part from the total velovity. Creation : 2013-01-17 ...
625941ca23849d37ff7b3149
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, AddAccessControlGroupOutboundRuleResponse): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__
Returns true if both objects are equal
625941ca63d6d428bbe445a9
def p_program_bez_deklaracji(self, p): <NEW_LINE> <INDENT> p[0] = ("program", [], p[2])
program : BEGIN instrukcje END
625941ca379a373c97cfabfe
def _get_word2vec_matrix(self, wv_model, idx2char, embedding_dim): <NEW_LINE> <INDENT> count = 0 <NEW_LINE> embedding_matrix = np.zeros((len(idx2char), embedding_dim)) <NEW_LINE> for idx, char in enumerate(idx2char): <NEW_LINE> <INDENT> if char in wv_model.wv.vocab: <NEW_LINE> <INDENT> wv_idx = wv_model.wv.vocab[char]....
return the word2vec matrix, reordered by char2idx vocabulary index
625941cadc8b845886cb55ee
def ShouldSerializeKeyFrames(self): <NEW_LINE> <INDENT> pass
ShouldSerializeKeyFrames(self: VectorAnimationUsingKeyFrames) -> bool Returns true if the value of the System.Windows.Media.Animation.VectorAnimationUsingKeyFrames.KeyFrames property of this instance of System.Windows.Media.Animation.VectorAnimationUsingKeyFrames should be value-serialized. Returns: tru...
625941cad164cc6175782e07
def breadthFirstSearch(problem): <NEW_LINE> <INDENT> visited = set() <NEW_LINE> node_list = util.Queue() <NEW_LINE> start_node = problem.getStartState() <NEW_LINE> moves = [] <NEW_LINE> init_cost = 0 <NEW_LINE> node_list.push((start_node, moves, init_cost)) <NEW_LINE> while node_list.isEmpty() is False: <NEW_LINE> <IND...
Search the shallowest nodes in the search tree first.
625941ca4a966d76dd5510c9
def render(self, context): <NEW_LINE> <INDENT> request = context.get("request") <NEW_LINE> if self.current_category: <NEW_LINE> <INDENT> obj = context.get("category") or context.get("product") <NEW_LINE> if obj: <NEW_LINE> <INDENT> category = obj if isinstance(obj, Category) else obj.get_current_category(request) <NEW_...
Renders the portlet as html.
625941cad486a94d0b98e1ff
def has_pyvisfile(): <NEW_LINE> <INDENT> global _has_pyvisfile <NEW_LINE> if _has_pyvisfile is None: <NEW_LINE> <INDENT> _has_pyvisfile = True <NEW_LINE> try: <NEW_LINE> <INDENT> import pyvisfile <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> _has_pyvisfile = False <NEW_LINE> <DEDENT> <DEDENT> return _has_...
Return True if pyvisfile is available.
625941cad58c6744b4257d1a
def zoom_out(self): <NEW_LINE> <INDENT> org_size = self._sizes[self._zoom_level] <NEW_LINE> self._zoom_level -= 1 <NEW_LINE> if self._zoom_level < 0: <NEW_LINE> <INDENT> self._zoom_level = 0 <NEW_LINE> <DEDENT> new_size = self._sizes[self._zoom_level] <NEW_LINE> self._zoom_center(org_size, new_size)
Zoom out in on center of view.
625941ca7b25080760e39513
def GetService(self, *args): <NEW_LINE> <INDENT> pass
GetService(self: Component, service: Type) -> object Returns an object that represents a service provided by the System.ComponentModel.Component or by its System.ComponentModel.Container. service: A service provided by the System.ComponentModel.Component. Returns: An System.Object that repre...
625941ca44b2445a33932150
def runTest(self): <NEW_LINE> <INDENT> p.send_all(self.shell, "echo hello\n") <NEW_LINE> self.assertEqual(p.recv_some(self.shell), "hello\n") <NEW_LINE> p.send_all(self.shell, "echo hello world\n") <NEW_LINE> self.assertEqual(p.recv_some(self.shell), "hello world\n") <NEW_LINE> p.send_all(self.shell, "exit\n") <NEW_LIN...
try echoing some text and see if it comes back out
625941ca4e4d5625662d4492
def convert_related_cols_categorical_to_numeric(df, col_list): <NEW_LINE> <INDENT> ret = pd.DataFrame() <NEW_LINE> values = None <NEW_LINE> for c in col_list: <NEW_LINE> <INDENT> values = pd.concat([values, df[c]], axis=0) <NEW_LINE> values = pd.Series(values.unique()) <NEW_LINE> <DEDENT> col_dict = _get_nominal_intege...
Convert categorical columns, that are related between each other, to numeric and leave numeric columns as they are. Args: df (pd.DataFrame): Dataframe. col_list (list): List of columns. Returns: pd.DataFrame: An dataframe with numeric values. Examples: >>> df = pd.DataFrame({'letters':['a','b','c'],'...
625941ca3c8af77a43ae385a
def findMostSimilarNodes(self, source, number=None, conserveMemory=False): <NEW_LINE> <INDENT> if number is None: <NEW_LINE> <INDENT> number = self.n <NEW_LINE> <DEDENT> reachableNodes = self.metaPathUtility.findMetaPathNeighbors(self.graph, source, self.metaPath) <NEW_LINE> for reachableNode in reachableNodes: <NEW_LI...
Simple find the similarity scores between this node and all reachable nodes on this meta path. Note that if there are fewer reachable nodes than "number", the number of reachable nodes will be returned.
625941ca8e71fb1e9831d863
def identify_file(self, file_path, test_profile_ids, force_short_audio = False): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if len(test_profile_ids) < 1: <NEW_LINE> <INDENT> raise Exception('Error identifying file: no test profile IDs are provided.') <NEW_LINE> <DEDENT> test_profile_ids_str = ','.join(test_profile_id...
Enrolls a profile using an audio file and returns a dictionary of the enrollment response. Arguments: file_path -- the file path of the audio file to test test_profile_ids -- an array of test profile IDs strings force_short_audio -- instruct the service to waive the recommended minimum audio limit ...
625941cacc40096d61595a0b
def test_counts_changes(self): <NEW_LINE> <INDENT> nt.eq_(self.test.counts.changes[1], 2)
summary.Counts.changes: contains a list of the number of differences between results
625941ca23e79379d52ee61e
def __init__(self, data_type, plot_widget=None, data_control_widget=None, *args, **kwargs): <NEW_LINE> <INDENT> super(DataToggle, self).__init__(*args, **kwargs) <NEW_LINE> self.data_type = data_type <NEW_LINE> self.plot_widget = plot_widget <NEW_LINE> self.data_control_widget = data_control_widget <NEW_LINE> self.togg...
Instantiates a DataToggle with given data_type and assigns a plot_widget and/or data_control_widget if necessary, and connects the QButton's toggle signal to the update() method :param data_types: str supported: 'Axis', 'Derivative', 'Isolate', 'Limit' 'Legend' :param plot_widget: QWidget that the toggle is to oper...
625941ca45492302aab5e37c
def validate_terminal_nodes(template_data, part_data, **kwargs): <NEW_LINE> <INDENT> N_parts = len(part_data) <NEW_LINE> terminal_nodes = template_data.get('terminal_nodes', '') <NEW_LINE> try: <NEW_LINE> <INDENT> for part_id, pred_flag in map(tuple, terminal_nodes.split(',')): <NEW_LINE> <INDENT> if not int(part_id) <...
The terminal nodes expression should be a comma-separate list of relation template part internal IDs and their relation part flags. For example: ``0s,1o`` refers to the subject of the first part and object of the second part.
625941cad53ae8145f87a32b
def get_task_list(label): <NEW_LINE> <INDENT> if label == '': <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> if label[0] != '[': <NEW_LINE> <INDENT> label = label[label.find(':') + 2:label.find(']')] <NEW_LINE> return [int(label)] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if label.find('[') != -1: <NEW_LINE> <IN...
Get an integer list of tasks from an edge label.
625941ca16aa5153ce362532
def unset(self): <NEW_LINE> <INDENT> self.__effects__ = {}
clear settings
625941ca85dfad0860c3af15
def is_scrollable_horizontally(self): <NEW_LINE> <INDENT> screen_width, _ = self.get_visible_area_size() <NEW_LINE> left_width = self.images[0].get_pixbuf() and self.images[0].get_pixbuf().get_width() or 0 <NEW_LINE> right_width = self.images[1].get_pixbuf() and self.images[1].get_pixbuf()...
Returns True when the displayed image does not fit into the display port horizontally and must be scrolled to be viewed completely.
625941cab57a9660fec3393d
def lookup_status(self, **params): <NEW_LINE> <INDENT> return self.post('statuses/lookup', params=params)
Returns fully-hydrated tweet objects for up to 100 tweets per request, as specified by comma-separated values passed to the id parameter. Docs: https://dev.twitter.com/docs/api/1.1/get/statuses/lookup
625941ca66673b3332b9214b
def __init__(self, defaults: dict = None) -> None: <NEW_LINE> <INDENT> LOGGER.debug('WalletManager.__init__ >>> defaults %s', defaults) <NEW_LINE> self._defaults = { 'storage_type': (defaults or {}).get('storage_type', None), 'freshness_time': int((defaults or {}).get('freshness_time', 0)), 'auto_create': bool((default...
Initializer for wallet manager. Store default values by dict key: - 'storage_type': storage type (default None) - 'freshness_time': freshness time (default indefinite) - 'auto_create': auto_create behaviour (default False) - 'auto_remove': auto_remove behaviour (default False) - 'key': access crede...
625941ca851cf427c661a5c9
def minimize(self, *args, **kwargs): <NEW_LINE> <INDENT> monitors = None <NEW_LINE> for monitors in self.iteropt(*args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return monitors
Optimize our loss exhaustively. This method is a thin wrapper over the :func:`iteropt` method. It simply exhausts the iterative optimization process and returns the final monitor values. Returns ------- train_monitors : dict A dictionary mapping monitor names to values, evaluated on the training dataset. vali...
625941cae8904600ed9f1fe7
def saveControlShapeToFile(name, icon, curve, filePath): <NEW_LINE> <INDENT> data = { 'name': name, 'icon': icon, 'sort': 100, 'curves': getShapeData(curve), } <NEW_LINE> with open(filePath, 'w') as fp: <NEW_LINE> <INDENT> yaml.dump(data, fp)
Save a control curve to a yaml file. Args: curve (PyNode): A curve transform node containing one or more curve shapes.
625941ca851cf427c661a5ca
def _EncodeMultipartFormData(fields, files): <NEW_LINE> <INDENT> BOUNDARY = '-M-A-G-I-C---B-O-U-N-D-A-R-Y-' <NEW_LINE> CRLF = '\r\n' <NEW_LINE> lines = [] <NEW_LINE> for key, value in fields: <NEW_LINE> <INDENT> lines.append('--' + BOUNDARY) <NEW_LINE> lines.append('Content-Disposition: form-data; name="%s"' % key) <NE...
Encode form fields for multipart/form-data. Args: fields: A sequence of (name, value) elements for regular form fields. files: A sequence of (name, filename, value) elements for data to be uploaded as files. Returns: (content_type, body) ready for httplib.HTTP instance. Source: http://code.google.com...
625941ca26068e7796caed98
def flux_integral(spectbl, wa=None, wb=None, normed=False): <NEW_LINE> <INDENT> if normed: <NEW_LINE> <INDENT> if 'normflux' not in spectbl.colnames: <NEW_LINE> <INDENT> spectbl = add_normflux(spectbl) <NEW_LINE> <DEDENT> <DEDENT> assert wa is None or wa >= spectbl['w0'][0] <NEW_LINE> assert wb is None or wb <= spectbl...
Compute integral of flux from spectbl values. Result will be in erg/s/cm2.
625941ca8c3a873295158475
def test_performer_raises(self): <NEW_LINE> <INDENT> calls = [] <NEW_LINE> eff = Effect("meaningless").on(error=calls.append) <NEW_LINE> performer = lambda d, i, box: raise_(ValueError("oh dear")) <NEW_LINE> dispatcher = lambda i: performer <NEW_LINE> perform(dispatcher, eff) <NEW_LINE> self.assertThat( calls, MatchesL...
When a performer raises an exception, it is passed to the error handler.
625941cabd1bec0571d906ea
def fit(self, env: gym.Env, nb_steps: int) -> None: <NEW_LINE> <INDENT> action_counter = 0 <NEW_LINE> episode_counter = 0 <NEW_LINE> nb_steps_digits = len(str(nb_steps)) <NEW_LINE> while action_counter < nb_steps: <NEW_LINE> <INDENT> env.reset() <NEW_LINE> done = False <NEW_LINE> episode_counter += 1 <NEW_LINE> while n...
Train the agent on the given proxy environment. :param env: the gym environment in which the agent is trained :param nb_steps: number of training steps to be performed :return: None
625941ca21a7993f00bc7da9
def set_host_records(self, sld, tld, host_records): <NEW_LINE> <INDENT> if host_records is None or len(host_records) == 0: <NEW_LINE> <INDENT> raise EnomAPIError('Cannot set host records: Missing hosts') <NEW_LINE> <DEDENT> parameters = {COMMAND: 'SetHosts', SLD: sld, TLD: tld} <NEW_LINE> for index, host_record in enum...
Set the host records for a domain sld, tld: The host and domain name (host.sld.tld) that you want to update in the DNS. For example, www.resellerdocs.com host_records is a list of dictionaries with these keys: name: subdomain (e.g. www, *, ...) type: The record type (A, AAAA, CNET etc.) ip: The IP address t...
625941ca5fdd1c0f98dc02ed
def _MergeMessage( node, source, destination, replace_message, replace_repeated): <NEW_LINE> <INDENT> source_descriptor = source.DESCRIPTOR <NEW_LINE> for name in node: <NEW_LINE> <INDENT> child = node[name] <NEW_LINE> field = source_descriptor.fields_by_name[name] <NEW_LINE> if field is None: <NEW_LINE> <INDENT> raise...
Merge all fields specified by a sub-tree from source to destination.
625941ca3cc13d1c6d3c7435
def handle_extended_ops(self, raw_data): <NEW_LINE> <INDENT> return False
Called by the main loop when an unknown command is found This can be used to support custom commands from a HydraClient without having to re-write the operation parser. This can be overridden as necessary when subclassing :class:`HydraWorker <multiprocessing.Process>`. Return True if the command was handled Return Fal...
625941ca7b25080760e39514
def close(self): <NEW_LINE> <INDENT> if self.closed is True: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.put_messge_in_q(CloseMessage()) <NEW_LINE> self.closed = True
Puts a None in the queue which leads to closing it.
625941ca7047854f462a14c5
def plotNative (protein_name, native, T, iteration, r, environ = ''): <NEW_LINE> <INDENT> legend = [] <NEW_LINE> from source.calc import get_native_list as get_native <NEW_LINE> native_list = get_native(protein_name) <NEW_LINE> fig, ax1 = plt.subplots() <NEW_LINE> print('Calculating Native State Probability...') <NEW_...
Functions plots the native state probability over a trajectory. protein_name is the name of the protein expressed as a string. See proteins native is a list of integer values reresenting the number of natiive contacts present at each MC step in a simulation trajectory T is the temperature of the simulation expressed...
625941ca21bff66bcd684a0e
def start_validation(self): <NEW_LINE> <INDENT> self.proceed_to_validation = False <NEW_LINE> self.validation_started_at = datetime.datetime.now()
Mark the attempt validation as started.
625941ca462c4b4f79d1d78b
def minMemory(self): <NEW_LINE> <INDENT> return self.data.min_memory
Returns the minimum amount of memory that frames in this layer require. :rtype: int :return: minimum kB of memory required by frames in this layer
625941ca76d4e153a657ebeb
def __iter__(self): <NEW_LINE> <INDENT> for x in self.zipFile.namelist(): <NEW_LINE> <INDENT> yield self.zipFile.open(x)
Iteractor object yielding file object from zipfile collection
625941cbd10714528d5ffd9d
def is_invalid_comment(self): <NEW_LINE> <INDENT> return self._tag == 'invalid_comment'
Check if the union tag is ``invalid_comment``. :rtype: bool
625941cade87d2750b85fe4d
def get_user_info(user_name = '', account_id = 0): <NEW_LINE> <INDENT> if user_name is not None and account_id is not None: <NEW_LINE> <INDENT> print("\nTest name and id are: " + user_name + ', ' + str(account_id)) <NEW_LINE> <DEDENT> if user_name and account_id == 0: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> accoun...
Get user information by name or id. Prints information with approximated age based on today's year minus signup date's year added to age. Return: None (prints information) Parameters: user_name (string) account_id (int)
625941ca6aa9bd52df036e5f
def make_dirs(path, mode=0o700, exist_ok=True): <NEW_LINE> <INDENT> os.makedirs(path, mode=mode, exist_ok=exist_ok)
Create the directory for a path given
625941ca4e696a04525c9506
def test_weighted_multi_example_train(self): <NEW_LINE> <INDENT> head = head_lib.RegressionHead(weight_column='label_weights') <NEW_LINE> self.assertEqual(1, head.logits_dimension) <NEW_LINE> features = { 'x': np.array(((42,), (43,), (44,)), dtype=np.float32), 'label_weights': np.array(((1.,), (.1,), (1.5,)), dtype=np....
1d label, 3 examples, 1 batch.
625941cb50485f2cf553ce54
def list_audiorooms(config=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> instance = janus._create_instance(config) <NEW_LINE> plugin = janus._attach_plugin(instance['id'], "janus.plugin.audiobridge") <NEW_LINE> message = {"request": "list"} <NEW_LINE> resp = janus._message_request(instance['id'], plugin['id'], me...
List the current list of audiorooms availables in Janus service instance CLI example: .. code-block:: bash salt '*' janus.list_audiorooms
625941cba79ad161976cc200
def __str__(self) -> str: <NEW_LINE> <INDENT> return ( f"Configured to construct nodes and weights {self._description} with options " f"{format_options(self._specification_options)}." )
Format the configuration as a string.
625941cbf7d966606f6aa0be
def confirm_or_cancel(*args, **kwds): <NEW_LINE> <INDENT> return alert3('caution', *args, **kwds)
Displays a 3-button alert of type 'caution'. See alert3().
625941cb377c676e91272263
def __init__(self, db_name="subscriptors.db", verbose=False): <NEW_LINE> <INDENT> self.__verbose__ = verbose <NEW_LINE> self.__db_name__ = db_name <NEW_LINE> if not os.path.exists('private_key.pem'): <NEW_LINE> <INDENT> self.__print__("No private_key.pem file found") <NEW_LINE> Vapid().save_key('private_key.pem') <NEW_...
Class constructor. :param db_name: The [optional] name ("subscriptors.db" by default) of the file in which subscriptions will be stored in. This is only required if methods like ``newSubscription`` will be used. :type db_name: str :param verbose: An optional value, to enabl...
625941cb8e71fb1e9831d864
@pytest.mark.parametrize('tags', [('B-BRAWLER', 'I-BRAWLER', 'I-BRAWLER')]) <NEW_LINE> def test_issue2385_iob_bcharacter(tags): <NEW_LINE> <INDENT> assert iob_to_biluo(tags) == ['B-BRAWLER', 'I-BRAWLER', 'L-BRAWLER']
fix bug in labels with a 'b' character
625941cb379a373c97cfabff
def test_base36encode_ok(self): <NEW_LINE> <INDENT> self.assertEqual(base36encode(666), 'ii')
Test if base36encoding works
625941cb56ac1b37e626428b
def parse_raw_emails(newSites, text): <NEW_LINE> <INDENT> ptext = [] <NEW_LINE> if len(newSites)>0: <NEW_LINE> <INDENT> for i in newSites: <NEW_LINE> <INDENT> ptext.append(pyzmail.PyzMessage.factory(text[i][b'BODY[]'])) <NEW_LINE> <DEDENT> return ptext <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sys.exit('No new site...
Parse imapObj.fetch object into PyzMessage object.
625941cb6fece00bbac2d7f9