text
stringlengths
48
9.16k
def test_slow_shattered(self): """The port number is received slowly in chunks.""" # start() # As the lock is mocked out, this provides a mox expectation. with self.proxy._process_lock: safe_subprocess.start_process_file( args=['/runtime'], input_string=self.runtime_config.SerializeToString(...
def IsComplete(self): return self.message and self.message[-1] == '\n'
def ByteSize(self): n = 0 n += self.lengthString(len(self.status_)) return n + 1
def v3_reference_to_group(self, v3_ref, group): """Converts a v3 Reference to a v3 Path representing the entity group. The entity group is represented as an entity_pb.Path containing only the first element in the provided Reference. Args: v3_ref: an entity_pb.Reference group: an entity_pb.Path to popu...
def _local_grad(self, parent, d_out_d_self): parent_shape = self._parents[parent].shape num_singletons = len(d_out_d_self.shape) - len(parent_shape) if num_singletons > 0: extra_singletons = tuple(range(num_singletons)) result = np.sum(d_out_d_self, axis=extra_singletons, keepdims=False) ...
def getcallargs(func, *positional, **named): """Get the mapping of arguments to values. A dict is returned, with keys the function argument names (including the names of the * and ** arguments, if any), and values the respective bound values from 'positional' and 'named'.""" args, varargs, varkw, d...
@staticmethod def compute_interval(distribution, alpha): alpha_lower, alpha_upper = (alpha / 2.0, 1 - alpha / 2.0) return np.percentile(distribution, 100 * alpha_lower), np.percentile(distribution, 100 * alpha_upper)
def GsBucketURL(self, bucket_name): return 'https://%s/%s/' % (self.GS_API_HOSTNAME, bucket_name)
def update_video_views(gplus_id): """Iterate through ActivityRecords and get video views""" logging.info('Updating Video Views') # build the service object of the yt api API_KEY = get_server_api_key() yt_service = build('youtube', 'v3', developerKey=API_KEY) # get the activities for the gde ...
def mail_message_to_mime_message(protocol_message): """Generate a MIMEMultitype message from protocol buffer. Generates a complete MIME multi-part email object from a MailMessage protocol buffer. The body fields are sent as individual alternatives if they are both present, otherwise, only one body part is sen...
@staticmethod def MergeSkipFiles(skip_files_one, skip_files_two): if skip_files_one == SKIP_NO_FILES: return skip_files_two if skip_files_two == SKIP_NO_FILES: return skip_files_one return validation.RegexStr().Validate( [skip_files_one, skip_files_two], SKIP_FILES)
def get_prep_value(self, value): if value is not None: return int(value) return super(SaneTimeField,self).get_prep_value(value)
def MergeFrom(self, x): assert x is not self if (x.has_time()): self.set_time(x.time()) if (x.has_level()): self.set_level(x.level()) if (x.has_log_message()): self.set_log_message(x.log_message()) if (x.has_source_location()): self.mutable_source_location().MergeFrom(x.source_location())
def predictive_log_likelihood(self, Xtest, data_index=0, Npred=100): """ Hacky way of computing the predictive log likelihood :param X_pred: :param data_index: :param M: :return: """ Tpred = Xtest.shape[0] # Sample particle trajectories preds = self.states_list[data_index].sampl...
def shutdown(sts, mode): print(mode + 'ing Appliance') ret = sts.shutdown(mode) pprint(ret)
def __rmod__(self, other): return other % self.value
def execute_pre_save_hooks(kind, pb_key, entity): put_type_id = put_type.UNKNOWN func_list = pre_save_hooks.get(kind, None) if func_list is not None: key = db.Key._FromPb(pb_key) if not key.id_or_name(): path = key.to_path()[:-1] path.append(1) model_key = db.Key.from_path(*path) i...
def test_template_name_change_based_on_ajax_request(self): view = self._prepare_view(forms.views.ModalFormView, dict(HTTP_X_REQUESTED_WITH='XMLHttpRequest')) self.assertEqual(view.get_template_names(), '_' + view.template_name) view = self._prepare_view(form...
def __init__(self, application, response_wrapper=None, use_cookies=True): self.application = application if response_wrapper is None: response_wrapper = lambda a, s, h: (a, s, h) self.response_wrapper = response_wrapper if use_cookies: self.cookie_jar = _TestCookieJar() else: ...
def average( values ) : return sum( values ) / len( values )
def testWindowParent( self ) : parentWindow1 = GafferUI.Window() parentWindow2 = GafferUI.Window() childWindow = GafferUI.Window() childWindowWeakRef = weakref.ref( childWindow ) self.failUnless( parentWindow1.parent() is None ) self.failUnless( parentWindow2.parent() is None ) self.failUnless( childWindow.par...
def setVisible( self, visible ) : if visible == self.getVisible() : return self.__visibilityAnimation = _VisibilityAnimation( self._qtWidget(), visible ) self.__visibilityAnimation.start()
def commit(self): self.log('in commit') for p in [c for c in self.block_candidates.values() if c.block.prevhash == self.head.hash]: assert isinstance(p, BlockProposal) ls = self.heights[p.height].last_quorum_lockset if ls and ls.has_quorum == p.blockhash: self.store_proposal(...
def _updateFromPlug( self ) : view = self.getPlug().node() ## \todo We're getting the context from the view because our # own context hasn't been set properly. We need to fix that # properly, I think by having some sort of ContextSensitiveWidget # base class which inherits contexts from parents. with view.getCo...
def updateSystem(name, profile_name, mac_address, ip_address): cobbler_handle = xmlrpclib.Server("http://"+cobbler_server+"/cobbler_api") ltoken = cobbler_handle.login(cobbler_user, cobbler_password) system_id = cobbler_handle.new_system(ltoken) cobbler_server_conn.modify_system(system_...
def __revertToSavedAvailable( menu ) : scriptWindow = menu.ancestor( GafferUI.ScriptWindow ) script = scriptWindow.scriptNode() if script["fileName"].getValue() and script["unsavedChanges"].getValue() : return True return False
def testSliceDel( self ) : c = GafferUI.ListContainer( GafferUI.ListContainer.Orientation.Vertical ) ca = TestWidget( "a" ) cb = TestWidget( "b" ) cc = TestWidget( "c" ) self.assert_( ca.parent() is None ) self.assert_( cb.parent() is None ) self.assert_( cc.parent() is None ) c.append( ca ) self.assert_( c...
def __updateChildNameChangedConnection( self, child ) : if self.__parent.isSame( child.parent() ) : if child not in self.__childNameChangedConnections : self.__childNameChangedConnections[child] = child.nameChangedSignal().connect( Gaffer.WeakMethod( self.__childNameChanged ) ) else : if child in self.__child...
def testEnabled( self ) : w = GafferUI.MultiSelectionMenu() w.append("A") w.append("B") # Test the return type self.assertTrue( isinstance( w.getEnabledItems(), list ) ) # Test that a single element can be enabled. w.setEnabledItems( "A" ) self.assertEqual( w.getEnabledItems(), ["A"] ) self.assertEqual( w.ge...
def sniffer(genre, host, item_aliases, provider_config=default_settings.PROVIDERS): all_metrics_providers = [provider.provider_name for provider in ProviderFactory.get_providers(provider_config, "metrics")] if "arxiv" in item_aliases: # for these purposes host = "arxiv" ...
def _updateFromPlug( self ) : self.__selectionMenu.setEnabled( self._editable() ) if self.getPlug() is not None : with self.getContext() : plugValue = self.getPlug().getValue() for labelAndValue in self.__labelsAndValues : if labelAndValue[1] == plugValue : with Gaffer.BlockedConnection( self.__sel...
def sm_flow_3(self): """Type: Flow or Auxiliary """ return (self.sm_stock_2()-self.sm_stock_3())/self.per_stock_adjustment_time()
def readStructBegin(self): assert self.state in (CLEAR, CONTAINER_READ, VALUE_READ), self.state self.__structs.append((self.state, self.__last_fid)) self.state = FIELD_READ self.__last_fid = 0
def just_finished_profile_refresh(self): refresh_status = self.get_refresh_status() if refresh_status.refresh_state == RefreshStatus.states["PROGRESS_BAR"] and \ refresh_status.is_done_refreshing: return True return False
def setUp( self ) : GafferTest.TestCase.setUp( self ) open( self.temporaryDirectory() + "/a", "w" ) open( self.temporaryDirectory() + "/b.txt", "w" )
def testSymLinkInfo( self ) : with open( self.temporaryDirectory() + "/a", "w" ) as f : f.write( "AAAA" ) os.symlink( self.temporaryDirectory() + "/a", self.temporaryDirectory() + "/l" ) # symlinks should report the info for the file # they point to. a = Gaffer.FileSystemPath( self.temporaryDirectory() + "/a"...
def get_all(self, key, column_count=100, yield_batch=False, **kwargs): kwargs['key'] = key kwargs['column_count'] = column_count results = self.get(**kwargs) result_count = len(results) if yield_batch: k = next(reversed(results)) yield results else: for k, v in results.iteritems(): yield k...
def test_signup(suite): result = _call('auth/users.signup', data={ 'username': 'signup', 'password': 'password', 'email': 'signup@sondra.github.com', 'given_name': "Jefferson", 'family_name': "Heard" }) assert result.ok, result.text assert 'signup' in suite['auth...
def get_next_task(self): """get the next task if there's one that should be processed, and return how long it will be until the next one should be processed.""" if _debug: TaskManager._debug("get_next_task") # get the time now = _time() task = None delta = None if self.tasks: ...
def test_remove_connection(self): self.worker.set_connections(self.worker_addresses) sleep(0.1) self.assertTrue(self.worker_addresses[0] in self.worker.active_connections) self.assertTrue(self.worker_addresses[1] in self.worker.active_connections) self.assertTrue(self.worker_addresses[2] in self.worker.active...
def _build_request_url(self, params, kwargs, post=False): """ Build URL to send API query to. - params: dictionary of parameters - kwargs: urlencoded contents of params - post: boolean """ if post: return '%s%s' % (self.endpoint, self.methodname) else: return '%s%s...
def confirmation(self, pdu): if _debug: BIPForeign._debug("confirmation %r", pdu) # check for a registration request result if isinstance(pdu, Result): # if we are unbinding, do nothing if self.registrationStatus == -2: return ### make sure we have a bind request in pro...
def enable_recompress(self): """Enable the recompress button.""" self.ui.recompress.setEnabled(True) if QSystemTrayIcon.isSystemTrayAvailable() and not self.cli: self.systemtray.recompress.setEnabled(True)
def _print_msg(self, stream, msg, record): same_line = hasattr(record, 'same_line') if self.on_same_line and not same_line: stream.write(self.terminator) stream.write(msg) if same_line: self.on_same_line = True else: stream.write(self.terminator) self.on_same_line = F...
def testCoshaderType( self ) : coshader = self.compileShader( os.path.dirname( __file__ ) + "/shaders/coshader.sl" ) coshaderNode = GafferRenderMan.RenderManShader() coshaderNode.loadShader( coshader ) self.assertEqual( coshaderNode.state()[0].type, "ri:shader" )
def create_group(self, bucket_id, group_id, members=None): if members is None: group = MINIMALIST_GROUP else: group = {'data': {'members': members}} group_url = '/buckets/%s/groups/%s' % (bucket_id, group_id) self.app.put_json(group_url, group, headers=self.headers,...
def test_create_api_key(self): key = self.app.apikeys.create() keys = self.app.apikeys.all() self.assertTrue(key.key in [k.key for k in keys])
def _inner(value): if not (low <= value <= high): raise ValueError('{} not in range ({}, {})'.format(value, low, high)) if step: value = round((value - low) / step) * step + low return value
def test(self, exercise): _, _, err = self.run(["make", "clean", "all", "run-test"], exercise) ret = [] testpath = path.join(exercise.path(), "test", "tmc_test_results.xml") if not path.isfile(testpath): return [TestResult(success=False, message=err)] if len(err) > 0: ret.append(Te...
@contextmanager def timer(s): t0 = time.time() yield debug("%s (%.2f)" % (s, time.time() - t0))
def load_registry(db, registry_data, datalang='en'): for item in registry_data: typ = item['Type'] if typ == 'language': db.add_language(item, datalang, name_order=10) elif typ == 'extlang': db.add_extlang(item, datalang) elif typ in {'grandfathered', 'redunda...
def asByte(self): """ Name: BitField.asByte() Args: None Desc: Returns the value of the bitfield as a byte. >>> bf = BitField() >>> bf.fromByte(123) # Modifies bf in place >>> bf.bit4 = 0 >>> print bf.asByte() 107 """ byteVal = 0 for i, v in enumerate(reversed(self.r...
@properties.setter def properties(self, value): """The properties property. Args: value (hash). the property value. """ if value == self._defaults['properties'] and 'properties' in self._values: del self._values['properties'] else: self._values['properties'] = value
@user_id.setter def user_id(self, value): """The user_id property. Args: value (string). the property value. """ if value == self._defaults['userId'] and 'userId' in self._values: del self._values['userId'] else: self._values['userId'] = value
def run_viterbi(initial_scores, transition_scores, final_scores, emission_scores): length = np.size(emission_scores, 0) # Length of the sequence. num_states = np.size(initial_scores) # Number of states. # Variables storing the Viterbi scores. viterbi_scores = np.zeros([length, num_states]) # V...
def botcommand(*args, **kwargs): """Decorator for bot command function""" def decorate(function, hidden=False, admin=False, name=None, need_arg=False): function._zxLoLBoT_command = True function._zxLoLBoT_command_name = name or function.__name__ function._zxLoLBoT_command_admin = admin ...
def save_supplies(self, data): url = self._construct_url(addl=['supplies', ]) entity, _ = super(Strategy, self)._post(PATHS['mgmt'], url, data) self._update_self(next(entity)) self._deserialize_target_expr() if 'relations' in self.properties: del self.properties['relations']
def ArrayOf(klass): """Function to return a class that can encode and decode a list of some other type.""" global _array_of_map global _array_of_classes, _sequence_of_classes # if this has already been built, return the cached one if klass in _array_of_map: return _array_of_map[klass] ...
def reconstruct(self,rows): if rows is None: U = self.U else: U = np.asfortranarray(self.U[rows,:]) return U.dot(self.V.T + self.X.dot(self.W).T)
def add_response_code_stats(self, stats): for code in self.STATUS_CODES: self.add_derive_value('Requests/Response/%s' % code, 'requests', stats[str(code)].get('current', 0))
@property def account_acquisition_date(self): """The account_acquisition_date property. Returns: (string). the property value. (defaults to: None) """ if 'ai.user.accountAcquisitionDate' in self._values: return self._values['ai.user.accountAcquisitionDate'] return self._defaults...
def collect_numerals(z3term): if z3.is_int_value(z3term) or z3.is_bv_value(z3term): yield z3term elif z3.is_app_of(z3term,z3.Z3_OP_ITE): yield collect_numerals(z3term.arg(1)) yield collect_numerals(z3term.arg(2))
def __getitem__(self, key): val = self.get(key) if val: return val raise KeyError('%s not found' % key)
def decompress(self, value): if value is not None: return list(value) else: return ['', {}]
def get_image_url(self, file_id, size=None, include_filename=True): """Return an image significant URL In: - ``file_id`` -- file identifier - ``size`` -- size to get (thumb, medium, cover, large) - ``include_filename`` -- add the filename to the URL or not Return: - image si...
def _check_for_overlaps(self): '''make sure that cases with different rvals aren't overlapping''' for outer in self.cases: for inner in self.cases: #if the return vals are the same, it doesn't really matter if they blend together. if self.cases[inner]['rval'] != self.cases[outer]...
def validate_old_password(self, value): """Check old password In: - ``value`` -- old password Return: - password value if value is the old password """ if len(value) == 0 or security.get_user().data.check_password(value): return self.validate_password(value) raise ValueError(_...
def get_tokens(self): query = DataToken.query.filter_by(username=self.username) query = query.filter(DataToken.action.like(self.action + '%')) return query
def __init__(self): if self._entry_point is None: raise AttributeError('Plugins must declare their entry point namespace in a _entry_point class attribute') if self._name is None: raise AttributeError('Plugins must declare their entry point name in a _name class attribute')
def test_missing_required_permissions(self): other_user = User.objects.create_user('OtherGuy') self.client.force_authenticate(user=other_user) patch_dict = { 'description': "renamed %s" % uuid.uuid4(), } response = self.client.patch(self.item_url, patch_dict) self.assertEqual(response....
def test_modify_job(self): headers = {'Content-Type': 'application/json; charset=UTF-8'} data = { 'job_class_string': 'hello.world', 'name': 'hello world job', 'minute': '*/5'} response = self.fetch(self.JOBS_URL, method='POST', headers=headers, body=json.du...
def run(cmd, args, cb=True): if AsyncError: M._log(1, 'AsyncError %s' % repr(AsyncError)) M.logout() typ, val = AsyncError raise typ(val) if not M.debug: M._log(0, '%s %.100s' % (cmd, args)) try: if cb: typ, dat = getattr(M, cmd)(callback=responder, cb_arg...
def buildPlotInfo(self, seriesInfo): #remove all of the nodatavalues from the pandas table filteredData = seriesInfo.dataTable[seriesInfo.dataTable["DataValue"] != seriesInfo.noDataValue] val = filteredData["Month"].map(calcSeason) filteredData["Season"] = val # construct tasks for the task server ...
def test_collections_datatable(self): url = '/api/collections/%d/datatable/' % self.Collection1.pk response = json.loads(self.client.get(url, follow=True).content) collection_name = "not found" for prop in response['aaData']: if prop[0] == 'name': collection_name = prop[1] ...
def _normalize(self): # Step 1: Normalize the chunks so that all runs of identical charsets # get collapsed into a single unicode string. chunks = [] last_charset = None last_chunk = [] for string, charset in self._chunks: if charset == last_charset: last_chunk.append(string)...
def _dump_ur(self, lvl): if lvl > self.debug: return l = self.untagged_responses # NB: bytes array if not l: return t = '\n\t\t' l = ['%s: "%s"' % (x[0], x[1][0] and b'" "'.join(x[1]) or '') for x in l] self.debug_lock.acquire() self._mesg('untagged responses dump:%s%s' % ...
def test_rpc_delete(self): self._connecting_to_connected() self.protocol.router.addContact(self.protocol.sourceNode) # Set a keyword to store m = message.Message() m.messageID = digest("msgid") m.sender.MergeFrom(self.protocol.sourceNode.getProto()) m.command = message.Command.Value("STORE"...
def set_writer(self, writer): """ Changes the writer function to handle writing to the text edit. A writer function must have the following prototype: .. code-block:: python def write(text_edit, text, color) :param writer: write function as described above. """ if self._writer !=...
def onEditDelPoint(self, event): dataframe = self.parent.getRecordService().get_filtered_points() try: self.isEmptySelection(dataframe) except EmptySelection: wx.MessageBox("There are no points to delete", 'Delete Points', wx.OK | wx.ICON_WARNING, parent=self.parent) ...
def header_store_parse(self, name, value): """+ The name is returned unchanged. If the input value has a 'name' attribute and it matches the name ignoring case, the value is returned unchanged. Otherwise the name and value are passed to header_factory method, and the resulting custom header object...
@presentation.render_for(Icon) def render_Icon(self, h, comp, *args): if self.title is not None: h << h.i(class_=self.icon, title=self.title) h << self.title else: h << h.i(class_=self.icon, title=self.title) return h.root
def body_encode(self, string): """Body-encode a string by converting it first to bytes. The type of encoding (base64 or quoted-printable) will be based on self.body_encoding. If body_encoding is None, we assume the output charset is a 7bit encoding, so re-encoding the decoded string using the asci...
def test_cleanup_rows_buffered(self): conn = self.test_connection cursor = conn.cursor(pymysql.cursors.Cursor) cursor.execute("select * from test as t1, test as t2") for counter, row in enumerate(cursor): if counter > 10: break del cursor self.safe_gc_collect() c2 = co...
def set_ntp_servers(self, primary, secondary=None): self._logger.debug("Set ntp-servers: primary:%s secondary:%s" % (primary, secondary)) self.set_config_changed() xpath = pandevice.XPATH_DEVICECONFIG_SYSTEM xpath61 = pandevice.XPATH_DEVICECONFIG_SYSTEM + "/ntp-servers" # Path is different depending...
@responder(pattern="^!(?P<source>.+)", form="!<code>", help="Execute some python code") def python(conversation, source): from droned.entity import namespace source = source.strip() try: code = compile(source, '<jabber>', 'eval') except: try: code = compile(source, '<jabber>'...
def __init__( self, logger ): """ Initialize the base class and validate the logger component. @param logger: the ILogger object tasked with dispatching debug messages. @type logger: ILogger """ self.logger = logger self.re_address = re.compile( '^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[...
def think(self): if self.active_state is None: return self.active_state.do_actions() new_state_name = self.active_state.check_conditions() if new_state_name is not None: self.set_state(new_state_name)
def intersects(self, shape): try: return shape.intersects_sphere(self) except AttributeError: raise TypeError( "No 'intersects_sphere' method supplied by %s" % type(shape) )
def to_message(base): """ Given a MailBase, this will construct a MIME part that is canonicalized for use with the Python email API. """ ctype, ctparams = base.get_content_type() if not ctype: if base.parts: ctype = 'multipart/mixed' else: ctype = 'text/p...
def append(self, item): kv = item.split(b':', 1) if len(kv) > 1 and kv[0].lower() == b'content-length': self.content_length = kv[1].strip() list.append(self, item)
def get_node(node_to_ask): def parse_response(response): if response[0] and response[1][0] == "True": return True if not response[0]: self.send_message(Node(unhexlify(buyer_guid)), buyer_enc_key.encode(), objects.Pla...
def draw_quad(x, y, z, w, h): # Send four vertices to draw a quad glBegin(GL_QUADS) glTexCoord2f(0, 0) glVertex3f(x-w/2, y-h/2, z) glTexCoord2f(1, 0) glVertex3f(x+w/2, y-h/2, z) glTexCoord2f(1, 1) glVertex3f(x+w/2, y+h/2, z) glTexCoord2f(0, 1) glVertex3f(x-w/2, y+h/2...
def stero_pan(x_coord, screen_width): right_volume = float(x_coord) / screen_width left_volume = 1.0 - right_volume return (left_volume, right_volume)
def formfield_for_manytomany(self, db_field, request=None, **kwargs): field = super(GroupTabularPermissionsAdminBase, self).formfield_for_manytomany(db_field, request, **kwargs) if db_field.name == 'permissions': field.widget = TabularPermissionsWidget(db_field.verbose_name, db_field.name in self.filter...
def __set_api_key(self): if self.api_key is None: self.keygen() self._log(DEBUG1, 'autoset api_key: "%s"', self.api_key)
def prompt(name, default=None): """ Grab user input from command line. :param name: prompt text :param default: default value if no input provided. """ prompt = name + (default and ' [%s]' % default or '') prompt += name.endswith('?') and ' ' or ': ' while True: rv = input(prom...
def test_simulate_ergodicity(): P = [[0.4, 0.6], [0.2, 0.8]] stationary_dist = [0.25, 0.75] init = 0 mc = MarkovChain(P) seed = 4433 ts_length = 100 num_reps = 300 tol = 0.1 x = mc.simulate(ts_length, init=init, num_reps=num_reps, random_state=seed) frequency_1 = x[:, -1].mean(...
def get_liberties(state, maximum=8): """A feature encoding the number of liberties of the group connected to the stone at each location Note: - there is no zero-liberties plane; the 0th plane indicates groups in atari - the [maximum-1] plane is used for any stone with liberties greater than or equal to maximum -...
def test_bad_request(): assert '400 BAD REQUEST' == current_app.test_client().get('/examples/alerts/modal').status assert '400 BAD REQUEST' == current_app.test_client().get('/examples/alerts/modal?flash_type=success').status
def validate_user(val): if val is None: return os.geteuid() if isinstance(val, int): return val elif val.isdigit(): return int(val) else: try: return pwd.getpwnam(val).pw_uid except KeyError: raise ConfigError("No such user: '%s'" % val)