code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def fixpointmethod(self, cfg_node): """The most important part of PyT, where we perform the variant of reaching definitions to find where sources reach. """ JOIN = self.join(cfg_node) # Assignment check if isinstance(cfg_node, AssignmentNode): arrow_result = J...
The most important part of PyT, where we perform the variant of reaching definitions to find where sources reach.
def animate(self, animation, static, score, best, appear): """Handle animation.""" # Create a surface of static parts in the animation. surface = pygame.Surface((self.game_width, self.game_height), 0) surface.fill(self.BACKGROUND) # Draw all static tiles. for y in range...
Handle animation.
def compute(self, inputVector, learn, activeArray, applyLateralInhibition=True): """ This is the primary public method of the LateralPooler class. This function takes a input vector and outputs the indices of the active columns. If 'learn' is set to True, this method also updates the permanences of the ...
This is the primary public method of the LateralPooler class. This function takes a input vector and outputs the indices of the active columns. If 'learn' is set to True, this method also updates the permanences of the columns and their lateral inhibitory connection weights.
def get_page(self, index=None): """Return page widget""" if index is None: widget = self.pages_widget.currentWidget() else: widget = self.pages_widget.widget(index) return widget.widget()
Return page widget
def _adaptSynapses(self, inputVector, activeColumns, synPermActiveInc, synPermInactiveDec): """ The primary method in charge of learning. Adapts the permanence values of the synapses based on the input vector, and the chosen columns after inhibition round. Permanence values are increased for synapses co...
The primary method in charge of learning. Adapts the permanence values of the synapses based on the input vector, and the chosen columns after inhibition round. Permanence values are increased for synapses connected to input bits that are turned on, and decreased for synapses connected to inputs bits th...
def to_array(tensor): # type: (TensorProto) -> np.ndarray[Any] """Converts a tensor def object to a numpy array. Inputs: tensor: a TensorProto object. Returns: arr: the converted array. """ if tensor.HasField("segment"): raise ValueError( "Currently not supporti...
Converts a tensor def object to a numpy array. Inputs: tensor: a TensorProto object. Returns: arr: the converted array.
def calculate_incorrect_name_dict(graph: BELGraph) -> Mapping[str, str]: """Group all of the incorrect identifiers in a dict of {namespace: list of erroneous names}. :return: A dictionary of {namespace: list of erroneous names} """ missing = defaultdict(list) for _, e, ctx in graph.warnings: ...
Group all of the incorrect identifiers in a dict of {namespace: list of erroneous names}. :return: A dictionary of {namespace: list of erroneous names}
def delta(feat, N): """Compute delta features from a feature vector sequence. :param feat: A numpy array of size (NUMFRAMES by number of features) containing features. Each row holds 1 feature vector. :param N: For each frame, calculate delta features based on preceding and following N frames :returns:...
Compute delta features from a feature vector sequence. :param feat: A numpy array of size (NUMFRAMES by number of features) containing features. Each row holds 1 feature vector. :param N: For each frame, calculate delta features based on preceding and following N frames :returns: A numpy array of size (NUM...
def log_level_from_string(str_level): """ Returns the proper log level core based on a given string :param str_level: Log level string :return: The log level code """ levels = { 'CRITICAL': logging.CRITICAL, 'ERROR': logging.ERROR, 'WARNING': logging.WARNING, 'INFO':...
Returns the proper log level core based on a given string :param str_level: Log level string :return: The log level code
def extend_schema(schema, documentAST=None): """Produces a new schema given an existing schema and a document which may contain GraphQL type extensions and definitions. The original schema will remain unaltered. Because a schema represents a graph of references, a schema cannot be extended without ...
Produces a new schema given an existing schema and a document which may contain GraphQL type extensions and definitions. The original schema will remain unaltered. Because a schema represents a graph of references, a schema cannot be extended without effectively making an entire copy. We do not know un...
def _get_normalized_args(parser): """Return the parsed command line arguments. Support the case when executed from a shebang, where all the parameters come in sys.argv[1] in a single string separated by spaces (in this case, the third parameter is what is being executed) """ env = os.enviro...
Return the parsed command line arguments. Support the case when executed from a shebang, where all the parameters come in sys.argv[1] in a single string separated by spaces (in this case, the third parameter is what is being executed)
def reload_config(self, async=True, verbose=False): ''' Initiate a config reload. This may take a while on large installations. ''' # If we're using an API version older than 4.5.0, don't use async api_version = float(self.api_version()['api_version']) if api_version < 4....
Initiate a config reload. This may take a while on large installations.
def get_user_contact_lists_contacts(self, id, contact_list_id, **data): """ GET /users/:id/contact_lists/:contact_list_id/contacts/ Returns the :format:`contacts <contact>` on the contact list as ``contacts``. """ return self.get("/users/{0}/contact_lists/{0}/con...
GET /users/:id/contact_lists/:contact_list_id/contacts/ Returns the :format:`contacts <contact>` on the contact list as ``contacts``.
def empty(cls: Type[BoardT], *, chess960: bool = False) -> BoardT: """Creates a new empty board. Also see :func:`~chess.Board.clear()`.""" return cls(None, chess960=chess960)
Creates a new empty board. Also see :func:`~chess.Board.clear()`.
def coordinate(self, panes=[], index=0): """ Update pane coordinate tuples based on their height and width relative to other panes within the dimensions of the current window. We account for panes with a height of 1 where the bottom coordinates are the same as the top. Account f...
Update pane coordinate tuples based on their height and width relative to other panes within the dimensions of the current window. We account for panes with a height of 1 where the bottom coordinates are the same as the top. Account for floating panes and self-coordinating panes adjacent to pan...
def _is_dynamic(v: Var) -> bool: """Return True if the Var holds a value which should be compiled to a dynamic Var access.""" return ( Maybe(v.meta) .map(lambda m: m.get(SYM_DYNAMIC_META_KEY, None)) # type: ignore .or_else_get(False) )
Return True if the Var holds a value which should be compiled to a dynamic Var access.
def as_create_table(self, table_name, overwrite=False): """Reformats the query into the create table as query. Works only for the single select SQL statements, in all other cases the sql query is not modified. :param superset_query: string, sql query that will be executed :param...
Reformats the query into the create table as query. Works only for the single select SQL statements, in all other cases the sql query is not modified. :param superset_query: string, sql query that will be executed :param table_name: string, will contain the results of the qu...
def _format_vector(self, vecs, form='broadcast'): """ Format a 3d vector field in certain ways, see `coords` for a description of each formatting method. """ if form == 'meshed': return np.meshgrid(*vecs, indexing='ij') elif form == 'vector': vecs ...
Format a 3d vector field in certain ways, see `coords` for a description of each formatting method.
def focus_window(winhandle, path=None, name=None, sleeptime=.01): """ sudo apt-get install xautomation apt-get install autokey-gtk wmctrl -xa gnome-terminal.Gnome-terminal wmctrl -xl """ import utool as ut import time print('focus: ' + winhandle) ...
sudo apt-get install xautomation apt-get install autokey-gtk wmctrl -xa gnome-terminal.Gnome-terminal wmctrl -xl
def _next_state(index, event_time, transition_set, population_view): """Moves a population between different states using information from a `TransitionSet`. Parameters ---------- index : iterable of ints An iterable of integer labels for the simulants. event_time : pandas.Timestamp ...
Moves a population between different states using information from a `TransitionSet`. Parameters ---------- index : iterable of ints An iterable of integer labels for the simulants. event_time : pandas.Timestamp When this transition is occurring. transition_set : TransitionSet ...
def message(self, value): """ Setter for **self.__message** attribute. :param value: Attribute value. :type value: unicode """ if value is not None: assert type(value) in (unicode, QString), \ "'{0}' attribute: '{1}' type is not 'unicode' or ...
Setter for **self.__message** attribute. :param value: Attribute value. :type value: unicode
def guess_message_type(message): """ Guess the message type based on the class of message :param message: Message to guess the type for :type message: APPMessage :return: The corresponding message type (MsgType) or None if not found :rtype: None | int """ if isinstance(message, APPConf...
Guess the message type based on the class of message :param message: Message to guess the type for :type message: APPMessage :return: The corresponding message type (MsgType) or None if not found :rtype: None | int
def pp_prep(self, mlt_df): """ prepare pilot point based parameterizations Parameters ---------- mlt_df : pandas.DataFrame a dataframe with multiplier array information Note ---- calls pyemu.pp_utils.setup_pilot_points_grid() """ if...
prepare pilot point based parameterizations Parameters ---------- mlt_df : pandas.DataFrame a dataframe with multiplier array information Note ---- calls pyemu.pp_utils.setup_pilot_points_grid()
def filter_minreads_samples_from_table(table, minreads=1, inplace=True): """Filter samples from biom table that have less than minreads reads total Paraneters ---------- table : biom.Table the biom table to filter minreads : int (optional) the minimal number of reads in a sample...
Filter samples from biom table that have less than minreads reads total Paraneters ---------- table : biom.Table the biom table to filter minreads : int (optional) the minimal number of reads in a sample in order to keep it inplace : bool (optional) if True, filter the b...
def get(self, sid): """ Constructs a ReservationContext :param sid: The sid :returns: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationContext :rtype: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationContext """ return Reservati...
Constructs a ReservationContext :param sid: The sid :returns: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationContext :rtype: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationContext
def solveAndNotify(proto, exercise): """The user at the given AMP protocol has solved the given exercise. This will log the solution and notify the user. """ exercise.solvedBy(proto.user) proto.callRemote(ce.NotifySolved, identifier=exercise.identifier, tit...
The user at the given AMP protocol has solved the given exercise. This will log the solution and notify the user.
def make_type(typename, lineno, implicit=False): """ Converts a typename identifier (e.g. 'float') to its internal symbol table entry representation. Creates a type usage symbol stored in a AST E.g. DIM a As Integer will access Integer type """ assert isinstance(typename, str) if not SY...
Converts a typename identifier (e.g. 'float') to its internal symbol table entry representation. Creates a type usage symbol stored in a AST E.g. DIM a As Integer will access Integer type
def to_import(self): # type: () -> ImportEndpoint """ Converts an EndpointDescription bean to an ImportEndpoint :return: An ImportEndpoint bean """ # Properties properties = self.get_properties() # Framework UUID fw_uid = self.get_framework_uuid(...
Converts an EndpointDescription bean to an ImportEndpoint :return: An ImportEndpoint bean
def revnet_cifar_base(): """Tiny hparams suitable for CIFAR/etc.""" hparams = revnet_base() hparams.num_channels_init_block = 32 hparams.first_batch_norm = [False, True, True] hparams.init_stride = 1 hparams.init_kernel_size = 3 hparams.init_maxpool = False hparams.strides = [1, 2, 2] hparams.batch_si...
Tiny hparams suitable for CIFAR/etc.
def api_representation(self, content_type): """ Returns the JSON representation of this message required for making requests to the API. Args: content_type (str): Either 'HTML' or 'Text' """ payload = dict(Subject=self.subject, Body=dict(ContentType=content_type, Content=sel...
Returns the JSON representation of this message required for making requests to the API. Args: content_type (str): Either 'HTML' or 'Text'
def get_albums_for_artist(self, artist, full_album_art_uri=False): """Get an artist's albums. Args: artist (str): an artist's name. full_album_art_uri: whether the album art URI should be absolute (i.e. including the IP address). Default `False`. Returns...
Get an artist's albums. Args: artist (str): an artist's name. full_album_art_uri: whether the album art URI should be absolute (i.e. including the IP address). Default `False`. Returns: A `SearchResult` instance.
def disable_hostgroup_svc_checks(self, hostgroup): """Disable service checks for a hostgroup Format of the line that triggers function call:: DISABLE_HOSTGROUP_SVC_CHECKS;<hostgroup_name> :param hostgroup: hostgroup to disable :type hostgroup: alignak.objects.hostgroup.Hostgrou...
Disable service checks for a hostgroup Format of the line that triggers function call:: DISABLE_HOSTGROUP_SVC_CHECKS;<hostgroup_name> :param hostgroup: hostgroup to disable :type hostgroup: alignak.objects.hostgroup.Hostgroup :return: None
def discover_engines(self, executor=None): """Discover configured engines. :param executor: Optional executor module override """ if executor is None: executor = getattr(settings, 'FLOW_EXECUTOR', {}).get('NAME', 'resolwe.flow.executors.local') self.executor = self.l...
Discover configured engines. :param executor: Optional executor module override
def _sign(private_key, data, hash_algorithm, rsa_pss_padding=False): """ Generates an RSA, DSA or ECDSA signature :param private_key: The PrivateKey to generate the signature with :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode ...
Generates an RSA, DSA or ECDSA signature :param private_key: The PrivateKey to generate the signature with :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode string of "md5", "sha1", "sha224", "sha256", "sha384" or "sha512" :param rsa...
def get_data_home(data_home=None): """ Return the path of the revrand data dir. This folder is used by some large dataset loaders to avoid downloading the data several times. By default the data dir is set to a folder named 'revrand_data' in the user home folder. Alternatively, it can be ...
Return the path of the revrand data dir. This folder is used by some large dataset loaders to avoid downloading the data several times. By default the data dir is set to a folder named 'revrand_data' in the user home folder. Alternatively, it can be set by the 'REVRAND_DATA' environment varia...
def insert_many(objects, using="default"): """Insert list of Django objects in one SQL query. Objects must be of the same Django model. Note that save is not called and signals on the model are not raised. Mostly from: http://people.iola.dk/olau/python/bulkops.py """ if not objects: ret...
Insert list of Django objects in one SQL query. Objects must be of the same Django model. Note that save is not called and signals on the model are not raised. Mostly from: http://people.iola.dk/olau/python/bulkops.py
def exists(self, filename): """Report whether a file exists on the distribution point. Determines file type by extension. Args: filename: Filename you wish to check. (No path! e.g.: "AdobeFlashPlayer-14.0.0.176.pkg") """ if is_package(filename): ...
Report whether a file exists on the distribution point. Determines file type by extension. Args: filename: Filename you wish to check. (No path! e.g.: "AdobeFlashPlayer-14.0.0.176.pkg")
def create(self, validated_data): """ Create the video and its nested resources. """ courses = validated_data.pop("courses", []) encoded_videos = validated_data.pop("encoded_videos", []) video = Video.objects.create(**validated_data) EncodedVideo.objects.bulk_cr...
Create the video and its nested resources.
def array(self): """ return the underlying numpy array """ return np.geomspace(self.start, self.stop, self.num, self.endpoint)
return the underlying numpy array
def cal_k_vinet_from_v(v, v0, k0, k0p): """ calculate bulk modulus in GPa :param v: unit-cell volume in A^3 :param v0: unit-cell volume in A^3 at 1 bar :param k0: bulk modulus at reference conditions :param k0p: pressure derivative of bulk modulus at reference conditions :return: bulk modul...
calculate bulk modulus in GPa :param v: unit-cell volume in A^3 :param v0: unit-cell volume in A^3 at 1 bar :param k0: bulk modulus at reference conditions :param k0p: pressure derivative of bulk modulus at reference conditions :return: bulk modulus at high pressure in GPa
def _CreatePlacemark(self, parent, name, style_id=None, visible=True, description=None): """Create a KML Placemark element. Args: parent: The parent ElementTree.Element instance. name: The placemark name as a string. style_id: If not None, the id of a style to use for t...
Create a KML Placemark element. Args: parent: The parent ElementTree.Element instance. name: The placemark name as a string. style_id: If not None, the id of a style to use for the placemark. visible: Whether the placemark is initially visible or not. description: A description string...
def optimize(lattice, positions, numbers, displacements, forces, alm_options=None, p2s_map=None, p2p_map=None, log_level=0): """Calculate force constants lattice : array_like Basis vectors. a, b, c a...
Calculate force constants lattice : array_like Basis vectors. a, b, c are given as column vectors. shape=(3, 3), dtype='double' positions : array_like Fractional coordinates of atomic points. shape=(num_atoms, 3), dtype='double' numbers : array_like Atomic numbers. ...
def get_or_create_hosted_zone(client, zone_name): """Get the Id of an existing zone, or create it. Args: client (:class:`botocore.client.Route53`): The connection used to interact with Route53's API. zone_name (string): The name of the DNS hosted zone to create. Returns: ...
Get the Id of an existing zone, or create it. Args: client (:class:`botocore.client.Route53`): The connection used to interact with Route53's API. zone_name (string): The name of the DNS hosted zone to create. Returns: string: The Id of the Hosted Zone.
def modify_server(self, UUID, **kwargs): """ modify_server allows updating the server's updateable_fields. Note: Server's IP-addresses and Storages are managed by their own add/remove methods. """ body = dict() body['server'] = {} for arg in kwargs: i...
modify_server allows updating the server's updateable_fields. Note: Server's IP-addresses and Storages are managed by their own add/remove methods.
def _get_generator(parser, extract, keep, check_maf): """Generates the data (with extract markers and keep, if required.""" if extract is not None: parser = Extractor(parser, names=extract) for data in parser.iter_genotypes(): data.genotypes = data.genotypes[keep] # Checking the MA...
Generates the data (with extract markers and keep, if required.
def _process_reservations(self, reservations): """ Given a dict with the structure of a response from boto3.ec2.describe_instances(...), find the public/private ips. :param reservations: :return: """ reservations = reservations['Reservations'] private_ip...
Given a dict with the structure of a response from boto3.ec2.describe_instances(...), find the public/private ips. :param reservations: :return:
def xread(self, streams, count=None, block=None): """ Block and monitor multiple streams for new data. streams: a dict of stream names to stream IDs, where IDs indicate the last ID already seen. count: if set, only return this many items, beginning with the ...
Block and monitor multiple streams for new data. streams: a dict of stream names to stream IDs, where IDs indicate the last ID already seen. count: if set, only return this many items, beginning with the earliest available. block: number of milliseconds to wait,...
def get_nn_shell_info(self, structure, site_idx, shell): """Get a certain nearest neighbor shell for a certain site. Determines all non-backtracking paths through the neighbor network computed by `get_nn_info`. The weight is determined by multiplying the weight of the neighbor at each h...
Get a certain nearest neighbor shell for a certain site. Determines all non-backtracking paths through the neighbor network computed by `get_nn_info`. The weight is determined by multiplying the weight of the neighbor at each hop through the network. For example, a 2nd-nearest-neighbor ...
def update(self, time): """ Update acceleration. Accounts for the importance and priority (order) of multiple behaviors. """ # .... I feel this stuff could be done a lot better. total_acceleration = Vector.null() max_jerk = self.max_acceleration for behavior in ...
Update acceleration. Accounts for the importance and priority (order) of multiple behaviors.
def subscribe(self, handler, topic=None, options=None): """Subscribe to a topic for receiving events. Replace :meth:`autobahn.wamp.interface.IApplicationSession.subscribe` """ def proxy_handler(*args, **kwargs): return self._callbacks_runner.put(partial(handler, *args, **kwa...
Subscribe to a topic for receiving events. Replace :meth:`autobahn.wamp.interface.IApplicationSession.subscribe`
def join_room(self, room_name): """ Connects to a given room If it does not exist it is created""" logging.debug('Joining room {ro}'.format(ro=room_name)) for room in self.rooms: if room.name == room_name: room.add_user(self) ...
Connects to a given room If it does not exist it is created
def get_template_dirs(): """Return a set of all template directories.""" temp_glob = rel_to_cwd('templates', '**', 'templates', 'config.yaml') temp_groups = glob(temp_glob) temp_groups = [get_parent_dir(path, 2) for path in temp_groups] return set(temp_groups)
Return a set of all template directories.
def pass_outflow_v1(self): """Update the outlet link sequence |dam_outlets.Q|.""" flu = self.sequences.fluxes.fastaccess out = self.sequences.outlets.fastaccess out.q[0] += flu.outflow
Update the outlet link sequence |dam_outlets.Q|.
def replace_namespaced_horizontal_pod_autoscaler_status(self, name, namespace, body, **kwargs): """ replace status of the specified HorizontalPodAutoscaler This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>...
replace status of the specified HorizontalPodAutoscaler This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_horizontal_pod_autoscaler_status(name, namespace, body, async_req=True) >>...
def get_project(self, project_id, include_capabilities=None, include_history=None): """GetProject. Get project with the specified id or name, optionally including capabilities. :param str project_id: :param bool include_capabilities: Include capabilities (such as source control) in the t...
GetProject. Get project with the specified id or name, optionally including capabilities. :param str project_id: :param bool include_capabilities: Include capabilities (such as source control) in the team project result (default: false). :param bool include_history: Search within renamed...
def strip_cdata(text): """Removes all CDATA blocks from `text` if it contains them. Note: If the function contains escaped XML characters outside of a CDATA block, they will be unescaped. Args: A string containing one or more CDATA blocks. Returns: An XML unescaped str...
Removes all CDATA blocks from `text` if it contains them. Note: If the function contains escaped XML characters outside of a CDATA block, they will be unescaped. Args: A string containing one or more CDATA blocks. Returns: An XML unescaped string with CDATA block qualifier...
def _writeData(self, command, device, params=()): """ Write the data to the device. :Parameters: command : `int` The command to write to the device. device : `int` The device is the integer number of the hardware devices ID and is only use...
Write the data to the device. :Parameters: command : `int` The command to write to the device. device : `int` The device is the integer number of the hardware devices ID and is only used with the Pololu Protocol. params : `tuple` Seq...
def list(self, end_date=values.unset, friendly_name=values.unset, minutes=values.unset, start_date=values.unset, task_channel=values.unset, split_by_wait_time=values.unset, limit=None, page_size=None): """ Lists TaskQueuesStatisticsInstance records from the API as ...
Lists TaskQueuesStatisticsInstance records from the API as a list. Unlike stream(), this operation is eager and will load `limit` records into memory before returning. :param datetime end_date: Filter cumulative statistics by an end date. :param unicode friendly_name: Filter the TaskQue...
def dispatch(self, tree): """Dispatcher function, dispatching tree type T to method _T.""" # display omp directive in python dump for omp in metadata.get(tree, openmp.OMPDirective): deps = list() for dep in omp.deps: old_file = self.f self....
Dispatcher function, dispatching tree type T to method _T.
def add_trits(left, right): # type: (Sequence[int], Sequence[int]) -> List[int] """ Adds two sequences of trits together. The result is a list of trits equal in length to the longer of the two sequences. .. note:: Overflow is possible. For example, ``add_trits([1], [1])`` retu...
Adds two sequences of trits together. The result is a list of trits equal in length to the longer of the two sequences. .. note:: Overflow is possible. For example, ``add_trits([1], [1])`` returns ``[-1]``.
def npartitions(self): """ Get number of partitions (Spark only). """ if self.mode == 'spark': return self.tordd().getNumPartitions() else: notsupported(self.mode)
Get number of partitions (Spark only).
def select_best_url(self): """Select `best` url. Since urls are pre-sorted w.r.t. their ping times, we simply return the first element from the list. And we always return the same url unless we observe greater than max allowed number of consecutive failures. In this case, we would return the next `best...
Select `best` url. Since urls are pre-sorted w.r.t. their ping times, we simply return the first element from the list. And we always return the same url unless we observe greater than max allowed number of consecutive failures. In this case, we would return the next `best` url, and append the previous...
def send_like(self, *, user_id, times=1): """ 发送好友赞 ------------ :param int user_id: 对方 QQ 号 :param int times: 赞的次数,每个好友每天最多 10 次 :return: None :rtype: None """ return super().__getattr__('send_like') \ (user_id=user_id, times=times)
发送好友赞 ------------ :param int user_id: 对方 QQ 号 :param int times: 赞的次数,每个好友每天最多 10 次 :return: None :rtype: None
def config(self): """The envs for this app.""" return self._h._get_resource( resource=('apps', self.name, 'config_vars'), obj=ConfigVars, app=self )
The envs for this app.
def centralManager_didConnectPeripheral_(self, manager, peripheral): """Called when a device is connected.""" logger.debug('centralManager_didConnectPeripheral called') # Setup peripheral delegate and kick off service discovery. For now just # assume all services need to be discovered. ...
Called when a device is connected.
def portfolio_prices( symbols=("AAPL", "GLD", "GOOG", "$SPX", "XOM", "msft"), start=datetime.datetime(2005, 1, 1), end=datetime.datetime(2011, 12, 31), # data stops at 2013/1/1 normalize=True, allocation=None, price_type='actual_close', ): """Calculate the Sharpe Ratio and other perfor...
Calculate the Sharpe Ratio and other performance metrics for a portfolio Arguments: symbols (list of str): Ticker symbols like "GOOG", "AAPL", etc start (datetime): The date at the start of the period being analyzed. end (datetime): The date at the end of the period being analyzed. normaliz...
def run_as(user, domain, password, filename, logon_flag=1, work_dir="", show_flag=Properties.SW_SHOWNORMAL): """ Runs an external program. :param user: username The user name to use. :param domain: The domain name to use. :param password: The password to use. :param logon_flag: 0 = do...
Runs an external program. :param user: username The user name to use. :param domain: The domain name to use. :param password: The password to use. :param logon_flag: 0 = do not load the user profile, 1 = (default) load the user profile, 2 = use for net credentials only :param filename: The n...
def root(self, scope, names): """Find root of identifier, from scope args: scope (Scope): current scope names (list): identifier name list (, separated identifiers) returns: list """ parent = scope.scopename if parent: paren...
Find root of identifier, from scope args: scope (Scope): current scope names (list): identifier name list (, separated identifiers) returns: list
def update_scheme(current, target): """ Take the scheme from the current URL and applies it to the target URL if the target URL startswith // or is missing a scheme :param current: current URL :param target: target URL :return: target URL with the current URLs scheme """ target_p = urlpa...
Take the scheme from the current URL and applies it to the target URL if the target URL startswith // or is missing a scheme :param current: current URL :param target: target URL :return: target URL with the current URLs scheme
def _encrypt(cipher, key, data, iv, padding): """ Encrypts plaintext :param cipher: A unicode string of "aes128", "aes192", "aes256", "des", "tripledes_2key", "tripledes_3key", "rc2", "rc4" :param key: The encryption key - a byte string 5-32 bytes long :param data: ...
Encrypts plaintext :param cipher: A unicode string of "aes128", "aes192", "aes256", "des", "tripledes_2key", "tripledes_3key", "rc2", "rc4" :param key: The encryption key - a byte string 5-32 bytes long :param data: The plaintext - a byte string :param iv: The...
def rst_table(self, array): """Given an array, the function formats and returns and table in rST format.""" # Determine cell width for each column cell_dict = {} for i, row in enumerate(array): for j, val in enumerate(row): if j not in cell_dict: ...
Given an array, the function formats and returns and table in rST format.
def ssn(self): """ Returns a 9 digits Dutch SSN called "burgerservicenummer (BSN)". the Dutch "burgerservicenummer (BSN)" needs to pass the "11-proef", which is a check digit approach; this function essentially reverses the checksum steps to create a random valid BSN (which is 9...
Returns a 9 digits Dutch SSN called "burgerservicenummer (BSN)". the Dutch "burgerservicenummer (BSN)" needs to pass the "11-proef", which is a check digit approach; this function essentially reverses the checksum steps to create a random valid BSN (which is 9 digits).
def index(self, weighted=True, prune=False): """Return cube index measurement. This function is deprecated. Use index_table from CubeSlice. """ warnings.warn( "CrunchCube.index() is deprecated. Use CubeSlice.index_table().", DeprecationWarning, ) ...
Return cube index measurement. This function is deprecated. Use index_table from CubeSlice.
def set_outgoing(self, value): """ Setter for 'outgoing' field. :param value - a new value of 'outgoing' field. Must be a list of IDs (String type) of outgoing flows. """ if not isinstance(value, list): raise TypeError("OutgoingList new value must be a list") ...
Setter for 'outgoing' field. :param value - a new value of 'outgoing' field. Must be a list of IDs (String type) of outgoing flows.
def get(self, *args, **kwargs): """ Quick and dirty hack to fix change_view and delete_view; they use self.queryset(request).get(...) to get the object they should work with. Our modifications to the queryset when INCLUDE_ANCESTORS is enabled make get() fail often with a Multiple...
Quick and dirty hack to fix change_view and delete_view; they use self.queryset(request).get(...) to get the object they should work with. Our modifications to the queryset when INCLUDE_ANCESTORS is enabled make get() fail often with a MultipleObjectsReturned exception.
def batch(self, client=None): """Return a batch to use as a context manager. :type client: :class:`~google.cloud.logging.client.Client` or ``NoneType`` :param client: the client to use. If not passed, falls back to the ``client`` stored on the curre...
Return a batch to use as a context manager. :type client: :class:`~google.cloud.logging.client.Client` or ``NoneType`` :param client: the client to use. If not passed, falls back to the ``client`` stored on the current topic. :rtype: :class:`Batch`...
def get_user_bookmarks(self, id, **data): """ GET /users/:id/bookmarks/ Gets all the user's saved events. In order to update the saved events list, the user must unsave or save each event. A user is authorized to only see his/her saved events. """ return ...
GET /users/:id/bookmarks/ Gets all the user's saved events. In order to update the saved events list, the user must unsave or save each event. A user is authorized to only see his/her saved events.
def split_key(key): """Splits a node key.""" if key == KEY_SEP: return () key_chunks = tuple(key.strip(KEY_SEP).split(KEY_SEP)) if key_chunks[0].startswith(KEY_SEP): return (key_chunks[0][len(KEY_SEP):],) + key_chunks[1:] else: return key_chunks
Splits a node key.
def load_airpassengers(as_series=False): """Monthly airline passengers. The classic Box & Jenkins airline data. Monthly totals of international airline passengers, 1949 to 1960. Parameters ---------- as_series : bool, optional (default=False) Whether to return a Pandas series. If False...
Monthly airline passengers. The classic Box & Jenkins airline data. Monthly totals of international airline passengers, 1949 to 1960. Parameters ---------- as_series : bool, optional (default=False) Whether to return a Pandas series. If False, will return a 1d numpy array. Ret...
def _add_cadd_score(self, variant_obj, info_dict): """Add the cadd score to the variant Args: variant_obj (puzzle.models.Variant) info_dict (dict): A info dictionary """ cadd_score = info_dict.get('CADD') if cadd_score: log...
Add the cadd score to the variant Args: variant_obj (puzzle.models.Variant) info_dict (dict): A info dictionary
def parse_device(lines): """Parse all the lines of a device block. A device block is composed of a header line with the name of the device and at least one extra line describing the device and its status. The extra lines have a varying format depending on the status and personality of the device (...
Parse all the lines of a device block. A device block is composed of a header line with the name of the device and at least one extra line describing the device and its status. The extra lines have a varying format depending on the status and personality of the device (e.g. RAID1 vs RAID5, healthy vs ...
def shell(self, name='default', user=None, password=None, root=0, verbose=1, write_password=1, no_db=0, no_pw=0): """ Opens a SQL shell to the given database, assuming the configured database and user supports this feature. """ raise NotImplementedError
Opens a SQL shell to the given database, assuming the configured database and user supports this feature.
def course_or_program_exist(self, course_id, program_uuid): """ Return whether the input course or program exist. """ course_exists = course_id and CourseApiClient().get_course_details(course_id) program_exists = program_uuid and CourseCatalogApiServiceClient().program_exists(pro...
Return whether the input course or program exist.
def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ...
Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can...
def AddLeNetModel(model, data): ''' This part is the standard LeNet model: from data to the softmax prediction. For each convolutional layer we specify dim_in - number of input channels and dim_out - number or output channels. Also each Conv and MaxPool layer changes the image size. For example, ke...
This part is the standard LeNet model: from data to the softmax prediction. For each convolutional layer we specify dim_in - number of input channels and dim_out - number or output channels. Also each Conv and MaxPool layer changes the image size. For example, kernel of size 5 reduces each side of an image...
def mount(cls, device, mount_directory, fs=None, options=None, cmd_timeout=None, sudo=False): """ Mount a device to mount directory :param device: device to mount :param mount_directory: target directory where the given device will be mounted to :param fs: optional, filesystem on the specified device. If speci...
Mount a device to mount directory :param device: device to mount :param mount_directory: target directory where the given device will be mounted to :param fs: optional, filesystem on the specified device. If specifies - overrides OS filesystem \ detection with this value. :param options: specifies mount opti...
def _pool_one_shape(features_2d, area_width, area_height, batch_size, width, height, depth, fn=tf.reduce_max, name=None): """Pools for an area in features_2d. Args: features_2d: a Tensor in a shape of [batch_size, height, width, depth]. area_width: the max width allowed for an area. ...
Pools for an area in features_2d. Args: features_2d: a Tensor in a shape of [batch_size, height, width, depth]. area_width: the max width allowed for an area. area_height: the max height allowed for an area. batch_size: the batch size. width: the width of the memory. height: the height of the...
def _remove_prefix(name): """Strip the possible prefix 'Table: ' from one or more table names.""" if isinstance(name, str): return _do_remove_prefix(name) return [_do_remove_prefix(nm) for nm in name]
Strip the possible prefix 'Table: ' from one or more table names.
def subst_quoted_strings(sql, params): """Reverse operation to mark_quoted_strings - substitutes '@' by params. """ parts = sql.split('@') params_dont_match = "number of parameters doesn' match the transformed query" assert len(parts) == len(params) + 1, params_dont_match # would be internal error ...
Reverse operation to mark_quoted_strings - substitutes '@' by params.
def get_name(self, use_alias=True): """ Gets the name to reference the sorted field :return: the name to reference the sorted field :rtype: str """ if self.desc: direction = 'DESC' else: direction = 'ASC' if use_alias: ...
Gets the name to reference the sorted field :return: the name to reference the sorted field :rtype: str
def combine(self, other, func, fill_value=None, overwrite=True): """ Perform column-wise combine with another DataFrame. Combines a DataFrame with `other` DataFrame using `func` to element-wise combine columns. The row and column indexes of the resulting DataFrame will be the un...
Perform column-wise combine with another DataFrame. Combines a DataFrame with `other` DataFrame using `func` to element-wise combine columns. The row and column indexes of the resulting DataFrame will be the union of the two. Parameters ---------- other : DataFrame ...
def to_method(func): """ Lift :func:`func` to a method; it will be called with the first argument 'self' ignored. :param func: Any callable object """ @functools.wraps(func) def wrapper(*args, **kwargs): """Wrapper function. """ return func(*args[1:], **kwargs) ...
Lift :func:`func` to a method; it will be called with the first argument 'self' ignored. :param func: Any callable object
def verify_embedding(emb, source, target, ignore_errors=()): """A simple (exception-raising) diagnostic for minor embeddings. See :func:`diagnose_embedding` for a more detailed diagnostic / more information. Args: emb (dict): a dictionary mapping source nodes to arrays of target nodes sour...
A simple (exception-raising) diagnostic for minor embeddings. See :func:`diagnose_embedding` for a more detailed diagnostic / more information. Args: emb (dict): a dictionary mapping source nodes to arrays of target nodes source (graph or edgelist): the graph to be embedded target (gra...
def _range_from_slice(myslice, start=None, stop=None, step=None, length=None): """Convert a slice to an array of integers.""" assert isinstance(myslice, slice) # Find 'step'. step = myslice.step if myslice.step is not None else step if step is None: step = 1 # Find 'start'. start = m...
Convert a slice to an array of integers.
def get_certificates(self): """Get user's certificates.""" for certificate in self.user_data.certificates: certificate['datetime'] = certificate['datetime'].strip() return self.user_data.certificates
Get user's certificates.
def from_header(self, header): """Generate a SpanContext object using the trace context header. The value of enabled parsed from header is int. Need to convert to bool. :type header: str :param header: Trace context header which was extracted from the HTTP ...
Generate a SpanContext object using the trace context header. The value of enabled parsed from header is int. Need to convert to bool. :type header: str :param header: Trace context header which was extracted from the HTTP request headers. :rtype: :class:...
def _render_template_block_nodelist(nodelist, block_name, context): """Recursively iterate over a node to find the wanted block.""" # Attempt to find the wanted block in the current template. for node in nodelist: # If the wanted block was found, return it. if isinstance(node, BlockNode): ...
Recursively iterate over a node to find the wanted block.
def f_contains(self, item, with_links=True, shortcuts=False, max_depth=None): """Checks if the node contains a specific parameter or result. It is checked if the item can be found via the :func:`~pypet.naturalnaming.NNGroupNode.f_get` method. :param item: Parameter/Result name or insta...
Checks if the node contains a specific parameter or result. It is checked if the item can be found via the :func:`~pypet.naturalnaming.NNGroupNode.f_get` method. :param item: Parameter/Result name or instance. If a parameter or result instance is supplied it is also checked if ...
def _RunIpRoute(self, args=None, options=None): """Run a command with ip route and return the response. Args: args: list, the string ip route command args to execute. options: dict, the string parameters to append to the ip route command. Returns: string, the standard output from the ip ...
Run a command with ip route and return the response. Args: args: list, the string ip route command args to execute. options: dict, the string parameters to append to the ip route command. Returns: string, the standard output from the ip route command execution.
def finalize(self, **kwargs): """ Finalize executes any remaining image modifications making it ready to show. """ # Set the aspect ratio to make the visualization square # TODO: still unable to make plot square using make_axes_locatable # x0,x1 = self.ax.get_xlim() ...
Finalize executes any remaining image modifications making it ready to show.