code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def upload(sess_id_or_alias, files): """ Upload files to user's home folder. \b SESSID: Session ID or its alias given when creating the session. FILES: Path to upload. """ if len(files) < 1: return with Session() as session: try: print_wait('Uploading files.....
Upload files to user's home folder. \b SESSID: Session ID or its alias given when creating the session. FILES: Path to upload.
Below is the the instruction that describes the task: ### Input: Upload files to user's home folder. \b SESSID: Session ID or its alias given when creating the session. FILES: Path to upload. ### Response: def upload(sess_id_or_alias, files): """ Upload files to user's home folder. \b ...
def lon360to180(lon): """Convert longitude from (0, 360) to (-180, 180) """ if np.any(lon > 360.0) or np.any(lon < 0.0): print("Warning: lon outside expected range") lon = wraplon(lon) #lon[lon > 180.0] -= 360.0 #lon180 = (lon+180) - np.floor((lon+180)/360)*360 - 180 lon = lon - ...
Convert longitude from (0, 360) to (-180, 180)
Below is the the instruction that describes the task: ### Input: Convert longitude from (0, 360) to (-180, 180) ### Response: def lon360to180(lon): """Convert longitude from (0, 360) to (-180, 180) """ if np.any(lon > 360.0) or np.any(lon < 0.0): print("Warning: lon outside expected range") ...
def show_error(cls, error=True): """ Show `error` around the conspect elements. If the `error` is ``False``, hide it. """ if error: cls.input_el.style.border = "2px solid red" cls.conspect_el.style.border = "2px solid red" cls.subconspect_el.st...
Show `error` around the conspect elements. If the `error` is ``False``, hide it.
Below is the the instruction that describes the task: ### Input: Show `error` around the conspect elements. If the `error` is ``False``, hide it. ### Response: def show_error(cls, error=True): """ Show `error` around the conspect elements. If the `error` is ``False``, hide it. ...
def read_stdout(self): """ Reads the standard output of the QEMU process. Only use when the process has been stopped or has crashed. """ output = "" if self._stdout_file: try: with open(self._stdout_file, "rb") as file: out...
Reads the standard output of the QEMU process. Only use when the process has been stopped or has crashed.
Below is the the instruction that describes the task: ### Input: Reads the standard output of the QEMU process. Only use when the process has been stopped or has crashed. ### Response: def read_stdout(self): """ Reads the standard output of the QEMU process. Only use when the proces...
def issuer(self): """The certificate issuer field as :py:class:`~django_ca.subject.Subject`.""" return Subject([(s.oid, s.value) for s in self.x509.issuer])
The certificate issuer field as :py:class:`~django_ca.subject.Subject`.
Below is the the instruction that describes the task: ### Input: The certificate issuer field as :py:class:`~django_ca.subject.Subject`. ### Response: def issuer(self): """The certificate issuer field as :py:class:`~django_ca.subject.Subject`.""" return Subject([(s.oid, s.value) for s in self.x509....
def call(subcommand, args): """Call a subcommand passing the args.""" args['<napp>'] = parse_napps(args['<napp>']) func = getattr(NAppsAPI, subcommand) func(args)
Call a subcommand passing the args.
Below is the the instruction that describes the task: ### Input: Call a subcommand passing the args. ### Response: def call(subcommand, args): """Call a subcommand passing the args.""" args['<napp>'] = parse_napps(args['<napp>']) func = getattr(NAppsAPI, subcommand) func(args)
def interpret_pixel_data(data, dc, pixel_array, invert=True): '''Takes the pixel raw data and interprets them. This includes consistency checks and pixel/data matching. The data has to come from one double column only but can have more than one pixel bit (e.g. TDAC = 5 bit). Parameters ---------- ...
Takes the pixel raw data and interprets them. This includes consistency checks and pixel/data matching. The data has to come from one double column only but can have more than one pixel bit (e.g. TDAC = 5 bit). Parameters ---------- data : numpy.ndarray The raw data words. dc : int ...
Below is the the instruction that describes the task: ### Input: Takes the pixel raw data and interprets them. This includes consistency checks and pixel/data matching. The data has to come from one double column only but can have more than one pixel bit (e.g. TDAC = 5 bit). Parameters ---------- ...
def get_area(self, geojson): """Read the first feature from the geojson and return it as a Polygon object. """ geojson = json.load(open(geojson, 'r')) self.area = Polygon(geojson['features'][0]['geometry']['coordinates'][0])
Read the first feature from the geojson and return it as a Polygon object.
Below is the the instruction that describes the task: ### Input: Read the first feature from the geojson and return it as a Polygon object. ### Response: def get_area(self, geojson): """Read the first feature from the geojson and return it as a Polygon object. """ geojson = ...
def debug(self, msg, *args, **kwargs): """ Log 'msg % args' with severity 'DEBUG'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.debug("Houston, we have a %s", "thorny problem", exc_info=1) """ self._baseLogger.debug(self, self.getExtendedM...
Log 'msg % args' with severity 'DEBUG'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.debug("Houston, we have a %s", "thorny problem", exc_info=1)
Below is the the instruction that describes the task: ### Input: Log 'msg % args' with severity 'DEBUG'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.debug("Houston, we have a %s", "thorny problem", exc_info=1) ### Response: def debug(self, msg, *arg...
def _ilshift(self, n): """Shift bits by n to the left in place. Return self.""" assert 0 < n <= self.len self._append(Bits(n)) self._truncatestart(n) return self
Shift bits by n to the left in place. Return self.
Below is the the instruction that describes the task: ### Input: Shift bits by n to the left in place. Return self. ### Response: def _ilshift(self, n): """Shift bits by n to the left in place. Return self.""" assert 0 < n <= self.len self._append(Bits(n)) self._truncatestart(n) ...
def synctree(src, dst, onexist=None): """Recursively sync files at directory src to dst This is more or less equivalent to:: cp -n -R ${src}/ ${dst}/ If a file at the same path exists in src and dst, it is NOT overwritten in dst. Pass ``onexist`` in order to raise an error on such conditions. ...
Recursively sync files at directory src to dst This is more or less equivalent to:: cp -n -R ${src}/ ${dst}/ If a file at the same path exists in src and dst, it is NOT overwritten in dst. Pass ``onexist`` in order to raise an error on such conditions. Args: src (path-like): source di...
Below is the the instruction that describes the task: ### Input: Recursively sync files at directory src to dst This is more or less equivalent to:: cp -n -R ${src}/ ${dst}/ If a file at the same path exists in src and dst, it is NOT overwritten in dst. Pass ``onexist`` in order to raise an er...
def current_session(): """ Returns the :class:`Session` for the current driver and app, instantiating one if needed. Returns: Session: The :class:`Session` for the current driver and app. """ driver = current_driver or default_driver session_key = "{driver}:{session}:{app}".format( ...
Returns the :class:`Session` for the current driver and app, instantiating one if needed. Returns: Session: The :class:`Session` for the current driver and app.
Below is the the instruction that describes the task: ### Input: Returns the :class:`Session` for the current driver and app, instantiating one if needed. Returns: Session: The :class:`Session` for the current driver and app. ### Response: def current_session(): """ Returns the :class:`Session...
def merge_includes(code): """Merge all includes recursively.""" pattern = '\#\s*include\s*"(?P<filename>[a-zA-Z0-9\_\-\.\/]+)"' regex = re.compile(pattern) includes = [] def replace(match): filename = match.group("filename") if filename not in includes: includes.append...
Merge all includes recursively.
Below is the the instruction that describes the task: ### Input: Merge all includes recursively. ### Response: def merge_includes(code): """Merge all includes recursively.""" pattern = '\#\s*include\s*"(?P<filename>[a-zA-Z0-9\_\-\.\/]+)"' regex = re.compile(pattern) includes = [] def replace(...
async def add_unit(self, count=1, to=None): """Add one or more units to this application. :param int count: Number of units to add :param str to: Placement directive, e.g.:: '23' - machine 23 'lxc:7' - new lxc container on machine 7 '24/lxc/3' - lxc container...
Add one or more units to this application. :param int count: Number of units to add :param str to: Placement directive, e.g.:: '23' - machine 23 'lxc:7' - new lxc container on machine 7 '24/lxc/3' - lxc container 3 or machine 24 If None, a new machine is...
Below is the the instruction that describes the task: ### Input: Add one or more units to this application. :param int count: Number of units to add :param str to: Placement directive, e.g.:: '23' - machine 23 'lxc:7' - new lxc container on machine 7 '24/lxc/3' -...
def add_validation_message(self, message): """ Adds a message to the messages dict :param message: """ if message.file not in self.messages: self.messages[message.file] = [] self.messages[message.file].append(message)
Adds a message to the messages dict :param message:
Below is the the instruction that describes the task: ### Input: Adds a message to the messages dict :param message: ### Response: def add_validation_message(self, message): """ Adds a message to the messages dict :param message: """ if message.file not in self.messa...
def update(cls, domain, source, dest_add, dest_del): """Update a domain mail forward destinations.""" result = None if dest_add or dest_del: current_destinations = cls.get_destinations(domain, source) fwds = current_destinations[:] if dest_add: ...
Update a domain mail forward destinations.
Below is the the instruction that describes the task: ### Input: Update a domain mail forward destinations. ### Response: def update(cls, domain, source, dest_add, dest_del): """Update a domain mail forward destinations.""" result = None if dest_add or dest_del: current_destina...
def Print(self, x, data, message, **kwargs): # pylint: disable=invalid-name """call tf.Print. Args: x: a LaidOutTensor data: a list of LaidOutTensor message: a string **kwargs: keyword arguments to tf.print Returns: a LaidOutTensor """ tf.logging.info("PlacementMeshIm...
call tf.Print. Args: x: a LaidOutTensor data: a list of LaidOutTensor message: a string **kwargs: keyword arguments to tf.print Returns: a LaidOutTensor
Below is the the instruction that describes the task: ### Input: call tf.Print. Args: x: a LaidOutTensor data: a list of LaidOutTensor message: a string **kwargs: keyword arguments to tf.print Returns: a LaidOutTensor ### Response: def Print(self, x, data, message, **kwargs):...
def directory(): """Construct hitman_dir from os name""" home = os.path.expanduser('~') if platform.system() == 'Linux': hitman_dir = os.path.join(home, '.hitman') elif platform.system() == 'Darwin': hitman_dir = os.path.join(home, 'Library', 'Application Support', ...
Construct hitman_dir from os name
Below is the the instruction that describes the task: ### Input: Construct hitman_dir from os name ### Response: def directory(): """Construct hitman_dir from os name""" home = os.path.expanduser('~') if platform.system() == 'Linux': hitman_dir = os.path.join(home, '.hitman') elif platform....
def __EncodedAttribute_generic_encode_rgb24(self, rgb24, width=0, height=0, quality=0, format=_ImageFormat.RawImage): """Internal usage only""" if not is_seq(rgb24): raise TypeError("Expected sequence (str, numpy.ndarray, list, tuple " "or bytearray) as first argument") is_s...
Internal usage only
Below is the the instruction that describes the task: ### Input: Internal usage only ### Response: def __EncodedAttribute_generic_encode_rgb24(self, rgb24, width=0, height=0, quality=0, format=_ImageFormat.RawImage): """Internal usage only""" if not is_seq(rgb24): raise TypeError("Expected sequence...
def _lonlat_from_geos_angle(x, y, geos_area): """Get lons and lats from x, y in projection coordinates.""" h = (geos_area.proj_dict['h'] + geos_area.proj_dict['a']) / 1000 b__ = (geos_area.proj_dict['a'] / geos_area.proj_dict['b']) ** 2 sd = np.sqrt((h * np.cos(x) * np.cos(y)) ** 2 - (...
Get lons and lats from x, y in projection coordinates.
Below is the the instruction that describes the task: ### Input: Get lons and lats from x, y in projection coordinates. ### Response: def _lonlat_from_geos_angle(x, y, geos_area): """Get lons and lats from x, y in projection coordinates.""" h = (geos_area.proj_dict['h'] + geos_area.proj_dict['a']) / 1000 ...
def _dump_query_timestamps(self, current_time: float): """Output the number of GraphQL queries grouped by their query_hash within the last time.""" windows = [10, 11, 15, 20, 30, 60] print("GraphQL requests:", file=sys.stderr) for query_hash, times in self._graphql_query_timestamps.items...
Output the number of GraphQL queries grouped by their query_hash within the last time.
Below is the the instruction that describes the task: ### Input: Output the number of GraphQL queries grouped by their query_hash within the last time. ### Response: def _dump_query_timestamps(self, current_time: float): """Output the number of GraphQL queries grouped by their query_hash within the last ti...
def secp256k1(): """ create the secp256k1 curve """ GFp = FiniteField(2 ** 256 - 2 ** 32 - 977) # This is P from below... aka FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F ec = EllipticCurve(GFp, 0, 7) return ECDSA(ec, ec.point(0x79BE667EF9DCBBAC55A062...
create the secp256k1 curve
Below is the the instruction that describes the task: ### Input: create the secp256k1 curve ### Response: def secp256k1(): """ create the secp256k1 curve """ GFp = FiniteField(2 ** 256 - 2 ** 32 - 977) # This is P from below... aka FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF...
def estimate_tx_operational_gas(self, safe_address: str, data_bytes_length: int): """ Estimates the gas for the verification of the signatures and other safe related tasks before and after executing a transaction. Calculation will be the sum of: - Base cost of 15000 gas ...
Estimates the gas for the verification of the signatures and other safe related tasks before and after executing a transaction. Calculation will be the sum of: - Base cost of 15000 gas - 100 of gas per word of `data_bytes` - Validate the signatures 5000 * threshold (ecrecov...
Below is the the instruction that describes the task: ### Input: Estimates the gas for the verification of the signatures and other safe related tasks before and after executing a transaction. Calculation will be the sum of: - Base cost of 15000 gas - 100 of gas per word of `data...
def _handle_subscription(self, topics): """Handle subscription of topics.""" if not isinstance(topics, list): topics = [topics] for topic in topics: topic_levels = topic.split('/') try: qos = int(topic_levels[-2]) except ValueError:...
Handle subscription of topics.
Below is the the instruction that describes the task: ### Input: Handle subscription of topics. ### Response: def _handle_subscription(self, topics): """Handle subscription of topics.""" if not isinstance(topics, list): topics = [topics] for topic in topics: topic_le...
def pre_build(self, traj, brian_list, network_dict): """Pre-builds the connections. Pre-build is only performed if none of the relevant parameters is explored and the relevant neuron groups exist. :param traj: Trajectory container :param brian_list: List o...
Pre-builds the connections. Pre-build is only performed if none of the relevant parameters is explored and the relevant neuron groups exist. :param traj: Trajectory container :param brian_list: List of objects passed to BRIAN network constructor. Adds...
Below is the the instruction that describes the task: ### Input: Pre-builds the connections. Pre-build is only performed if none of the relevant parameters is explored and the relevant neuron groups exist. :param traj: Trajectory container :param brian_list: L...
def _init_map(self, record_types=None, **kwargs): """Initialize form map""" osid_objects.OsidObjectForm._init_map(self, record_types=record_types) self._my_map['assignedBinIds'] = [str(kwargs['bin_id'])] self._my_map['group'] = self._group_default self._my_map['avatarId'] = self....
Initialize form map
Below is the the instruction that describes the task: ### Input: Initialize form map ### Response: def _init_map(self, record_types=None, **kwargs): """Initialize form map""" osid_objects.OsidObjectForm._init_map(self, record_types=record_types) self._my_map['assignedBinIds'] = [str(kwargs[...
def add_tot_length(self, qname, sname, value, sym=True): """Add a total length value to self.alignment_lengths.""" self.alignment_lengths.loc[qname, sname] = value if sym: self.alignment_lengths.loc[sname, qname] = value
Add a total length value to self.alignment_lengths.
Below is the the instruction that describes the task: ### Input: Add a total length value to self.alignment_lengths. ### Response: def add_tot_length(self, qname, sname, value, sym=True): """Add a total length value to self.alignment_lengths.""" self.alignment_lengths.loc[qname, sname] = value ...
def http_query(self, method, path, data={}, params={}, timeout=300): """ Make a query to the docker daemon :param method: HTTP method :param path: Endpoint in API :param data: Dictionnary with the body. Will be transformed to a JSON :param params: Parameters added as a q...
Make a query to the docker daemon :param method: HTTP method :param path: Endpoint in API :param data: Dictionnary with the body. Will be transformed to a JSON :param params: Parameters added as a query arg :param timeout: Timeout :returns: HTTP response
Below is the the instruction that describes the task: ### Input: Make a query to the docker daemon :param method: HTTP method :param path: Endpoint in API :param data: Dictionnary with the body. Will be transformed to a JSON :param params: Parameters added as a query arg :pa...
def get_editorTab(self, editor): """ Returns the **Script_Editor_tabWidget** Widget tab associated with the given editor. :param editor: Editor to search tab for. :type editor: Editor :return: Tab index. :rtype: Editor """ for i in range(self.Script_Edit...
Returns the **Script_Editor_tabWidget** Widget tab associated with the given editor. :param editor: Editor to search tab for. :type editor: Editor :return: Tab index. :rtype: Editor
Below is the the instruction that describes the task: ### Input: Returns the **Script_Editor_tabWidget** Widget tab associated with the given editor. :param editor: Editor to search tab for. :type editor: Editor :return: Tab index. :rtype: Editor ### Response: def get_editorTab(sel...
def gaussian(x, mu, sigma): """ Gaussian function of the form :math:`\\frac{1}{\\sqrt{2 \\pi}\\sigma} e^{-\\frac{(x-\\mu)^2}{2\\sigma^2}}`. .. versionadded:: 1.5 Parameters ---------- x : float Function variable :math:`x`. mu : float Mean of the Gaussian function. sigma...
Gaussian function of the form :math:`\\frac{1}{\\sqrt{2 \\pi}\\sigma} e^{-\\frac{(x-\\mu)^2}{2\\sigma^2}}`. .. versionadded:: 1.5 Parameters ---------- x : float Function variable :math:`x`. mu : float Mean of the Gaussian function. sigma : float Standard deviation of t...
Below is the the instruction that describes the task: ### Input: Gaussian function of the form :math:`\\frac{1}{\\sqrt{2 \\pi}\\sigma} e^{-\\frac{(x-\\mu)^2}{2\\sigma^2}}`. .. versionadded:: 1.5 Parameters ---------- x : float Function variable :math:`x`. mu : float Mean of the...
def _replicate(n, tensor): """Replicate the input tensor n times along a new (major) dimension.""" # TODO(axch) Does this already exist somewhere? Should it get contributed? multiples = tf.concat([[n], tf.ones_like(tensor.shape)], axis=0) return tf.tile(tf.expand_dims(tensor, axis=0), multiples)
Replicate the input tensor n times along a new (major) dimension.
Below is the the instruction that describes the task: ### Input: Replicate the input tensor n times along a new (major) dimension. ### Response: def _replicate(n, tensor): """Replicate the input tensor n times along a new (major) dimension.""" # TODO(axch) Does this already exist somewhere? Should it get cont...
def determine_file_type(self, z): """Determine file type.""" content = z.read('[Content_Types].xml') with io.BytesIO(content) as b: encoding = self._analyze_file(b) if encoding is None: encoding = 'utf-8' b.seek(0) text = b.read()....
Determine file type.
Below is the the instruction that describes the task: ### Input: Determine file type. ### Response: def determine_file_type(self, z): """Determine file type.""" content = z.read('[Content_Types].xml') with io.BytesIO(content) as b: encoding = self._analyze_file(b) i...
def write_table(self, table): """Send DDL to create the specified `table` :Parameters: - `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that represents the table to read/write. Returns None """ table_sql, serial_key_sql = s...
Send DDL to create the specified `table` :Parameters: - `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that represents the table to read/write. Returns None
Below is the the instruction that describes the task: ### Input: Send DDL to create the specified `table` :Parameters: - `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that represents the table to read/write. Returns None ### Response: def wr...
def render_pull_base_image(self): """Configure pull_base_image""" phase = 'prebuild_plugins' plugin = 'pull_base_image' if self.user_params.parent_images_digests.value: self.pt.set_plugin_arg(phase, plugin, 'parent_images_digests', self.use...
Configure pull_base_image
Below is the the instruction that describes the task: ### Input: Configure pull_base_image ### Response: def render_pull_base_image(self): """Configure pull_base_image""" phase = 'prebuild_plugins' plugin = 'pull_base_image' if self.user_params.parent_images_digests.value: ...
def make_pinwheel(radial_std, tangential_std, num_classes, num_per_class, rate, rs=npr.RandomState(0)): """Based on code by Ryan P. Adams.""" rads = np.linspace(0, 2*np.pi, num_classes, endpoint=False) features = rs.randn(num_classes*num_per_class, 2) \ * np.array([radial_std, tan...
Based on code by Ryan P. Adams.
Below is the the instruction that describes the task: ### Input: Based on code by Ryan P. Adams. ### Response: def make_pinwheel(radial_std, tangential_std, num_classes, num_per_class, rate, rs=npr.RandomState(0)): """Based on code by Ryan P. Adams.""" rads = np.linspace(0, 2*np.pi, num_c...
def fuse_batchnorm_weights(gamma, beta, mean, var, epsilon): # https://github.com/Tencent/ncnn/blob/master/src/layer/batchnorm.cpp """ float sqrt_var = sqrt(var_data[i]); a_data[i] = bias_data[i] - slope_data[i] * mean_data[i] / sqrt_var; b_data[i] = slope_data[i] / sqrt_var; ... ...
float sqrt_var = sqrt(var_data[i]); a_data[i] = bias_data[i] - slope_data[i] * mean_data[i] / sqrt_var; b_data[i] = slope_data[i] / sqrt_var; ... ptr[i] = b * ptr[i] + a;
Below is the the instruction that describes the task: ### Input: float sqrt_var = sqrt(var_data[i]); a_data[i] = bias_data[i] - slope_data[i] * mean_data[i] / sqrt_var; b_data[i] = slope_data[i] / sqrt_var; ... ptr[i] = b * ptr[i] + a; ### Response: def fuse_batchnorm_weights(gamma,...
def iterate_forever(func, *args, **kwargs): """Iterate over a finite iterator forever When the iterator is exhausted will call the function again to generate a new iterator and keep iterating. """ output = func(*args, **kwargs) while True: try: playlist_item = next(output) ...
Iterate over a finite iterator forever When the iterator is exhausted will call the function again to generate a new iterator and keep iterating.
Below is the the instruction that describes the task: ### Input: Iterate over a finite iterator forever When the iterator is exhausted will call the function again to generate a new iterator and keep iterating. ### Response: def iterate_forever(func, *args, **kwargs): """Iterate over a finite iterator...
def emit(self, event, data=None, room=None, include_self=True, namespace=None, callback=None): """Emit a custom event to one or more connected clients.""" return self.socketio.emit(event, data, room=room, include_self=include_self, ...
Emit a custom event to one or more connected clients.
Below is the the instruction that describes the task: ### Input: Emit a custom event to one or more connected clients. ### Response: def emit(self, event, data=None, room=None, include_self=True, namespace=None, callback=None): """Emit a custom event to one or more connected clients.""" ...
def get_storage(self): '''Get the storage instance. :return Redis: Redis instance ''' if self.storage: return self.storage self.storage = self.reconnect_redis() return self.storage
Get the storage instance. :return Redis: Redis instance
Below is the the instruction that describes the task: ### Input: Get the storage instance. :return Redis: Redis instance ### Response: def get_storage(self): '''Get the storage instance. :return Redis: Redis instance ''' if self.storage: return self.storage ...
def __envelope(x, hop): '''Compute the max-envelope of x at a stride/frame length of h''' return util.frame(x, hop_length=hop, frame_length=hop).max(axis=0)
Compute the max-envelope of x at a stride/frame length of h
Below is the the instruction that describes the task: ### Input: Compute the max-envelope of x at a stride/frame length of h ### Response: def __envelope(x, hop): '''Compute the max-envelope of x at a stride/frame length of h''' return util.frame(x, hop_length=hop, frame_length=hop).max(axis=0)
def CSS_setMediaText(self, styleSheetId, range, text): """ Function path: CSS.setMediaText Domain: CSS Method name: setMediaText Parameters: Required arguments: 'styleSheetId' (type: StyleSheetId) -> No description 'range' (type: SourceRange) -> No description 'text' (type: string) ->...
Function path: CSS.setMediaText Domain: CSS Method name: setMediaText Parameters: Required arguments: 'styleSheetId' (type: StyleSheetId) -> No description 'range' (type: SourceRange) -> No description 'text' (type: string) -> No description Returns: 'media' (type: CSSMedia) -> The...
Below is the the instruction that describes the task: ### Input: Function path: CSS.setMediaText Domain: CSS Method name: setMediaText Parameters: Required arguments: 'styleSheetId' (type: StyleSheetId) -> No description 'range' (type: SourceRange) -> No description 'text' (type: stri...
def batch_iter(data, batch_size, num_epochs): """Generates a batch iterator for a dataset.""" data = np.array(data) data_size = len(data) num_batches_per_epoch = int(len(data)/batch_size) + 1 for epoch in range(num_epochs): # Shuffle the data at each epoch shuffle_indices = np.random...
Generates a batch iterator for a dataset.
Below is the the instruction that describes the task: ### Input: Generates a batch iterator for a dataset. ### Response: def batch_iter(data, batch_size, num_epochs): """Generates a batch iterator for a dataset.""" data = np.array(data) data_size = len(data) num_batches_per_epoch = int(len(data)/ba...
def shift(schedule: ScheduleComponent, time: int, name: str = None) -> Schedule: """Return schedule shifted by `time`. Args: schedule: The schedule to shift time: The time to shift by name: Name of shifted schedule. Defaults to name of `schedule` """ if name is None: nam...
Return schedule shifted by `time`. Args: schedule: The schedule to shift time: The time to shift by name: Name of shifted schedule. Defaults to name of `schedule`
Below is the the instruction that describes the task: ### Input: Return schedule shifted by `time`. Args: schedule: The schedule to shift time: The time to shift by name: Name of shifted schedule. Defaults to name of `schedule` ### Response: def shift(schedule: ScheduleComponent, time:...
def _get_dvportgroup_dict(pg_ref): ''' Returns a dictionary with a distributed virutal portgroup data pg_ref Portgroup reference ''' props = salt.utils.vmware.get_properties_of_managed_object( pg_ref, ['name', 'config.description', 'config.numPorts', 'config.type',...
Returns a dictionary with a distributed virutal portgroup data pg_ref Portgroup reference
Below is the the instruction that describes the task: ### Input: Returns a dictionary with a distributed virutal portgroup data pg_ref Portgroup reference ### Response: def _get_dvportgroup_dict(pg_ref): ''' Returns a dictionary with a distributed virutal portgroup data pg_ref P...
def open(self): """initialize visit variables""" self.stats = self.linter.add_stats() self._returns = [] self._branches = defaultdict(int) self._stmts = []
initialize visit variables
Below is the the instruction that describes the task: ### Input: initialize visit variables ### Response: def open(self): """initialize visit variables""" self.stats = self.linter.add_stats() self._returns = [] self._branches = defaultdict(int) self._stmts = []
def write(self, fn=None): """copy the zip file from its filename to the given filename.""" fn = fn or self.fn if not os.path.exists(os.path.dirname(fn)): os.makedirs(os.path.dirname(fn)) f = open(self.fn, 'rb') b = f.read() f.close() f = open(fn, 'wb')...
copy the zip file from its filename to the given filename.
Below is the the instruction that describes the task: ### Input: copy the zip file from its filename to the given filename. ### Response: def write(self, fn=None): """copy the zip file from its filename to the given filename.""" fn = fn or self.fn if not os.path.exists(os.path.dirname(fn)):...
def qzordered(A,B,crit=1.0): "Eigenvalues bigger than crit are sorted in the top-left." TOL = 1e-10 def select(alpha, beta): return alpha**2>crit*beta**2 [S,T,alpha,beta,U,V] = ordqz(A,B,output='real',sort=select) eigval = abs(numpy.diag(S)/numpy.diag(T)) return [S,T,U,V,eigval]
Eigenvalues bigger than crit are sorted in the top-left.
Below is the the instruction that describes the task: ### Input: Eigenvalues bigger than crit are sorted in the top-left. ### Response: def qzordered(A,B,crit=1.0): "Eigenvalues bigger than crit are sorted in the top-left." TOL = 1e-10 def select(alpha, beta): return alpha**2>crit*beta**2 ...
def get_available_gpus(): """ Returns a list of string names of all available GPUs """ local_device_protos = device_lib.list_local_devices() return [x.name for x in local_device_protos if x.device_type == 'GPU']
Returns a list of string names of all available GPUs
Below is the the instruction that describes the task: ### Input: Returns a list of string names of all available GPUs ### Response: def get_available_gpus(): """ Returns a list of string names of all available GPUs """ local_device_protos = device_lib.list_local_devices() return [x.name for x in local_de...
def get_configdir(name): """ Return the string representing the configuration directory. The directory is chosen as follows: 1. If the ``name.upper() + CONFIGDIR`` environment variable is supplied, choose that. 2a. On Linux, choose `$HOME/.config`. 2b. On other platforms, choose `$HOM...
Return the string representing the configuration directory. The directory is chosen as follows: 1. If the ``name.upper() + CONFIGDIR`` environment variable is supplied, choose that. 2a. On Linux, choose `$HOME/.config`. 2b. On other platforms, choose `$HOME/.matplotlib`. 3. If the chosen...
Below is the the instruction that describes the task: ### Input: Return the string representing the configuration directory. The directory is chosen as follows: 1. If the ``name.upper() + CONFIGDIR`` environment variable is supplied, choose that. 2a. On Linux, choose `$HOME/.config`. 2b. ...
def exclude_range(self, field, start="*", stop="*", inclusive=True, new_group=False): """Exclude a ``field:[some range]`` term from the query. Matches will not have any ``value`` in the range in the ``field``. Arguments: field (str): The field to check for the value. ...
Exclude a ``field:[some range]`` term from the query. Matches will not have any ``value`` in the range in the ``field``. Arguments: field (str): The field to check for the value. The field must be namespaced according to Elasticsearch rules using the ...
Below is the the instruction that describes the task: ### Input: Exclude a ``field:[some range]`` term from the query. Matches will not have any ``value`` in the range in the ``field``. Arguments: field (str): The field to check for the value. The field must be names...
def generate_fault_source_model(self): ''' Creates a resulting `openquake.hmtk` fault source set. :returns: source_model - list of instances of either the :class: `openquake.hmtk.sources.simple_fault_source.mtkSimpleFaultSource` or :class: `openqu...
Creates a resulting `openquake.hmtk` fault source set. :returns: source_model - list of instances of either the :class: `openquake.hmtk.sources.simple_fault_source.mtkSimpleFaultSource` or :class: `openquake.hmtk.sources.complex_fault_source.mtkComplexFaultSource...
Below is the the instruction that describes the task: ### Input: Creates a resulting `openquake.hmtk` fault source set. :returns: source_model - list of instances of either the :class: `openquake.hmtk.sources.simple_fault_source.mtkSimpleFaultSource` or :class: ...
def _check_flag_meanings(self, ds, name): ''' Check a variable's flag_meanings attribute for compliance under CF - flag_meanings exists - flag_meanings is a string - flag_meanings elements are valid strings :param netCDF4.Dataset ds: An open netCDF dataset :para...
Check a variable's flag_meanings attribute for compliance under CF - flag_meanings exists - flag_meanings is a string - flag_meanings elements are valid strings :param netCDF4.Dataset ds: An open netCDF dataset :param str name: Variable name :rtype: compliance_checker.b...
Below is the the instruction that describes the task: ### Input: Check a variable's flag_meanings attribute for compliance under CF - flag_meanings exists - flag_meanings is a string - flag_meanings elements are valid strings :param netCDF4.Dataset ds: An open netCDF dataset ...
def Stephan_Abdelsalam(rhol, rhog, mul, kl, Cpl, Hvap, sigma, Tsat, Te=None, q=None, kw=401, rhow=8.96, Cpw=384, angle=None, correlation='general'): r'''Calculates heat transfer coefficient for a evaporator operating in the nucleate boiling regime according to [2]...
r'''Calculates heat transfer coefficient for a evaporator operating in the nucleate boiling regime according to [2]_ as presented in [1]_. Five variants are possible. Either heat flux or excess temperature is required. The forms for `Te` are not shown here, but are similar to those of the other functio...
Below is the the instruction that describes the task: ### Input: r'''Calculates heat transfer coefficient for a evaporator operating in the nucleate boiling regime according to [2]_ as presented in [1]_. Five variants are possible. Either heat flux or excess temperature is required. The forms for `Te` ...
def get_template_names(self): """Returns the template name to use for this request.""" if self.request.is_ajax(): template = self.ajax_template_name else: template = self.template_name return template
Returns the template name to use for this request.
Below is the the instruction that describes the task: ### Input: Returns the template name to use for this request. ### Response: def get_template_names(self): """Returns the template name to use for this request.""" if self.request.is_ajax(): template = self.ajax_template_name ...
def rhsm_register(self, rhsm): """Register the host on the RHSM. :param rhsm: a dict of parameters (login, password, pool_id) """ # Get rhsm credentials login = rhsm.get('login') password = rhsm.get('password', os.environ.get('RHN_PW')) pool_id = rhsm.get('pool_i...
Register the host on the RHSM. :param rhsm: a dict of parameters (login, password, pool_id)
Below is the the instruction that describes the task: ### Input: Register the host on the RHSM. :param rhsm: a dict of parameters (login, password, pool_id) ### Response: def rhsm_register(self, rhsm): """Register the host on the RHSM. :param rhsm: a dict of parameters (login, password, p...
def diff(s1, s2): ''' --word-diff=porcelain clone''' delta = difflib.Differ().compare(s1.split(), s2.split()) difflist = [] fullline = '' for line in delta: if line[0] == '?': continue elif line[0] == ' ': fullline += line.strip() + ' ' else: ...
--word-diff=porcelain clone
Below is the the instruction that describes the task: ### Input: --word-diff=porcelain clone ### Response: def diff(s1, s2): ''' --word-diff=porcelain clone''' delta = difflib.Differ().compare(s1.split(), s2.split()) difflist = [] fullline = '' for line in delta: if line[0] == '?': ...
def sort_values( self, by, axis=0, ascending=True, inplace=False, kind="quicksort", na_position="last", ): """Sorts by a column/row or list of columns/rows. Args: by: A list of labels for the axis to sort over. ...
Sorts by a column/row or list of columns/rows. Args: by: A list of labels for the axis to sort over. axis: The axis to sort. ascending: Sort in ascending or descending order. inplace: If true, do the operation inplace. kind: How to sort. ...
Below is the the instruction that describes the task: ### Input: Sorts by a column/row or list of columns/rows. Args: by: A list of labels for the axis to sort over. axis: The axis to sort. ascending: Sort in ascending or descending order. inplace: If t...
def get_json(self, prettyprint=False, translate=True): """ Get the data in JSON form """ j = [] if translate: d = self.get_translated_data() else: d = self.data for k in d: j.append(d[k]) if prettyprint: j = ...
Get the data in JSON form
Below is the the instruction that describes the task: ### Input: Get the data in JSON form ### Response: def get_json(self, prettyprint=False, translate=True): """ Get the data in JSON form """ j = [] if translate: d = self.get_translated_data() else: ...
def MakeRequest(http, http_request, retries=7, max_retry_wait=60, redirections=5, retry_func=HandleExceptionsAndRebuildHttpConnections, check_response_func=CheckResponse): """Send http_request via the given http, performing error/retry handling. Args: http:...
Send http_request via the given http, performing error/retry handling. Args: http: An httplib2.Http instance, or a http multiplexer that delegates to an underlying http, for example, HTTPMultiplexer. http_request: A Request to send. retries: (int, default 7) Number of retries to attempt...
Below is the the instruction that describes the task: ### Input: Send http_request via the given http, performing error/retry handling. Args: http: An httplib2.Http instance, or a http multiplexer that delegates to an underlying http, for example, HTTPMultiplexer. http_request: A Request ...
def makeAB(self): """ Munge A and B reads into single serial block with only unique fields.""" for fld in self.m_blk_a: compare_fld = fld.upper() if not "RESERVED" in compare_fld and not "CRC" in compare_fld: self.m_req[fld] = self.m_blk_a[fld] for fld in ...
Munge A and B reads into single serial block with only unique fields.
Below is the the instruction that describes the task: ### Input: Munge A and B reads into single serial block with only unique fields. ### Response: def makeAB(self): """ Munge A and B reads into single serial block with only unique fields.""" for fld in self.m_blk_a: compare_fld = fld....
def _get_album_or_image(json, imgur): """Return a gallery image/album depending on what the json represent.""" if json['is_album']: return Gallery_album(json, imgur, has_fetched=False) return Gallery_image(json, imgur)
Return a gallery image/album depending on what the json represent.
Below is the the instruction that describes the task: ### Input: Return a gallery image/album depending on what the json represent. ### Response: def _get_album_or_image(json, imgur): """Return a gallery image/album depending on what the json represent.""" if json['is_album']: return Gallery_album(...
def send_at_position(self, what, useSelection, where="range"): """Ask the server to perform an operation on a range (sometimes named point) `what` is used as the prefix for the typehint. If `useSelection` is `False` the range is calculated based on the word under de cursor. Current sel...
Ask the server to perform an operation on a range (sometimes named point) `what` is used as the prefix for the typehint. If `useSelection` is `False` the range is calculated based on the word under de cursor. Current selection start and end is used as the range otherwise. `where` defi...
Below is the the instruction that describes the task: ### Input: Ask the server to perform an operation on a range (sometimes named point) `what` is used as the prefix for the typehint. If `useSelection` is `False` the range is calculated based on the word under de cursor. Current selectio...
def xy2rd(input,x=None,y=None,coords=None, coordfile=None,colnames=None,separator=None, hms=True, precision=6,output=None,verbose=True): """ Primary interface to perform coordinate transformations from pixel to sky coordinates using STWCS and full distortion models read from the input im...
Primary interface to perform coordinate transformations from pixel to sky coordinates using STWCS and full distortion models read from the input image header.
Below is the the instruction that describes the task: ### Input: Primary interface to perform coordinate transformations from pixel to sky coordinates using STWCS and full distortion models read from the input image header. ### Response: def xy2rd(input,x=None,y=None,coords=None, coordfile=None,col...
def libvlc_media_add_option(p_md, psz_options): '''Add an option to the media. This option will be used to determine how the media_player will read the media. This allows to use VLC's advanced reading/streaming options on a per-media basis. @note: The options are listed in 'vlc --long-help' from the...
Add an option to the media. This option will be used to determine how the media_player will read the media. This allows to use VLC's advanced reading/streaming options on a per-media basis. @note: The options are listed in 'vlc --long-help' from the command line, e.g. "-sout-all". Keep in mind that ...
Below is the the instruction that describes the task: ### Input: Add an option to the media. This option will be used to determine how the media_player will read the media. This allows to use VLC's advanced reading/streaming options on a per-media basis. @note: The options are listed in 'vlc --long-...
def rename(self): """Renames media file to formatted name. After parsing data from initial media filename and searching for additional data to using a data service, a formatted filename will be generated and the media file will be renamed to the generated name and optionally rel...
Renames media file to formatted name. After parsing data from initial media filename and searching for additional data to using a data service, a formatted filename will be generated and the media file will be renamed to the generated name and optionally relocated.
Below is the the instruction that describes the task: ### Input: Renames media file to formatted name. After parsing data from initial media filename and searching for additional data to using a data service, a formatted filename will be generated and the media file will be renamed ...
def getHourTable(date, pos): """ Returns an HourTable object. """ table = hourTable(date, pos) return HourTable(table, date)
Returns an HourTable object.
Below is the the instruction that describes the task: ### Input: Returns an HourTable object. ### Response: def getHourTable(date, pos): """ Returns an HourTable object. """ table = hourTable(date, pos) return HourTable(table, date)
def fetch_list_members(list_url): """ Get all members of the list specified by the given url. E.g., https://twitter.com/lore77/lists/libri-cultura-education """ match = re.match(r'.+twitter\.com\/(.+)\/lists\/(.+)', list_url) if not match: print('cannot parse list url %s' % list_url) return ...
Get all members of the list specified by the given url. E.g., https://twitter.com/lore77/lists/libri-cultura-education
Below is the the instruction that describes the task: ### Input: Get all members of the list specified by the given url. E.g., https://twitter.com/lore77/lists/libri-cultura-education ### Response: def fetch_list_members(list_url): """ Get all members of the list specified by the given url. E.g., https://twitt...
def get_output(self, buildroot_id): """ Build the 'output' section of the metadata. :return: list, Output instances """ def add_buildroot_id(output): logfile, metadata = output metadata.update({'buildroot_id': buildroot_id}) return Output(fil...
Build the 'output' section of the metadata. :return: list, Output instances
Below is the the instruction that describes the task: ### Input: Build the 'output' section of the metadata. :return: list, Output instances ### Response: def get_output(self, buildroot_id): """ Build the 'output' section of the metadata. :return: list, Output instances ""...
def _convert_to_indexer(self, obj, axis=None, is_setter=False, raise_missing=False): """ Convert indexing key into something we can use to do actual fancy indexing on an ndarray Examples ix[:5] -> slice(0, 5) ix[[1,2,3]] -> [1,2,3] ix[...
Convert indexing key into something we can use to do actual fancy indexing on an ndarray Examples ix[:5] -> slice(0, 5) ix[[1,2,3]] -> [1,2,3] ix[['foo', 'bar', 'baz']] -> [i, j, k] (indices of foo, bar, baz) Going by Zen of Python? 'In the face of ambiguity, re...
Below is the the instruction that describes the task: ### Input: Convert indexing key into something we can use to do actual fancy indexing on an ndarray Examples ix[:5] -> slice(0, 5) ix[[1,2,3]] -> [1,2,3] ix[['foo', 'bar', 'baz']] -> [i, j, k] (indices of foo, bar, baz) ...
def sign(self, tx=None, wifs=[]): """ Sign a provided transaction witht he provided key(s) :param dict tx: The transaction to be signed and returned :param string wifs: One or many wif keys to use for signing a transaction. If not present, the keys will be loaded ...
Sign a provided transaction witht he provided key(s) :param dict tx: The transaction to be signed and returned :param string wifs: One or many wif keys to use for signing a transaction. If not present, the keys will be loaded from the wallet as defined in "missin...
Below is the the instruction that describes the task: ### Input: Sign a provided transaction witht he provided key(s) :param dict tx: The transaction to be signed and returned :param string wifs: One or many wif keys to use for signing a transaction. If not present, the keys...
def normalize(self, stats:Collection[Tensor]=None, do_x:bool=True, do_y:bool=False)->None: "Add normalize transform using `stats` (defaults to `DataBunch.batch_stats`)" if getattr(self,'norm',False): raise Exception('Can not call normalize twice') if stats is None: self.stats = self.batch_stats(...
Add normalize transform using `stats` (defaults to `DataBunch.batch_stats`)
Below is the the instruction that describes the task: ### Input: Add normalize transform using `stats` (defaults to `DataBunch.batch_stats`) ### Response: def normalize(self, stats:Collection[Tensor]=None, do_x:bool=True, do_y:bool=False)->None: "Add normalize transform using `stats` (defaults to `DataBunc...
def parse_arguments(argv): """Parse command line arguments. Args: argv: list of command line arguments, includeing programe name. Returns: An argparse Namespace object. """ parser = argparse.ArgumentParser( description='Runs Preprocessing on structured CSV data.') parser.add_argument('--inpu...
Parse command line arguments. Args: argv: list of command line arguments, includeing programe name. Returns: An argparse Namespace object.
Below is the the instruction that describes the task: ### Input: Parse command line arguments. Args: argv: list of command line arguments, includeing programe name. Returns: An argparse Namespace object. ### Response: def parse_arguments(argv): """Parse command line arguments. Args: argv: li...
def init_app(self, app=None, blueprint=None, additional_blueprints=None): """Update flask application with our api :param Application app: a flask application """ if app is not None: self.app = app if blueprint is not None: self.blueprint = blueprint ...
Update flask application with our api :param Application app: a flask application
Below is the the instruction that describes the task: ### Input: Update flask application with our api :param Application app: a flask application ### Response: def init_app(self, app=None, blueprint=None, additional_blueprints=None): """Update flask application with our api :param Applic...
def _medianindex(self,v): """ find new position of vertex v according to adjacency in layer l+dir. position is given by the median value of adjacent positions. median heuristic is proven to achieve at most 3 times the minimum of crossings (while barycenter achieve in theory the o...
find new position of vertex v according to adjacency in layer l+dir. position is given by the median value of adjacent positions. median heuristic is proven to achieve at most 3 times the minimum of crossings (while barycenter achieve in theory the order of |V|)
Below is the the instruction that describes the task: ### Input: find new position of vertex v according to adjacency in layer l+dir. position is given by the median value of adjacent positions. median heuristic is proven to achieve at most 3 times the minimum of crossings (while barycenter ...
def transport_param(image): """ Parse DockerImage info into skopeo parameter :param image: DockerImage :return: string. skopeo parameter specifying image """ transports = {SkopeoTransport.CONTAINERS_STORAGE: "containers-storage:", SkopeoTransport.DIRECTORY: "dir:", ...
Parse DockerImage info into skopeo parameter :param image: DockerImage :return: string. skopeo parameter specifying image
Below is the the instruction that describes the task: ### Input: Parse DockerImage info into skopeo parameter :param image: DockerImage :return: string. skopeo parameter specifying image ### Response: def transport_param(image): """ Parse DockerImage info into skopeo parameter :param image: Docke...
def addNewMainWindow(self, settings=None, inspectorFullName=None): """ Creates and shows a new MainWindow. If inspectorFullName is set, it will set the identifier from that name. If the inspector identifier is not found in the registry, a KeyError is raised. """ mainWind...
Creates and shows a new MainWindow. If inspectorFullName is set, it will set the identifier from that name. If the inspector identifier is not found in the registry, a KeyError is raised.
Below is the the instruction that describes the task: ### Input: Creates and shows a new MainWindow. If inspectorFullName is set, it will set the identifier from that name. If the inspector identifier is not found in the registry, a KeyError is raised. ### Response: def addNewMainWindow(se...
def mirror(self, axes='x'): """ Generates a symmetry of the Polyhedron respect global axes. :param axes: 'x', 'y', 'z', 'xy', 'xz', 'yz'... :type axes: str :returns: ``pyny.Polyhedron`` """ polygon = np.array([[0,0], [0,1], [1,1]]) space ...
Generates a symmetry of the Polyhedron respect global axes. :param axes: 'x', 'y', 'z', 'xy', 'xz', 'yz'... :type axes: str :returns: ``pyny.Polyhedron``
Below is the the instruction that describes the task: ### Input: Generates a symmetry of the Polyhedron respect global axes. :param axes: 'x', 'y', 'z', 'xy', 'xz', 'yz'... :type axes: str :returns: ``pyny.Polyhedron`` ### Response: def mirror(self, axes='x'): """ ...
def __get_merged_api_info(self, services): """Builds a description of an API. Args: services: List of protorpc.remote.Service instances implementing an api/version. Returns: The _ApiInfo object to use for the API that the given services implement. Raises: ApiConfigurationErr...
Builds a description of an API. Args: services: List of protorpc.remote.Service instances implementing an api/version. Returns: The _ApiInfo object to use for the API that the given services implement. Raises: ApiConfigurationError: If there's something wrong with the API ...
Below is the the instruction that describes the task: ### Input: Builds a description of an API. Args: services: List of protorpc.remote.Service instances implementing an api/version. Returns: The _ApiInfo object to use for the API that the given services implement. Raises: ...
def delete_session(self, ticket): ''' Delete a session record associated with a service ticket. ''' assert isinstance(self.session_storage_adapter, CASSessionAdapter) logging.debug('[CAS] Deleting session for ticket {}'.format(ticket)) self.session_storage_adapter.delete(...
Delete a session record associated with a service ticket.
Below is the the instruction that describes the task: ### Input: Delete a session record associated with a service ticket. ### Response: def delete_session(self, ticket): ''' Delete a session record associated with a service ticket. ''' assert isinstance(self.session_storage_adapter...
def pyquil_to_circuit(program: pyquil.Program) -> Circuit: """Convert a protoquil pyQuil program to a QuantumFlow Circuit""" circ = Circuit() for inst in program.instructions: # print(type(inst)) if isinstance(inst, pyquil.Declare): # Ignore continue if isinst...
Convert a protoquil pyQuil program to a QuantumFlow Circuit
Below is the the instruction that describes the task: ### Input: Convert a protoquil pyQuil program to a QuantumFlow Circuit ### Response: def pyquil_to_circuit(program: pyquil.Program) -> Circuit: """Convert a protoquil pyQuil program to a QuantumFlow Circuit""" circ = Circuit() for inst in program.i...
def getVertices(self,data): """ Returns the vertices of this region already transformed and ready-to-use. Internally uses :py:meth:`Bone.transformVertices()`\ . """ return self.bone.transformVertices(data,self.vertices,self.dims)
Returns the vertices of this region already transformed and ready-to-use. Internally uses :py:meth:`Bone.transformVertices()`\ .
Below is the the instruction that describes the task: ### Input: Returns the vertices of this region already transformed and ready-to-use. Internally uses :py:meth:`Bone.transformVertices()`\ . ### Response: def getVertices(self,data): """ Returns the vertices of this region alread...
def namer(cls, imageUrl, pageUrl): """Use page URL sequence which is apparently increasing.""" num = pageUrl.split('/')[-1] ext = imageUrl.rsplit('.', 1)[1] return "thethinhline-%s.%s" % (num, ext)
Use page URL sequence which is apparently increasing.
Below is the the instruction that describes the task: ### Input: Use page URL sequence which is apparently increasing. ### Response: def namer(cls, imageUrl, pageUrl): """Use page URL sequence which is apparently increasing.""" num = pageUrl.split('/')[-1] ext = imageUrl.rsplit('.', 1)[1] ...
def write_bvec_file(bvecs, bvec_file): """ Write an array of bvecs to a bvec file :param bvecs: array with the vectors :param bvec_file: filepath to write to """ if bvec_file is None: return logger.info('Saving BVEC file: %s' % bvec_file) with open(bvec_file, 'w') as text_file: ...
Write an array of bvecs to a bvec file :param bvecs: array with the vectors :param bvec_file: filepath to write to
Below is the the instruction that describes the task: ### Input: Write an array of bvecs to a bvec file :param bvecs: array with the vectors :param bvec_file: filepath to write to ### Response: def write_bvec_file(bvecs, bvec_file): """ Write an array of bvecs to a bvec file :param bvecs: arr...
def get_users(self, usernames): """Fetch user info for given usernames :param username: The usernames you want metadata for (max. 50) """ if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type) ...
Fetch user info for given usernames :param username: The usernames you want metadata for (max. 50)
Below is the the instruction that describes the task: ### Input: Fetch user info for given usernames :param username: The usernames you want metadata for (max. 50) ### Response: def get_users(self, usernames): """Fetch user info for given usernames :param username: The usernames you want...
def needkwargs(*argnames): """Function decorator which checks that the decorated function is called with a set of required kwargs. Args: *argnames: String keyword argument names. Raises: ValueError: If a required kwarg is missing in the decorated function call. """ ...
Function decorator which checks that the decorated function is called with a set of required kwargs. Args: *argnames: String keyword argument names. Raises: ValueError: If a required kwarg is missing in the decorated function call.
Below is the the instruction that describes the task: ### Input: Function decorator which checks that the decorated function is called with a set of required kwargs. Args: *argnames: String keyword argument names. Raises: ValueError: If a required kwarg is missing in the decorated func...
def _endpoint(self, endpoint, action, *url_args): """Return the URL for the action. :param str endpoint: The controller :param str action: The action provided by the controller :param url_args: Additional endpoints(for endpoints that take part of the url as opti...
Return the URL for the action. :param str endpoint: The controller :param str action: The action provided by the controller :param url_args: Additional endpoints(for endpoints that take part of the url as option) :return: Full URL for the requested action
Below is the the instruction that describes the task: ### Input: Return the URL for the action. :param str endpoint: The controller :param str action: The action provided by the controller :param url_args: Additional endpoints(for endpoints that take part of the url...
def until_any_child_in_state(self, state, timeout=None): """Return a tornado Future; resolves when any client is in specified state""" return until_any(*[r.until_state(state) for r in dict.values(self.children)], timeout=timeout)
Return a tornado Future; resolves when any client is in specified state
Below is the the instruction that describes the task: ### Input: Return a tornado Future; resolves when any client is in specified state ### Response: def until_any_child_in_state(self, state, timeout=None): """Return a tornado Future; resolves when any client is in specified state""" return until_...
def clustering_gmm(data, n_clusters, tol=1e-7, min_covar=None, scale='logicle'): """ Find clusters in an array using a Gaussian Mixture Model. Before clustering, `data` can be automatically rescaled as specified by the `scale` ...
Find clusters in an array using a Gaussian Mixture Model. Before clustering, `data` can be automatically rescaled as specified by the `scale` argument. Parameters ---------- data : FCSData or array_like Data to cluster. n_clusters : int Number of clusters to find. tol : flo...
Below is the the instruction that describes the task: ### Input: Find clusters in an array using a Gaussian Mixture Model. Before clustering, `data` can be automatically rescaled as specified by the `scale` argument. Parameters ---------- data : FCSData or array_like Data to cluster. ...
def get_receive(self, script_list): """Return a list of received events contained in script_list.""" events = defaultdict(set) for script in script_list: if self.script_start_type(script) == self.HAT_WHEN_I_RECEIVE: event = script.blocks[0].args[0].lower() ...
Return a list of received events contained in script_list.
Below is the the instruction that describes the task: ### Input: Return a list of received events contained in script_list. ### Response: def get_receive(self, script_list): """Return a list of received events contained in script_list.""" events = defaultdict(set) for script in script_list:...
def conv(arg,default=None,func=None): ''' essentially, the generalization of arg if arg else default or func(arg) if arg else default ''' if func: return func(arg) if arg else default; else: return arg if arg else default;
essentially, the generalization of arg if arg else default or func(arg) if arg else default
Below is the the instruction that describes the task: ### Input: essentially, the generalization of arg if arg else default or func(arg) if arg else default ### Response: def conv(arg,default=None,func=None): ''' essentially, the generalization of arg if arg else default or...
def householder(self): """Return Matrices u,b,v with self = ubv and b is in bidiagonal form The algorithm uses householder transformations. :return tuple (u,b,v): A tuple with the Matrix u, b and v. and self = ubv (except some rounding errors) u is a unitary mat...
Return Matrices u,b,v with self = ubv and b is in bidiagonal form The algorithm uses householder transformations. :return tuple (u,b,v): A tuple with the Matrix u, b and v. and self = ubv (except some rounding errors) u is a unitary matrix b is a bidiago...
Below is the the instruction that describes the task: ### Input: Return Matrices u,b,v with self = ubv and b is in bidiagonal form The algorithm uses householder transformations. :return tuple (u,b,v): A tuple with the Matrix u, b and v. and self = ubv (except some rounding errors)...
def models(cls, api_version=DEFAULT_API_VERSION): """Module depends on the API version: * 2016-02-01: :mod:`v2016_02_01.models<azure.mgmt.resource.resources.v2016_02_01.models>` * 2016-09-01: :mod:`v2016_09_01.models<azure.mgmt.resource.resources.v2016_09_01.models>` * 2017-05-...
Module depends on the API version: * 2016-02-01: :mod:`v2016_02_01.models<azure.mgmt.resource.resources.v2016_02_01.models>` * 2016-09-01: :mod:`v2016_09_01.models<azure.mgmt.resource.resources.v2016_09_01.models>` * 2017-05-10: :mod:`v2017_05_10.models<azure.mgmt.resource.resources.v2...
Below is the the instruction that describes the task: ### Input: Module depends on the API version: * 2016-02-01: :mod:`v2016_02_01.models<azure.mgmt.resource.resources.v2016_02_01.models>` * 2016-09-01: :mod:`v2016_09_01.models<azure.mgmt.resource.resources.v2016_09_01.models>` * ...
def register(self, item): """ Registers a new orb object to this schema. This could be a column, index, or collector -- including a virtual object defined through the orb.virtual decorator. :param item: <variant> :return: """ if callable(item) and hasattr(item,...
Registers a new orb object to this schema. This could be a column, index, or collector -- including a virtual object defined through the orb.virtual decorator. :param item: <variant> :return:
Below is the the instruction that describes the task: ### Input: Registers a new orb object to this schema. This could be a column, index, or collector -- including a virtual object defined through the orb.virtual decorator. :param item: <variant> :return: ### Response: def register(self...
def get_microscope_files(self, plate_name, acquisition_name): '''Gets status and name of files that have been registered for upload. Parameters ---------- plate_name: str name of the parent plate acquisition_name: str name of the parent acquisition ...
Gets status and name of files that have been registered for upload. Parameters ---------- plate_name: str name of the parent plate acquisition_name: str name of the parent acquisition Returns ------- List[Dict[str, str]] names...
Below is the the instruction that describes the task: ### Input: Gets status and name of files that have been registered for upload. Parameters ---------- plate_name: str name of the parent plate acquisition_name: str name of the parent acquisition R...
def randomPositions(input, nside_pix, n=1): """ Generate n random positions within a full HEALPix mask of booleans, or a set of (lon, lat) coordinates. Parameters: ----------- input : (1) full HEALPix mask of booleans, or (2) a set of (lon, lat) coordinates for catalog objects that define the o...
Generate n random positions within a full HEALPix mask of booleans, or a set of (lon, lat) coordinates. Parameters: ----------- input : (1) full HEALPix mask of booleans, or (2) a set of (lon, lat) coordinates for catalog objects that define the occupied pixels. nside_pix : nside_pix is meant to be...
Below is the the instruction that describes the task: ### Input: Generate n random positions within a full HEALPix mask of booleans, or a set of (lon, lat) coordinates. Parameters: ----------- input : (1) full HEALPix mask of booleans, or (2) a set of (lon, lat) coordinates for catalog objects that...
def encode(self, pdu): """encode the contents of the APCI into the PDU.""" if _debug: APCI._debug("encode %r", pdu) PCI.update(pdu, self) if (self.apduType == ConfirmedRequestPDU.pduType): # PDU type buff = self.apduType << 4 if self.apduSeg: ...
encode the contents of the APCI into the PDU.
Below is the the instruction that describes the task: ### Input: encode the contents of the APCI into the PDU. ### Response: def encode(self, pdu): """encode the contents of the APCI into the PDU.""" if _debug: APCI._debug("encode %r", pdu) PCI.update(pdu, self) if (self.apduType ...
def pauli_constraints(X, Y, Z): """Return a set of constraints that define Pauli spin operators. :param X: List of Pauli X operator on sites. :type X: list of :class:`sympy.physics.quantum.operator.HermitianOperator`. :param Y: List of Pauli Y operator on sites. :type Y: list of :class:`sympy.phys...
Return a set of constraints that define Pauli spin operators. :param X: List of Pauli X operator on sites. :type X: list of :class:`sympy.physics.quantum.operator.HermitianOperator`. :param Y: List of Pauli Y operator on sites. :type Y: list of :class:`sympy.physics.quantum.operator.HermitianOperator`...
Below is the the instruction that describes the task: ### Input: Return a set of constraints that define Pauli spin operators. :param X: List of Pauli X operator on sites. :type X: list of :class:`sympy.physics.quantum.operator.HermitianOperator`. :param Y: List of Pauli Y operator on sites. :type...
def sort_name(self): """ Get the sorting name of this category """ if self._record and self._record.sort_name: return self._record.sort_name return self.name
Get the sorting name of this category
Below is the the instruction that describes the task: ### Input: Get the sorting name of this category ### Response: def sort_name(self): """ Get the sorting name of this category """ if self._record and self._record.sort_name: return self._record.sort_name return self.name
def register(): """Plugin registration.""" from pelican import signals signals.initialized.connect(setup_git) signals.article_generator_finalized.connect(replace_git_url)
Plugin registration.
Below is the the instruction that describes the task: ### Input: Plugin registration. ### Response: def register(): """Plugin registration.""" from pelican import signals signals.initialized.connect(setup_git) signals.article_generator_finalized.connect(replace_git_url)
def merge_dicts(*dicts, **kwargs): """ merge_dicts(*dicts, cls=None) Takes multiple *dicts* and returns a single merged dict. The merging takes place in order of the passed dicts and therefore, values of rear objects have precedence in case of field collisions. The class of the returned merged dict is c...
merge_dicts(*dicts, cls=None) Takes multiple *dicts* and returns a single merged dict. The merging takes place in order of the passed dicts and therefore, values of rear objects have precedence in case of field collisions. The class of the returned merged dict is configurable via *cls*. If it is *None*, the...
Below is the the instruction that describes the task: ### Input: merge_dicts(*dicts, cls=None) Takes multiple *dicts* and returns a single merged dict. The merging takes place in order of the passed dicts and therefore, values of rear objects have precedence in case of field collisions. The class of the...