code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def set(self, key, value): <NEW_LINE> <INDENT> key_hash = hash(key) <NEW_LINE> new_record = HashTableRecord( key=key, value=value, previous=None, next=None, ) <NEW_LINE> record = self._table[key_hash] <NEW_LINE> if record is None: <NEW_LINE> <INDENT> self._table[key_hash] = new_record <NEW_LINE> self._size += 1 <NEW_LI...
Set a value in the table. If an existing value exists for this key it is overwritten
625941c78a349b6b435e81ab
def _compute_bot_car_lane_changes(self): <NEW_LINE> <INDENT> bot_cars_trajectories = [] <NEW_LINE> for i_bot_car, lane_change_end_time in enumerate(self.bot_cars_lane_change_end_times): <NEW_LINE> <INDENT> if self.current_sim_time >= lane_change_end_time: <NEW_LINE> <INDENT> if lane_change_end_time > 0.0: <NEW_LINE> <I...
Compute the bot car lane change splines and update bot car lane change end times
625941c7d6c5a10208144082
def test_create_event(self, init_manager, mocker): <NEW_LINE> <INDENT> mock_events = mocker.patch.object( houdini_toolbox.events.manager.HoudiniEventManager, "events", new_callable=mocker.PropertyMock, ) <NEW_LINE> mock_factory = mocker.patch("houdini_toolbox.events.manager.HoudiniEventFactory") <NEW_LINE> mock_event =...
Test creating an event.
625941c750812a4eaa59c35b
def addOnCreate(call,args,kwargs,nodeClass): <NEW_LINE> <INDENT> pass
Add code to execute when a node is created or undeleted
625941c71d351010ab855b54
def __repr__(self): <NEW_LINE> <INDENT> string = "" <NEW_LINE> for dessert in self.desserts: <NEW_LINE> <INDENT> string += repr(dessert) + '\n' <NEW_LINE> <DEDENT> return string
Nice formatting of dessert list objects in Python shell
625941c7e1aae11d1e749cee
def create_post(self, path, **kw): <NEW_LINE> <INDENT> content = kw.pop('content', None) <NEW_LINE> onefile = kw.pop('onefile', False) <NEW_LINE> kw.pop('is_page', False) <NEW_LINE> metadata = {} <NEW_LINE> metadata.update(self.default_metadata) <NEW_LINE> metadata.update(kw) <NEW_LINE> if not metadata['description']: ...
Create a new post.
625941c729b78933be1e56e6
def read_file(self, location): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return YAML(typ="safe").load(open(location)) <NEW_LINE> <DEDENT> except (ruamel.yaml.parser.ParserError, ruamel.yaml.scanner.ScannerError) as error: <NEW_LINE> <INDENT> raise self.BadFileErrorKls( "Failed to read yaml", location=location, error...
Read in a yaml file and return as a python object
625941c7cdde0d52a9e5306a
def best_model_from_dir(basename): <NEW_LINE> <INDENT> models = glob.glob(basename + '*.index') <NEW_LINE> best_model = None <NEW_LINE> models_out = [] <NEW_LINE> for m in models: <NEW_LINE> <INDENT> match = re.match(re.escape(basename) + '(1?[0-9]{4}).index', m) <NEW_LINE> if match: <NEW_LINE> <INDENT> models_out.appe...
Return best saved model from basename.
625941c7091ae35668666f98
def multipartite(corpus, featureset_names, min_weight=1, filters={}): <NEW_LINE> <INDENT> pairs = Counter() <NEW_LINE> node_type = {corpus._generate_index(p): {'type': 'paper'} for p in corpus.papers} <NEW_LINE> for featureset_name in featureset_names: <NEW_LINE> <INDENT> ftypes = {} <NEW_LINE> featureset = _get_featur...
A network of papers and one or more featuresets.
625941c74f6381625f114a74
def main(): <NEW_LINE> <INDENT> backup_args = None <NEW_LINE> try: <NEW_LINE> <INDENT> freezer_config.config(args=sys.argv[1:]) <NEW_LINE> freezer_config.setup_logging() <NEW_LINE> backup_args = freezer_config.get_backup_args() <NEW_LINE> if backup_args.config: <NEW_LINE> <INDENT> if backup_args.log_config_append: <NEW...
freezer-agent binary main execution
625941c7d99f1b3c44c675c8
def GetStates(self, clients=None, names=None, name_blocks=None): <NEW_LINE> <INDENT> if names and len(names) == 1 and clients and len(clients) == 1: <NEW_LINE> <INDENT> op = self.dao.StateGet(clients[0], names[0]) <NEW_LINE> if op.success and op.response_value[1] is not None: <NEW_LINE> <INDENT> states = [op.response_v...
Retrieve the raw State object(s). If the client_id or name arguments are None or empty then the State(s) are retrieved for all clients or names respectively. Args: clients - Client IDs string to retrieve state objects for. If None then all clients are retrieved. names - List of Taba Names to retrieve state o...
625941c7a219f33f346289a4
def user_page(request, user): <NEW_LINE> <INDENT> user = get_object_or_404(User, username=user) <NEW_LINE> profile = user.get_profile() <NEW_LINE> acl_projects = Project.objects.all_acl(request.user) <NEW_LINE> all_changes = Change.objects.filter( user=user, translation__subproject__project__in=acl_projects, ) <NEW_LIN...
User details page.
625941c7283ffb24f3c5593b
def events(self): <NEW_LINE> <INDENT> events = Event.objects.for_date(self.date, forward=datetime.timedelta(days=2)) <NEW_LINE> return events.order_by('start_day', 'start_time')[:10]
Grabs the events that should appear in this issue.
625941c7baa26c4b54cb1159
def train(self, num_epochs, metric_frequency=0, validation_frequency=0, trace_frequency=0): <NEW_LINE> <INDENT> self.session.run(self.initialization_operation) <NEW_LINE> self.reset_timer() <NEW_LINE> for _ in xrange(num_epochs): <NEW_LINE> <INDENT> self.shuffle() <NEW_LINE> for step in xrange(int(np.ceil(self.training...
Generate a classification prediction using the passed in data
625941c794891a1f4081bae1
def UsesIPv6Connection(host, port): <NEW_LINE> <INDENT> return any(t[0] == socket.AF_INET6 for t in socket.getaddrinfo(host, port))
Returns True if the connection to a given host/port could go through IPv6.
625941c724f1403a92600ba0
def initialize(self): <NEW_LINE> <INDENT> import importlib <NEW_LINE> self.examples = OrderedDict() <NEW_LINE> for filename in EXAMPLE_FILES: <NEW_LINE> <INDENT> m = importlib.import_module(filename) <NEW_LINE> for label, example in m.examples.items(): <NEW_LINE> <INDENT> self.examples[label] = example <NEW_LINE> <DEDE...
Initialize application.
625941c7f9cc0f698b140635
def move(self, instructions: str) -> None: <NEW_LINE> <INDENT> for instruction in instructions: <NEW_LINE> <INDENT> if instruction == 'A': <NEW_LINE> <INDENT> self.coordinates = self.new_coordinates() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.direction = self.new_direction(instruction)
Move the robot from a list of instructions
625941c7bf627c535bc13207
def do_set_excitation(self,param): <NEW_LINE> <INDENT> logging.debug(__name__ + ' : setting the excitation parameter for the instrument') <NEW_LINE> self.connectToAVS() <NEW_LINE> self._visainstrument.write('EXC%s' %param)
Set the excitation parameter of AVS Input: param(int)= 0 : no excitation 1 : 3muV 2 : 10muV 3 : 30muV 4 : 100muV 5 : 300muV 6 : 1mV 7 : 3mV Output: None
625941c7b5575c28eb68e038
def hex2Upper(self, _hexs, _hexsOff, _hexsLen, _costHexsLen, _result, _resultOff, _resultLen): <NEW_LINE> <INDENT> tempChars = [b'' for _ in range(_hexsLen // 2 + 1)] <NEW_LINE> costBits = 0 <NEW_LINE> _, _result, _costHexsLen = self.hex2Chars(_hexs, _hexsOff, _hexsLen, _costHexsLen, tempChars, 0, _resultLen * 5 if _re...
Taken From Java APK Source Code
625941c7f7d966606f6aa03b
def get_next_available_key(iterable, key, midfix="", suffix="", is_underscore=True, start_from_null=False): <NEW_LINE> <INDENT> if start_from_null and key + suffix not in iterable: <NEW_LINE> <INDENT> return key + suffix <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> i = 0 <NEW_LINE> underscore = "_" if is_underscore el...
Get the next available key that does not collide with the keys in the dictionary.
625941c7498bea3a759b9ae8
def walk(root_path, type_filter=None, pattern=None, return_basename=False): <NEW_LINE> <INDENT> assert os.path.exists(root_path) <NEW_LINE> paths = [os.path.join(root_path, p) for p in os.listdir(root_path)] <NEW_LINE> paths = sorted(paths) <NEW_LINE> if type_filter in ('file',): type_filter = os.path.isfile <NEW_LINE>...
Find all required contents under the given path
625941c70c0af96317bb8220
def __create_messages(self, metrics_array): <NEW_LINE> <INDENT> metrics = [] <NEW_LINE> for m in metrics_array: <NEW_LINE> <INDENT> metrics.append(str(m)) <NEW_LINE> <DEDENT> logger.debug('{0}.__create_messages: {1}'.format(self.cn, metrics)) <NEW_LINE> return metrics
Create a list of zabbix messages, from a list of ZabbixMetrics. Attributes: metrics_array (list of ZabbixMetrics): List of ZabbixMetrics Returns: list of str: List of zabbix messages
625941c77b25080760e39492
def boundingRect(self): <NEW_LINE> <INDENT> radius = 0.0 <NEW_LINE> if len(self.wheelNumberCircleRadius) > 0: <NEW_LINE> <INDENT> radius = self.wheelNumberCircleRadius[-1] <NEW_LINE> <DEDENT> diameter = radius + radius <NEW_LINE> x = -1.0 * radius <NEW_LINE> y = -1.0 * radius <NEW_LINE> width = diameter <NEW_LINE> heig...
Returns the bounding rectangle for this graphicsitem.
625941c77c178a314d6ef496
def test_nocmd_raises(self): <NEW_LINE> <INDENT> self.assertRaises(ValueError, scheduler, commands=[])
No commands to execute -> raise ValueError.
625941c7009cb60464c633eb
def queueNextServerPush(self): <NEW_LINE> <INDENT> if self.wasLastPushSuccessful(): <NEW_LINE> <INDENT> if self.stopped: <NEW_LINE> <INDENT> delay = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> delay = self.bufferDelay <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if self.stopped: <NEW_LINE> <INDENT> return...
Queue the next push or call it immediately. Called to signal new items are available to be sent or on shutdown. A timer should be queued to trigger a network request or the callback should be called immediately. If a status push is already queued, ignore the current call.
625941c7796e427e537b05fd
def _generate_jwt_token(self): <NEW_LINE> <INDENT> dt = datetime.now() + timedelta(days=60) <NEW_LINE> payload = jwt_payload_handler(self) <NEW_LINE> token = jwt_encode_handler(payload) <NEW_LINE> return token.decode('utf-8')
Generates a JSON Web Token that stores this user's ID and has an expiry date set to 60 days into the future.
625941c716aa5153ce3624b1
def process_row(row_tag): <NEW_LINE> <INDENT> res = [] <NEW_LINE> for tag in row_tag.children: <NEW_LINE> <INDENT> if not tag.string or tag.string.isspace(): <NEW_LINE> <INDENT> res.append(None) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> res.append(tag.string) <NEW_LINE> <DEDENT> <DEDENT> return res
return row_tag as a list of HTML-tag-stripped strings row_tag: a <tr> bs4 Tag, where each column contains exactly one string
625941c7090684286d50ed1d
def __init__(self, name, arguments, results, statements, local_vars, global_vars): <NEW_LINE> <INDENT> input_symbols = set([]) <NEW_LINE> symbols = set([]) <NEW_LINE> for arg in arguments: <NEW_LINE> <INDENT> if isinstance(arg, OutputArgument): <NEW_LINE> <INDENT> symbols.update(arg.expr.free_symbols) <NEW_LINE> <DEDEN...
Initialize a Routine instance. Parameters ========== name : string Name of the routine. arguments : list of Arguments These are things that appear in arguments of a routine, often appearing on the right-hand side of a function call. These are commonly InputArguments but in some languages, they can a...
625941c721a7993f00bc7d26
def delete_keypair(self, name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> proxy._json_response(self.compute.delete( '/os-keypairs/{name}'.format(name=name))) <NEW_LINE> <DEDENT> except exc.OpenStackCloudURINotFound: <NEW_LINE> <INDENT> self.log.debug("Keypair %s not found for deleting", name) <NEW_LINE> return False...
Delete a keypair. :param name: Name of the keypair to delete. :returns: True if delete succeeded, False otherwise. :raises: OpenStackCloudException on operation error.
625941c7cdde0d52a9e5306b
def arma(ar=[], ma=[], tau2=1, V=None): <NEW_LINE> <INDENT> assert not(ar is [] and ma is []), "You must specify at least one of 'ar' or 'ma'!" <NEW_LINE> p = len(ar) <NEW_LINE> q = len(ma) <NEW_LINE> m = max(p, q+1) <NEW_LINE> phi = join(np.array(ar), np.zeros(m-p)) <NEW_LINE> rest = np.vstack( (np.eye(m-1), np.zeros(...
ARMA component for DLM - ar: list of ar coefficients - ma: list of ma coefficients - tau2: variance for evolution matrix - V: variance for observations Note that there is no discount option here because W is assumed to be a matrix of zeros but with W_{1,1} = sig2 see West & Prado (p.75)
625941c744b2445a339320cf
def _GetIntroDescriptionRow(self): <NEW_LINE> <INDENT> return { 'title': 'Description', 'content': [ { 'text': self._FormatDescription(self._namespace.description) } ] }
Generates the 'Description' row data for an API intro table.
625941c7596a897236089afa
def str2int(s): <NEW_LINE> <INDENT> s = bytearray(s) <NEW_LINE> r = 0 <NEW_LINE> for c in s: <NEW_LINE> <INDENT> r = (r << 8) | c <NEW_LINE> <DEDENT> return r
Convert a byte string to an integer. @param s: byte string representing a positive integer to convert @return: converted integer
625941c732920d7e50b28208
def mirror(self, pv, target, wait=False, expectation=True, srx=None): <NEW_LINE> <INDENT> cmd = "mirror %s %s" % (pv, target) <NEW_LINE> logger.debug(cmd) <NEW_LINE> ret = self.run_and_check(cmd, expectation) <NEW_LINE> if ret and srx: <NEW_LINE> <INDENT> ret = self.check_sr_masks(srx, pv) <NEW_LINE> <DEDENT> if not re...
Mirror a PV to a target LUN. If srx is not None, verify that the VSX set the masks for this PV on the SRX correctly.
625941c73eb6a72ae02ec513
def testIsFreshCreateFileInSubdirectory(self): <NEW_LINE> <INDENT> subdirectory = self._directory+'/subdirectory'; <NEW_LINE> os.mkdir(subdirectory); <NEW_LINE> resource = DirectoryResource(self._directory); <NEW_LINE> self.assertTrue(resource.isFresh(time() + 10), '->isFresh() returns True if an unmodified subdirector...
@covers Symfony\Component\Config\Resource\DirectoryResource.isFresh
625941c7ad47b63b2c509fb8
@contextmanager <NEW_LINE> def get_session(): <NEW_LINE> <INDENT> session = False <NEW_LINE> try: <NEW_LINE> <INDENT> session = driver.session() <NEW_LINE> yield session <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> if session: <NEW_LINE> <INDENT> session.close()
Allows the API to get sessions from the driver
625941c74e696a04525c9484
def delete(self, customer): <NEW_LINE> <INDENT> customer_obj = self.conekta.Customer.find(customer.id) <NEW_LINE> customer_obj.delete() <NEW_LINE> return True
Delete Customer
625941c73539df3088e2e383
def refer_or_store_block(self, block_id, block_data): <NEW_LINE> <INDENT> r = self.get_block_by_id(block_id) <NEW_LINE> if r is not None: <NEW_LINE> <INDENT> self.refer_block(block_id) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.store_block(block_id, block_data)
Convenience method for handling the common case of 'we have these bytes, no clue if the block is already inserted (by someone else) -> either refer to existing one, or add new block to the storage layer.
625941c74527f215b584c491
def do_python(self, line): <NEW_LINE> <INDENT> locals = self.getExpressionLocals() <NEW_LINE> if len(line) != 0: <NEW_LINE> <INDENT> cobj = compile(line, 'cli_input', 'exec') <NEW_LINE> exec(cobj, locals) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> code.interact(local=locals)
Start an interactive python interpreter. The namespace of the interpreter is updated with expression niceties. You may also specify a line of python code as an argument to be exec'd without beginning an interactive python interpreter on the controlling terminal. Usage: python [pycode]
625941c7956e5f7376d70ea7
def has_hook(self, func_obj): <NEW_LINE> <INDENT> last_frame = self.last() <NEW_LINE> if '$hooks' not in last_frame: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return func_obj in last_frame['$hooks'].values()
Returns True if the function object has been defined by a 'sub' or 'func' statement in the current scope. Returns False if the function object was created by other means. (e.g. a function that was passed in as an argument, or generated by another function such as 'compose(f, g)' is considered 'created by ot...
625941c78e7ae83300e4b005
def base64url_symmetric_decipher(self, data, key, vector): <NEW_LINE> <INDENT> binvector = binascii.unhexlify(vector) <NEW_LINE> key += key[0:8] <NEW_LINE> pas = re.sub(b'_', b'/', data) <NEW_LINE> pas = re.sub(b'-', b'+', pas) <NEW_LINE> pas = re.sub(b'\.', b'=', pas) <NEW_LINE> crypttext = base64.b64decode(pas) <NEW_...
:param data: :param key: :param vector: :return:
625941c7435de62698dfdc85
def getChar(self, key, defaultValue=0): <NEW_LINE> <INDENT> pass
Returns the value associated with the given key, or defaultValue if no mapping of the desired type exists for the given key. :param key: String: a String :param defaultValue: char: Value to return if key does not exist :return: char. a char value
625941c79c8ee82313fbb7ad
def check_cleanliness(net, df): <NEW_LINE> <INDENT> cleaned = streets_filter(net, df, equal_geom=True, scrub_check=True) <NEW_LINE> if not cleaned: <NEW_LINE> <INDENT> return cleaned <NEW_LINE> <DEDENT> cleaned = streets_filter(net, df, contained_geom=True, scrub_check=True) <NEW_LINE> return cleaned
scan segments to determine cleanse_supercycle needs to be run again Parameters ---------- net : spaghetti.SpaghettiNetwork df : geopandas.GeoDataFrame dataframe of geometries Returns ------- cleaned : bool False (repeat another cycle) or True (all clean --> break out of loop)
625941c72eb69b55b151c8e6
def loss(self, outputs, labels): <NEW_LINE> <INDENT> self.output_loss = self.criterion(outputs, labels) <NEW_LINE> if self.deform_fitting_mode == 'point2point': <NEW_LINE> <INDENT> self.reg_loss = p2p_fitting_regularizer(self) <NEW_LINE> <DEDENT> elif self.deform_fitting_mode == 'point2plane': <NEW_LINE> <INDENT> raise...
Runs the loss on outputs of the model :param outputs: logits :param labels: labels :return: loss
625941c78c0ade5d55d3e9f3
def __GetLabel(self, filePointer, index): <NEW_LINE> <INDENT> if (index < 0): <NEW_LINE> <INDENT> raise IndexError("Label index cannot be negative") <NEW_LINE> <DEDENT> filePointer.seek(8 + index) <NEW_LINE> label = unpack("B", filePointer.read(1))[0] <NEW_LINE> labelVector = zeros(10) <NEW_LINE> labelVector[label] = 1...
Returns an integer containing the label size for the specified index
625941c75fcc89381b1e16f7
def set(self, stheta, sphi): <NEW_LINE> <INDENT> super().set(stheta, sphi)
Sets angles. Args: stheta (float): Polar angle in deg. sphi (float): Azimuthal angle in deg.
625941c7656771135c3eb8a6
def get_object(self): <NEW_LINE> <INDENT> budget = super().get_object() <NEW_LINE> if not budget.student_can_edit(self.student.user_id): <NEW_LINE> <INDENT> raise PermissionDenied <NEW_LINE> <DEDENT> return budget
Only allow students with permission to edit
625941c7187af65679ca5157
def setUp(self): <NEW_LINE> <INDENT> V = { '0': ('0', '-0'), 'NUMBER': ('0', '-0', '100.1', '-100.1'), 'PERCENTAGE': ('0%', '-0%', '100.1%', '-100.1%'), 'EM': '1.2em', 'EX': '1.2ex', 'PX': '1.2px', 'CM': '1.2cm', 'MM': '1.2mm', 'IN': '1.2in', 'PT': '1.2pt', 'PC': '1.2pc', 'ANGLES': ('1deg', '1rad', '1grad'), 'TIMES': (...
init test values
625941c7d8ef3951e3243576
def get_categories_name(): <NEW_LINE> <INDENT> connection = Connection.connect_to_database() <NEW_LINE> cursor = connection.cursor() <NEW_LINE> get_categories_req = f"SELECT name FROM openfoodfact.categories" <NEW_LINE> cursor.execute(get_categories_req) <NEW_LINE> categories = cursor.fetchall() <NEW_LINE> cursor.close...
Getting the categories from database :return: categories
625941c7e8904600ed9f1f64
def __init__(self, ai_settings, screen, stats): <NEW_LINE> <INDENT> self.screen = screen <NEW_LINE> self.screen_rect = screen.get_rect() <NEW_LINE> self.ai_settings = ai_settings <NEW_LINE> self.stats = stats <NEW_LINE> self.text_color = (60, 60, 60) <NEW_LINE> self.font = pygame.font.SysFont(None, 48) <NEW_LINE> self....
初始化显示得分涉及的的属性
625941c7bd1bec0571d90668
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, PodPerformanceReplicationByArrayResponse): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__
Returns true if both objects are equal
625941c72c8b7c6e89b357fb
def evaluationFunction(self, currentGameState, action): <NEW_LINE> <INDENT> successorGameState = currentGameState.generatePacmanSuccessor(action) <NEW_LINE> newPos = successorGameState.getPacmanPosition() <NEW_LINE> newFood = successorGameState.getFood() <NEW_LINE> newGhostStates = successorGameState.getGhostStates() <...
Design a better evaluation function here. The evaluation function takes in the current and proposed successor GameStates (pacman.py) and returns a number, where higher numbers are better. The code below extracts some useful information from the state, like the remaining food (newFood) and Pacman position after moving...
625941c7fbf16365ca6f61fb
def Dispose(self): <NEW_LINE> <INDENT> pass
Dispose(self: DataGridTableStyle,disposing: bool) Disposes of the resources (other than memory) used by the System.Windows.Forms.DataGridTableStyle. disposing: true to release both managed and unmanaged resources; false to release only unmanaged resources.
625941c766656f66f7cbc1e4
def test_ogolnego_skladania_sciezki(self): <NEW_LINE> <INDENT> obk = GenericPathAssembler() <NEW_LINE> self.assertEqual(hasattr(obk, 'ustaw_poczatek_sciezki'), True)
TestOgolnegoSkladaniaSciezki:
625941c73c8af77a43ae37d8
def gif_duration(f): <NEW_LINE> <INDENT> delay = 0 <NEW_LINE> if f.read(6) not in ('GIF87a', 'GIF89a'): <NEW_LINE> <INDENT> raise GIFError('not a valid GIF file') <NEW_LINE> <DEDENT> f.seek(4, 1) <NEW_LINE> def skip_color_table(flags): <NEW_LINE> <INDENT> if flags & 0x80: f.seek(3 << ((flags & 7) + 1), 1) <NEW_LINE> <D...
Given a file object |f|, parse the GIF file it contains and return the duration of the animation in milliseconds. Raises GIFError on malformed data.
625941c77cff6e4e811179bf
def p_member_value_array_initializer(self, p): <NEW_LINE> <INDENT> p[0] = ArrayInitializer(p[2], lineno=p.lexer.lineno)
member_value_array_initializer : '{' member_values ',' '}' | '{' member_values '}'
625941c7d10714528d5ffd1b
def append(self, item): <NEW_LINE> <INDENT> self.items.append(item)
Expects field type and value
625941c7de87d2750b85fdcb
def repeat_test_to_catch_flakiness(times): <NEW_LINE> <INDENT> def fcn_helper(fcn): <NEW_LINE> <INDENT> return functools.wraps(fcn)( lambda *args, **kwargs: [fcn(*args, **kwargs) for _ in xrange(times)] ) <NEW_LINE> <DEDENT> return fcn_helper
Decorator that repeats a test to help catch flakiness. :param times: Number of times to repeat :type times: int
625941c7e64d504609d74879
def get_ip_address_from_request(request): <NEW_LINE> <INDENT> PRIVATE_IPS_PREFIX = ('10.', '172.', '192.', '127.') <NEW_LINE> ip_address = '' <NEW_LINE> x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR', '') <NEW_LINE> if x_forwarded_for and ',' not in x_forwarded_for: <NEW_LINE> <INDENT> if not x_forwarded_for...
Makes the best attempt to get the client's real IP or return the loopback
625941c7004d5f362079a36d
def evaluator(self, network): <NEW_LINE> <INDENT> fitness = 0 <NEW_LINE> for i in range(self.samplings): <NEW_LINE> <INDENT> inputs = np.random.rand(network.psi[0]) <NEW_LINE> target = inputs * self.factor <NEW_LINE> predictions = network.forward(inputs) <NEW_LINE> cost = network.costFunction(predictions, target) <NEW_...
Evaluate the given network on its ability to perform a multiplication by self.factor. The network should have the same amout of inputs as outputs. The network will evolve to approximate the multiplication of each inputs by self.factor. Parameters ---------- network : NeuralNetwork The neural network to be evaluate...
625941c7cb5e8a47e48b7ae5
def test_browserlayer(self): <NEW_LINE> <INDENT> from collective.documentcompare.interfaces import ICollectiveDocumentcompareLayer <NEW_LINE> from plone.browserlayer import utils <NEW_LINE> self.assertIn(ICollectiveDocumentcompareLayer, utils.registered_layers())
Test that ICollectiveDocumentcompareLayer is registered.
625941c73c8af77a43ae37d9
def dump(obj, fp, **kwargs): <NEW_LINE> <INDENT> fp.write(dumps(obj, **kwargs))
Serialize obj to fp (a .write() supporting file-like object). kwargs: arguments to pass to CBOREncoder
625941c791af0d3eaac9ba51
def _total_order_key(source): <NEW_LINE> <INDENT> if source._type == _FINITE: <NEW_LINE> <INDENT> return 0, source._exponent, source._significand <NEW_LINE> <DEDENT> elif source._type == _INFINITE: <NEW_LINE> <INDENT> return 1, <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert source._type == _NAN <NEW_LINE> return ...
Key function used to compare with total ordering. Assumes that the sign has already been dealt with.
625941c7cc0a2c11143dceca
def restore_model(self): <NEW_LINE> <INDENT> print('Loading the trained models... ') <NEW_LINE> G_path = './exps/'+trial+'/models/190000-G.ckpt' <NEW_LINE> g_checkpoint = self._load(G_path) <NEW_LINE> self.G.load_state_dict(g_checkpoint['model']) <NEW_LINE> self.g_optimizer.load_state_dict(g_checkpoint['optimizer']) <N...
Restore the model
625941c79b70327d1c4e0e0e
def test_basic(self): <NEW_LINE> <INDENT> equations = [ ['1', 'two', 'three'], ['four', 'two', '='] ] <NEW_LINE> expected = [ ' 1 two three', 'four two =' ] <NEW_LINE> actual = align_equations(equations) <NEW_LINE> self.assertListEqual(expected, actual)
Basic AlignEquations
625941c77b180e01f3dc4839
def quit_tlp_config(_, window) -> None: <NEW_LINE> <INDENT> settings.userconfig.write_user_config() <NEW_LINE> changedproperties = get_changed_properties() <NEW_LINE> if len(changedproperties) == 0: <NEW_LINE> <INDENT> Gtk.main_quit() <NEW_LINE> return <NEW_LINE> <DEDENT> tmpfilename = create_tmp_tlp_config_file(change...
Quit TLPUI and prompt for unsaved changes.
625941c763b5f9789fde711f
def interface_hundredgigabitethernet_ip_acl_interface_ip_access_group_ip_access_list(**kwargs): <NEW_LINE> <INDENT> config = ET.Element("config") <NEW_LINE> interface = ET.SubElement(config, "interface", xmlns="urn:brocade.com:mgmt:brocade-interface") <NEW_LINE> if kwargs.pop('delete_interface', False) is True: <NEW_LI...
Auto Generated Code
625941c7460517430c3941c1
def test_erase__bit_boundaries(self): <NEW_LINE> <INDENT> for height in range(2, 4): <NEW_LINE> <INDENT> for width in range(2, 66): <NEW_LINE> <INDENT> mask_size = (width, height) <NEW_LINE> mask_count = width * height <NEW_LINE> mask1 = pygame.mask.Mask(mask_size) <NEW_LINE> mask2 = pygame.mask.Mask(mask_size, fill=Tr...
Ensures erase handles masks of different sizes correctly. Tests masks of different sizes, including: -masks 31 to 33 bits wide (32 bit boundaries) -masks 63 to 65 bits wide (64 bit boundaries)
625941c7be8e80087fb20c7e
def discovery_request(self, headers, host_port): <NEW_LINE> <INDENT> (host, port) = host_port <NEW_LINE> logger.info('Discovery request from (%s,%d) for %s' % (host, port, headers['st'])) <NEW_LINE> for i in self.known.values(): <NEW_LINE> <INDENT> if i['MANIFESTATION'] == 'remote': <NEW_LINE> <INDENT> continue <NEW_LI...
Process a discovery request. The response must be sent to the address specified by (host, port).
625941c7cc40096d6159598a
@add_method(SimulationWell) <NEW_LINE> def cells(self, timestep): <NEW_LINE> <INDENT> sim_well_request = SimulationWell_pb2.SimulationWellRequest( case_id=self.case().id, well_name=self.name, timestep=timestep ) <NEW_LINE> return self._simulation_well_stub.GetSimulationWellCells(sim_well_request).data
Get reservoir cells the simulation well is defined for **SimulationWellCellInfo class description**:: Parameter | Description | Type ----------- | --------------------------------------------------------- | ----- ijk | Cell IJK location ...
625941c7097d151d1a222e94
def get_followers(self, first_user_id=None): <NEW_LINE> <INDENT> params = {} <NEW_LINE> if first_user_id: <NEW_LINE> <INDENT> params['next_openid'] = first_user_id <NEW_LINE> <DEDENT> return self._get( 'user/get', params=params )
获取关注者列表 详情请参考 http://mp.weixin.qq.com/wiki/3/17e6919a39c1c53555185907acf70093.html :param first_user_id: 可选。第一个拉取的 OPENID,不填默认从头开始拉取 :return: 返回的 JSON 数据包
625941c726068e7796caed17
def _resources_via_proc(pid): <NEW_LINE> <INDENT> utime, stime, start_time = proc.stats( pid, proc.Stat.CPU_UTIME, proc.Stat.CPU_STIME, proc.Stat.START_TIME, ) <NEW_LINE> total_cpu_time = float(utime) + float(stime) <NEW_LINE> memory_in_bytes = proc.memory_usage(pid)[0] <NEW_LINE> total_memory = proc.physical_memory() ...
Fetches resource usage information about a given process via proc. This returns a tuple of the form... (total_cpu_time, uptime, memory_in_bytes, memory_in_percent) :param int pid: process to be queried :returns: **tuple** with the resource usage information :raises: **IOError** if unsuccessful
625941c782261d6c526ab4d7
def _make_defaults(self, force=False): <NEW_LINE> <INDENT> if force or not self._cfg.has_option(self.SEC_COMMON, self.OPT_DATEFORMAT): <NEW_LINE> <INDENT> self.dateformat = str("%%d/%%m/%%Y") <NEW_LINE> <DEDENT> if force or not self._cfg.has_option(self.SEC_COMMON, self.OPT_DEBUG): <NEW_LINE> <INDENT> self.debug = str(...
Creates default values if does not exist or if ``force`` is true. :param force: If true, restores the default values.
625941c745492302aab5e2fc
def set_vm_storage_profile(vm, profile): <NEW_LINE> <INDENT> spec = vim.vm.ConfigSpec() <NEW_LINE> profile_specs = [] <NEW_LINE> profile_spec = vim.vm.DefinedProfileSpec() <NEW_LINE> profile_spec.profileId = profile.profileId.uniqueId <NEW_LINE> profile_specs.append(profile_spec) <NEW_LINE> spec.vmProfile = profile_spe...
Set vmware storage policy profile to VM Home :param vm: A virtual machine object :type vm: VirtualMachine :param profile: A VMware Storage Policy profile :type profile: pbm.profile.Profile :returns: None
625941c74e696a04525c9485
def get_option(self, key): <NEW_LINE> <INDENT> return self.options.get(key)
Get task option. Args: key (str): option name. Returns: str: option value.
625941c7167d2b6e31218bd0
def verify_publish_title(self, expected_title): <NEW_LINE> <INDENT> def wait_for_title_change(): <NEW_LINE> <INDENT> return (self.publish_title == expected_title, self.publish_title) <NEW_LINE> <DEDENT> Promise(wait_for_title_change, "Publish title incorrect. Found '" + self.publish_title + "'").fulfill()
Waits for the publish title to change to the expected value.
625941c7566aa707497f45a4
def usage(): <NEW_LINE> <INDENT> name = os.path.basename(__file__) <NEW_LINE> print('%s %s' % (name, __version__)) <NEW_LINE> print('Usage: %s <file> [-o file]' % name) <NEW_LINE> print('Command Line Arguments:') <NEW_LINE> print('<file> : The configuration file to use.') <NEW_LINE> print('-o <file> ...
Displays command-line information.
625941c73d592f4c4ed1d0aa
def _store_sparse_tensors_join(tensor_list_list, enqueue_many, keep_input): <NEW_LINE> <INDENT> (s0, sparse_info_list) = _store_sparse_tensors( tensor_list_list[0], enqueue_many, keep_input) <NEW_LINE> stored_list_list = [s0] <NEW_LINE> for tensor_list in tensor_list_list[1:]: <NEW_LINE> <INDENT> s, sparse_info_candida...
Store SparseTensors for feeding into batch_join, etc.
625941c70383005118ecf61d
def testDoubleConnect(self): <NEW_LINE> <INDENT> self.tc.connect() <NEW_LINE> self.assertTrue(self.tc.isconnected) <NEW_LINE> self.tc.connect() <NEW_LINE> self.assertTrue(self.tc.isconnected)
connect() if already connected should not change anything.
625941c71f037a2d8b946238
def to_stream(self, stream: _BufferedStream) -> None: <NEW_LINE> <INDENT> output = self.get_output() <NEW_LINE> header = _DataFrameHeader(fin=True, opcode=OPCODES_BY_MESSAGE[type(self)], length=len(output)) <NEW_LINE> frame = _DataFrame(header, output) <NEW_LINE> frame.to_stream(stream)
Write this message to the output stream.
625941c721bff66bcd68498e
def check_click_confirm_in_prompt(self): <NEW_LINE> <INDENT> self.click(self.release_confirm_loc) <NEW_LINE> return self.is_element_exist(self.row_titles_loc)
检查在提示页面点击【确定】,返回到文章列表页
625941c716aa5153ce3624b2
def sendForView(self, display_str, expect_return=False): <NEW_LINE> <INDENT> if self.view is not None: <NEW_LINE> <INDENT> return self.view.display(display_str, expect_return) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if expect_return: <NEW_LINE> <INDENT> return eval(input(display_str)) <NEW_LINE> <DEDENT> else: <N...
determines if view exists, if so send a display_str and whether or not to return input
625941c77b180e01f3dc483a
def dedupe_project_set(self, project_id_set, limit): <NEW_LINE> <INDENT> rtn = [] <NEW_LINE> it = project_id_set.iterator() <NEW_LINE> while len(rtn)<limit: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> row = next(it) <NEW_LINE> if not row['project_id'] in rtn: <NEW_LINE> <INDENT> rtn.append(row['project_id']) <NEW_LINE...
dedupes project entries based on project_id :param project_id_set: set of results as returned from django ORM .values() :param limit: maximmum results to return :return:
625941c729b78933be1e56e7
def play(strategy0, strategy1, goal=GOAL_SCORE): <NEW_LINE> <INDENT> who = 0 <NEW_LINE> score, opponent_score = 0, 0 <NEW_LINE> players = [score, opponent_score] <NEW_LINE> strategies = [strategy0, strategy1] <NEW_LINE> currentIndex = 0 <NEW_LINE> while players[0] < goal and players[1] < goal: <NEW_LINE> <INDENT> curre...
Simulate a game and return the final scores of both players, with Player 0's score first, and Player 1's score second. A strategy is a function that takes two total scores as arguments (the current player's score, and the opponent's score), and returns a number of dice that the current player will roll this turn. str...
625941c7baa26c4b54cb115a
def render(self, request): <NEW_LINE> <INDENT> self.setCSPHeader(request) <NEW_LINE> request.args = stringifyRequestArgs(request.args) <NEW_LINE> try: <NEW_LINE> <INDENT> response = self.getBridgeRequestAnswer(request) <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> logging.exception(err) <NEW_LINE> re...
Render a response for a client HTTP request. Presently, this method merely wraps :meth:`getBridgeRequestAnswer` to catch any unhandled exceptions which occur (otherwise the server will display the traceback to the client). If an unhandled exception *does* occur, the client will be served the default "No bridges curren...
625941c7d7e4931a7ee9df57
def __init__(self, input_size, hidden_size, use_bias=True): <NEW_LINE> <INDENT> super(WordLSTMCell, self).__init__() <NEW_LINE> self.input_size = input_size <NEW_LINE> self.hidden_size = hidden_size <NEW_LINE> self.use_bias = use_bias <NEW_LINE> self.weight_ih = nn.Parameter( torch.FloatTensor(input_size, 4 * hidden_si...
Most parts are copied from torch.nn.LSTMCell.
625941c70a50d4780f666ecb
def next(self): <NEW_LINE> <INDENT> if self.currentArrow: <NEW_LINE> <INDENT> self.currentArrow.stop() <NEW_LINE> self.scene().removeItem(self.currentArrow) <NEW_LINE> <DEDENT> self.index += 1 <NEW_LINE> if self.index == len(self.arrows): <NEW_LINE> <INDENT> self.currentArrow = None <NEW_LINE> return <NEW_LINE> <DEDENT...
Go to the next step.
625941c7b545ff76a8913e50
def groupAnagrams(self, strs): <NEW_LINE> <INDENT> group = {} <NEW_LINE> for s in strs: <NEW_LINE> <INDENT> curanagram = "".join(sorted(s)) <NEW_LINE> group.setdefault(curanagram, []) <NEW_LINE> group[curanagram].append(s) <NEW_LINE> <DEDENT> res = [] <NEW_LINE> for lst in group.values(): <NEW_LINE> <INDENT> res.append...
:type strs: List[str] :rtype: List[List[str]]
625941c707d97122c41788c3
def user_cert_upload(request, user_id): <NEW_LINE> <INDENT> user = get_object_or_404(User, pk=user_id) <NEW_LINE> must_have_permission(request.user, user, "can_change_user_cert") <NEW_LINE> if request.method == "POST": <NEW_LINE> <INDENT> form = UploadCertForm(data=request.POST, files=request.FILES) <NEW_LINE> if form....
Upload a key and certificate
625941c76fb2d068a760f0d6
def test_datatypes(self): <NEW_LINE> <INDENT> self.clear_database() <NEW_LINE> prov_document = examples.datatypes() <NEW_LINE> stored_document_id = self.provapi.save_document_from_prov(prov_document) <NEW_LINE> stored_document = self.provapi.get_document_as_prov(stored_document_id) <NEW_LINE> self.assertEqual(stored_do...
This test try to save and restore a common prov example document. :return:
625941c755399d3f055886ed
def constructMaximumBinaryTree(self, nums): <NEW_LINE> <INDENT> def find(x,y): <NEW_LINE> <INDENT> m = -1 <NEW_LINE> p = -1 <NEW_LINE> for i in range(x,y + 1): <NEW_LINE> <INDENT> if(nums[i] > m): <NEW_LINE> <INDENT> m = nums[i] <NEW_LINE> p = i <NEW_LINE> <DEDENT> <DEDENT> return m,p <NEW_LINE> <DEDENT> def create(sta...
:type nums: List[int] :rtype: TreeNode
625941c76aa9bd52df036ddd
def get_initial_values(self, add_and_svd_K = None): <NEW_LINE> <INDENT> if self.weight_2d is None: <NEW_LINE> <INDENT> self.get_weight_2d() <NEW_LINE> <DEDENT> if self.P is None: <NEW_LINE> <INDENT> self.svd() <NEW_LINE> <DEDENT> height,width,input_channel,output_channel = self.weight_4d.shape <NEW_LINE> C = input_chan...
return the initial weight of the decomposed layers
625941c732920d7e50b28209
def create_existing_painting(self, painting, painting_id): <NEW_LINE> <INDENT> painting_item = self.wd.QtoItemPage(self.painting_ids.get(painting_id)) <NEW_LINE> data = painting_item.get() <NEW_LINE> labels = make_labels(painting) <NEW_LINE> new_labels = find_new_values(data, labels, 'labels') <NEW_LINE> if new_labels:...
Add base info to an existing paining. Adds the same info as would have been added had it been created with create_new_painting() @param painting: information object for the painting @type painting: dict @param painting_id: the common (older) id of the painting in the Nationalmuseum collection @type painting_id: s...
625941c7f8510a7c17cf9736
def _get_history_series(df, window_size): <NEW_LINE> <INDENT> features = _get_history_features() <NEW_LINE> for index, row in df.iterrows(): <NEW_LINE> <INDENT> if index[0] < window_size: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> for day in range(window_size): <NEW_LINE> <INDENT> for feature in features: <NEW_LI...
构建时间序列历史信息特征(非统计类)
625941c7627d3e7fe0d68e89
def setUp(self): <NEW_LINE> <INDENT> IMP.test.TestCase.setUp(self) <NEW_LINE> self.mdl = IMP.kernel.Model() <NEW_LINE> self.mh = IMP.atom.read_pdb(self.get_input_file_name("1z5s_A.pdb"), self.mdl, IMP.atom.CAlphaPDBSelector()) <NEW_LINE> IMP.atom.add_radii(self.mh) <NEW_LINE> self.particles = IMP.core.get_leaves(self.m...
initialize IMP environment create particles
625941c7379a373c97cfab7e
def make_equations(x1, x2, w1, w2): <NEW_LINE> <INDENT> domain = {(a, b) for a in {'y1', 'y2', 'y3'} for b in {'x1', 'x2', 'x3'}} <NEW_LINE> u = Vec(domain, {('y3','x1'):w1*x1,('y3','x2'):w1*x2,('y3','x3'):w1,('y1','x1'):-x1,('y1','x2'):-x2,('y1','x3'):-1}) <NEW_LINE> v = Vec(domain, {('y3','x1'):w2*x1,('y3','x2'):w2*x...
Input: - x1 & x2: photo coordinates of a point on the board - y1 & y2: whiteboard coordinates of a point on the board Output: - List [u,v] where u*h = 0 and v*h = 0
625941c7a05bb46b383ec85d
def scale_window(self): <NEW_LINE> <INDENT> available_geometry = QApplication.desktop().availableGeometry() <NEW_LINE> scaled_height = available_geometry.height() * 0.35 <NEW_LINE> scaled_width = available_geometry.width() * 0.5 <NEW_LINE> scaled_geometry = QRect( (available_geometry.width() - scaled_width) / 2, (avail...
Resize and move the window to handle different dpi screens
625941c7adb09d7d5db6c7ca
def init(): <NEW_LINE> <INDENT> cs_dir = path.expanduser(CONFIG_DIR) <NEW_LINE> config_file = path.expanduser(DEFAULT_CONFIG_FILE) <NEW_LINE> try: <NEW_LINE> <INDENT> if not path.isdir(cs_dir): <NEW_LINE> <INDENT> os.mkdir(cs_dir) <NEW_LINE> copyfile(pkg_resources.resource_filename(__name__, "default_config.yml"), conf...
initalize the chunksub directory on the first run.
625941c7b545ff76a8913e51
@login_required <NEW_LINE> def activities(request, student_pk=None): <NEW_LINE> <INDENT> user_type = get_user_type(request) <NEW_LINE> if user_type == 'stu': <NEW_LINE> <INDENT> return stu_activities(request) <NEW_LINE> <DEDENT> elif user_type == 'coor' or user_type == 'advise': <NEW_LINE> <INDENT> return activities_vi...
Grabs all the activities associated with the student
625941c7956e5f7376d70ea8
def total_payables_this_year(self, group=None): <NEW_LINE> <INDENT> payables = Payable.objects.filter(date__year=self.year) <NEW_LINE> if group: <NEW_LINE> <INDENT> payables = payables.filter(project__group=group) <NEW_LINE> <DEDENT> return payables.aggregate(models.Sum("amount"))["amount__sum"] or 0
Return sum of payables ('kosten derden') with a date of this year
625941c755399d3f055886ee
def getPrintStatesVoc(self): <NEW_LINE> <INDENT> return DisplayList([ ('0', _('Never printed')), ('1', _('Printed after last publish')), ('2', _('Printed but republished afterwards')), ])
Returns a DisplayList object with print states.
625941c757b8e32f524834d4