_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q250500 | markdown | train | def markdown(random=random, length=10, *args, **kwargs):
"""
Produces a bunch of markdown text.
>>> mock_random.seed(0)
>>> markdown(random=mock_random, length=2)
'Nobody will **head** _to_ Mystery Studies Department **to** _buy_ a mighty poop.\\nNobody will **head** _to_ Mystery Studies Department... | python | {
"resource": ""
} |
q250501 | company | train | def company(random=random, *args, **kwargs):
"""
Produce a company name
>>> mock_random.seed(0)
>>> company(random=mock_random)
'faculty of applied chimp'
>>> mock_random.seed(1)
>>> company(random=mock_random)
'blistersecret studios'
>>> mock_random.seed(2)
>>> company(random=m... | python | {
"resource": ""
} |
q250502 | country | train | def country(random=random, *args, **kwargs):
"""
Produce a country name
>>> mock_random.seed(0)
>>> country(random=mock_random)
'testasia'
>>> country(random=mock_random, capitalize=True)
'West Xanth'
>>> country(random=mock_random, slugify=True)
'westeros'
"""
return rando... | python | {
"resource": ""
} |
q250503 | city | train | def city(random=random, *args, **kwargs):
"""
Produce a city name
>>> mock_random.seed(0)
>>> city(random=mock_random)
'east mysteryhall'
>>> city(random=mock_random, capitalize=True)
'Birmingchimp'
>>> city(random=mock_random, slugify=True)
'wonderfulsecretsound'
"""
retur... | python | {
"resource": ""
} |
q250504 | postal_code | train | def postal_code(random=random, *args, **kwargs):
"""
Produce something that vaguely resembles a postal code
>>> mock_random.seed(0)
>>> postal_code(random=mock_random)
'b0b 0c0'
>>> postal_code(random=mock_random, capitalize=True)
'E0E 0F0'
>>> postal_code(random=mock_random, slugify=Tr... | python | {
"resource": ""
} |
q250505 | street | train | def street(random=random, *args, **kwargs):
"""
Produce something that sounds like a street name
>>> mock_random.seed(0)
>>> street(random=mock_random)
'chimp place'
>>> street(random=mock_random, capitalize=True)
'Boatbench Block'
>>> mock_random.seed(3)
>>> street(random=mock_rand... | python | {
"resource": ""
} |
q250506 | address | train | def address(random=random, *args, **kwargs):
"""
A street name plus a number!
>>> mock_random.seed(0)
>>> address(random=mock_random)
'0000 amazingslap boardwalk'
>>> address(random=mock_random, capitalize=True)
'0000 South Throbbingjump Boulevard'
>>> address(random=mock_random, slugif... | python | {
"resource": ""
} |
q250507 | image | train | def image(random=random, width=800, height=600, https=False, *args, **kwargs):
"""
Generate the address of a placeholder image.
>>> mock_random.seed(0)
>>> image(random=mock_random)
'http://dummyimage.com/800x600/292929/e3e3e3&text=mighty poop'
>>> image(random=mock_random, width=60, height=60)... | python | {
"resource": ""
} |
q250508 | decode_copy_value | train | def decode_copy_value(value):
"""
Decodes value received as part of Postgres `COPY` command.
:param value: Value to decode.
:type value: str
:return: Either None if the value is NULL string, or the given value where
escape sequences have been decoded from.
:rtype: str|None
"""... | python | {
"resource": ""
} |
q250509 | unescape_single_character | train | def unescape_single_character(match):
"""
Unescape a single escape sequence found by regular expression.
:param match: Regular expression match object
:rtype: str
:raises: ValueError if the escape sequence is invalid
"""
try:
return DECODE_MAP[match.group(0)]
except KeyError:
... | python | {
"resource": ""
} |
q250510 | run | train | def run(url, output, config):
"""
Extracts database dump from given database URL and outputs sanitized
copy of it into given stream.
:param url: URL to the database which is to be sanitized.
:type url: str
:param output: Stream where sanitized copy of the database dump will be
... | python | {
"resource": ""
} |
q250511 | sanitize | train | def sanitize(url, config):
"""
Obtains dump of an Postgres database by executing `pg_dump` command and
sanitizes it's output.
:param url: URL to the database which is going to be sanitized, parsed by
Python's URL parser.
:type url: six.moves.urllib.parse.ParseResult
:param conf... | python | {
"resource": ""
} |
q250512 | parse_column_names | train | def parse_column_names(text):
"""
Extracts column names from a string containing quoted and comma separated
column names.
:param text: Line extracted from `COPY` statement containing quoted and
comma separated column names.
:type text: str
:return: | python | {
"resource": ""
} |
q250513 | get_mysqldump_args_and_env_from_url | train | def get_mysqldump_args_and_env_from_url(url):
"""
Constructs list of command line arguments and dictionary of environment
variables that can be given to `mysqldump` executable to obtain database
dump of the database described in given URL.
:param url: Parsed database URL.
:type url: urllib.urlp... | python | {
"resource": ""
} |
q250514 | decode_mysql_literal | train | def decode_mysql_literal(text):
"""
Attempts to decode given MySQL literal into Python value.
:param text: Value to be decoded, as MySQL literal.
:type text: str
:return: Python version of the given MySQL literal.
:rtype: any
"""
if MYSQL_NULL_PATTERN.match(text):
return None
... | python | {
"resource": ""
} |
q250515 | decode_mysql_string_literal | train | def decode_mysql_string_literal(text):
"""
Removes quotes and decodes escape sequences from given MySQL string literal
returning the result.
:param text: MySQL string literal, with the quotes still included.
:type text: str
:return: Given string literal with quotes removed and escape sequences... | python | {
"resource": ""
} |
q250516 | OutputMonitor.wait_for | train | def wait_for(self, text, seconds):
"""
Returns True when the specified text has appeared in a line of the
output, or False when the specified number of seconds have passed
without that occurring.
"""
found = False
stream = self.stream
start_time = time.tim... | python | {
"resource": ""
} |
q250517 | DockerSelenium.command_executor | train | def command_executor(self):
"""Get the appropriate command executor URL for the Selenium server
running in | python | {
"resource": ""
} |
q250518 | DockerSelenium.start | train | def start(self):
"""Start the Docker container"""
if self.container_id is not None:
msg = 'The Docker container is already running with ID {}'
raise Exception(msg.format(self.container_id))
process = Popen(['docker ps | grep ":{}"'.format(self.port)],
... | python | {
"resource": ""
} |
q250519 | DockerSelenium.stop | train | def stop(self):
"""Stop the Docker container"""
if self.container_id is None:
raise Exception('No Docker Selenium container was running')
| python | {
"resource": ""
} |
q250520 | hash_text_to_ints | train | def hash_text_to_ints(value, bit_lengths=(16, 16, 16, 16)):
# type: (str, Sequence[int]) -> Sequence[int]
"""
Hash a text value to a sequence of integers.
Generates a sequence of integer values with given bit-lengths
similarly to `hash_text_to_int`, but allowing generating many
separate numbers... | python | {
"resource": ""
} |
q250521 | hash_text | train | def hash_text(value, hasher=hashlib.sha256, encoding='utf-8'):
# type: (str, Callable, str) -> str
"""
Generate a hash for a text value.
The hash will be generated by encoding the text to bytes with given
encoding and then generating a hash with HMAC using the session
secret as the key and the ... | python | {
"resource": ""
} |
q250522 | hash_bytes | train | def hash_bytes(value, hasher=hashlib.sha256):
# type: (bytes, Callable) -> str
"""
Generate a hash for a bytes value.
The hash will be generated by generating a hash with HMAC using the | python | {
"resource": ""
} |
q250523 | _initialize_session | train | def _initialize_session():
# type: () -> None
"""
Generate a new session key and store it to thread local storage.
"""
sys_random = random.SystemRandom()
_thread_local_storage.secret_key = | python | {
"resource": ""
} |
q250524 | EvaluationMixin._get_proxy_object | train | def _get_proxy_object(self, obj, ProxyKlass, proxy_klass_attribute):
""" Returns the proxy object for an input object
If the object is already the proxy object, return it.
Otherwise set the appropriate proxy object to the proxy object's attribute
"""
| python | {
"resource": ""
} |
q250525 | Configuration.from_file | train | def from_file(cls, filename):
"""
Reads configuration from given path to a file in local file system and
returns parsed version of it.
:param filename: Path to the YAML file in local file system where the
configuration will be read from.
:type filename: ... | python | {
"resource": ""
} |
q250526 | Configuration.load | train | def load(self, config_data):
"""
Loads sanitizers according to rulesets defined in given already parsed
configuration file.
:param config_data: Already parsed configuration data, as dictionary.
:type config_data: dict[str,any]
"""
if not isinstance(config_data, d... | python | {
"resource": ""
} |
q250527 | Configuration.load_addon_packages | train | def load_addon_packages(self, config_data):
"""
Loads the module paths from which the configuration will attempt to
load sanitizers from. These must be stored as a list of strings under
"config.addons" section of the configuration data.
:param config_data: Already parsed configu... | python | {
"resource": ""
} |
q250528 | Configuration.load_sanitizers | train | def load_sanitizers(self, config_data):
"""
Loads sanitizers possibly defined in the configuration under dictionary
called "strategy", which should contain mapping of database tables with
column names mapped into sanitizer function names.
:param config_data: Already parsed confi... | python | {
"resource": ""
} |
q250529 | Configuration.find_sanitizer | train | def find_sanitizer(self, name):
"""
Searches for a sanitizer function with given name. The name should
contain two parts separated from each other with a dot, the first
part being the module name while the second being name of the function
contained in the module, when it's being... | python | {
"resource": ""
} |
q250530 | Configuration.find_sanitizer_from_module | train | def find_sanitizer_from_module(module_name, function_name):
"""
Attempts to find sanitizer function from given module. If the module
cannot be imported, or function with given name does not exist in it,
nothing will be returned by this method. Otherwise the found sanitizer
functi... | python | {
"resource": ""
} |
q250531 | Configuration.get_sanitizer_for | train | def get_sanitizer_for(self, table_name, column_name):
"""
Get sanitizer for given table and column name.
:param table_name: Name of the database table.
:type table_name: str
:param column_name: Name of the database column.
:type column_name: str
:return: Saniti... | python | {
"resource": ""
} |
q250532 | Configuration.sanitize | train | def sanitize(self, table_name, column_name, value):
"""
Sanitizes given value extracted from the database according to the
sanitation configuration.
TODO: Add support for dates, booleans and other types found in SQL than
string.
:param table_name: Name of the database t... | python | {
"resource": ""
} |
q250533 | Command.add_arguments | train | def add_arguments(self, parser):
"""Command line arguments for Django 1.8+"""
# Add the underlying test command arguments first
test_command = TestCommand()
| python | {
"resource": ""
} |
q250534 | Command.clean | train | def clean():
"""Clear out any old screenshots"""
screenshot_dir = settings.SELENIUM_SCREENSHOT_DIR
if | python | {
"resource": ""
} |
q250535 | Command.verify_appium_is_running | train | def verify_appium_is_running(self):
"""Verify that Appium is running so it can be used for local iOS tests."""
process = Popen(['ps -e | grep "Appium"'], shell=True, stdout=PIPE)
(grep_output, _grep_error) = process.communicate()
lines = grep_output.split('\n')
for line in lines:... | python | {
"resource": ""
} |
q250536 | NumpyHasher.save | train | def save(self, obj):
""" Subclass the save method, to hash ndarray subclass, rather
than pickling them. Off course, this is a total abuse of
the Pickler class.
"""
if isinstance(obj, self.np.ndarray) and not obj.dtype.hasobject:
# Compute a hash of the object
... | python | {
"resource": ""
} |
q250537 | sanitize_random | train | def sanitize_random(value):
"""
Random string of same length as the given value.
"""
if not value:
| python | {
"resource": ""
} |
q250538 | sanitize | train | def sanitize(url, config):
"""
Obtains dump of MySQL database by executing `mysqldump` command and
sanitizes it output.
:param url: URL to the database which is going to be sanitized, parsed by
Python's URL parser.
:type url: urllib.urlparse.ParseResult
:param config: Optional ... | python | {
"resource": ""
} |
q250539 | sanitize_from_stream | train | def sanitize_from_stream(stream, config):
"""
Reads dump of MySQL database from given stream and sanitizes it.
:param stream: Stream where the database dump is expected to be available
from, such as stdout of `mysqldump` process.
:type stream: file
:param config: Optional saniti... | python | {
"resource": ""
} |
q250540 | parse_column_names | train | def parse_column_names(text):
"""
Extracts column names from a string containing quoted and comma separated
column names of a table.
:param text: Line extracted from MySQL's `INSERT INTO` statement containing
quoted and comma separated column names.
:type text: str
| python | {
"resource": ""
} |
q250541 | parse_values | train | def parse_values(text):
"""
Parses values from a string containing values from extended format `INSERT
INTO` statement. Values will be yielded from the function as tuples, with
one tuple per row in the table.
:param text: Text extracted from MySQL's `INSERT INTO` statement containing
... | python | {
"resource": ""
} |
q250542 | HashableFileMixin.persist | train | def persist(self):
"""a private method that persists an object to the filesystem"""
if self.hash:
| python | {
"resource": ""
} |
q250543 | HashableFileMixin.load | train | def load(self):
"""a private method that loads an object from the filesystem"""
if self.is_persisted:
| python | {
"resource": ""
} |
q250544 | DatabaseOperations._switch_tz_offset_sql | train | def _switch_tz_offset_sql(self, field_name, tzname):
"""
Returns the SQL that will convert field_name to UTC from tzname.
"""
field_name = self.quote_name(field_name)
if settings.USE_TZ:
if pytz is None:
from django.core.exceptions import ImproperlyCon... | python | {
"resource": ""
} |
q250545 | DatabaseOperations.datetime_trunc_sql | train | def datetime_trunc_sql(self, lookup_type, field_name, tzname):
"""
Given a lookup_type of 'year', 'month', 'day', 'hour', 'minute' or
'second', returns the SQL that truncates the given datetime field
field_name to a datetime object with only the given specificity, and
a tuple of ... | python | {
"resource": ""
} |
q250546 | DatabaseOperations.last_insert_id | train | def last_insert_id(self, cursor, table_name, pk_name):
"""
Given a cursor object that has just performed an INSERT statement into
a table that has an auto-incrementing ID, returns the newly created ID.
This method also receives the table name and the name of the primary-key
colu... | python | {
"resource": ""
} |
q250547 | DatabaseOperations.quote_name | train | def quote_name(self, name):
"""
Returns a quoted version of the given table, index or column name. Does
not quote the given name if it's already been quoted.
"""
| python | {
"resource": ""
} |
q250548 | DatabaseOperations.last_executed_query | train | def last_executed_query(self, cursor, sql, params):
"""
Returns a string of the query last executed by the given cursor, with
placeholders replaced with actual values.
`sql` is the raw query containing placeholders, and `params` is the
sequence of parameters. These are used by d... | python | {
"resource": ""
} |
q250549 | DatabaseOperations.adapt_datetimefield_value | train | def adapt_datetimefield_value(self, value):
"""
Transform a datetime value to an object compatible with what is expected
by the backend driver for datetime columns.
"""
if value is None:
return None
if self.connection._DJANGO_VERSION >= 14 and settings.USE_TZ:... | python | {
"resource": ""
} |
q250550 | DatabaseOperations.adapt_timefield_value | train | def adapt_timefield_value(self, value):
"""
Transform a time value to an object compatible with what is expected
by the backend driver for time columns.
"""
if value is None:
return None
# SQL Server doesn't support microseconds
| python | {
"resource": ""
} |
q250551 | DatabaseOperations.convert_values | train | def convert_values(self, value, field):
"""
Coerce the value returned by the database backend into a consistent
type that is compatible with the field type.
In our case, cater for the fact that SQL Server < 2008 has no
separate Date and Time data types.
TODO: See how we'... | python | {
"resource": ""
} |
q250552 | DatabaseIntrospection._is_auto_field | train | def _is_auto_field(self, cursor, table_name, column_name):
"""
Checks whether column is Identity
"""
# COLUMNPROPERTY: http://msdn2.microsoft.com/en-us/library/ms174968.aspx
#from django.db import connection
#cursor.execute("SELECT COLUMNPROPERTY(OBJECT_ID(%s), %s, 'IsId... | python | {
"resource": ""
} |
q250553 | DatabaseIntrospection.get_table_description | train | def get_table_description(self, cursor, table_name, identity_check=True):
"""Returns a description of the table, with DB-API cursor.description interface.
The 'auto_check' parameter has been added to the function argspec.
If set to True, the function will check each of the table's fields for th... | python | {
"resource": ""
} |
q250554 | _break | train | def _break(s, find):
"""Break a string s into the part before the substring to find,
and the part | python | {
"resource": ""
} |
q250555 | SQLCompiler._fix_aggregates | train | def _fix_aggregates(self):
"""
MSSQL doesn't match the behavior of the other backends on a few of
the aggregate functions; different return type behavior, different
function names, etc.
MSSQL's implementation of AVG maintains datatype without proding. To
match behavior o... | python | {
"resource": ""
} |
q250556 | SQLCompiler._fix_slicing_order | train | def _fix_slicing_order(self, outer_fields, inner_select, order, inner_table_name):
"""
Apply any necessary fixes to the outer_fields, inner_select, and order
strings due to slicing.
"""
# Using ROW_NUMBER requires an ordering
if order is None:
meta = self.quer... | python | {
"resource": ""
} |
q250557 | SQLCompiler._alias_columns | train | def _alias_columns(self, sql):
"""Return tuple of SELECT and FROM clauses, aliasing duplicate column names."""
qn = self.connection.ops.quote_name
outer = list()
inner = list()
names_seen = list()
# replace all parens with placeholders
paren_depth, paren_buf = 0... | python | {
"resource": ""
} |
q250558 | SQLInsertCompiler._fix_insert | train | def _fix_insert(self, sql, params):
"""
Wrap the passed SQL with IDENTITY_INSERT statements and apply
other necessary fixes.
"""
meta = self.query.get_meta()
if meta.has_auto_field:
if hasattr(self.query, 'fields'):
# django 1.4 replaced colum... | python | {
"resource": ""
} |
q250559 | head | train | def head(line, n: int):
"""returns the first `n` lines"""
global counter
counter += 1
if counter > n:
| python | {
"resource": ""
} |
q250560 | cmd | train | def cmd(f):
"""wrapper for easily exposing a function as a CLI command.
including help message, arguments help and type.
Example Usage:
>>> import cbox
>>>
>>> @cbox.cmd
>>> def hello(name: str):
>>> '''greets a person by its name.
>>>
>>> :p... | python | {
"resource": ""
} |
q250561 | main | train | def main(func=None, argv=None, input_stream=stdin, output_stream=stdout,
error_stream=stderr, exit=True):
"""runs a function as a command.
runs a function as a command - reading input from `input_stream`, writing
output into `output_stream` and providing arguments from `argv`.
Example Usage:
... | python | {
"resource": ""
} |
q250562 | _parse_docstring | train | def _parse_docstring(docstring):
"""parses docstring into its help message and params"""
params = {}
if not docstring:
return None, params
try:
help_msg = _DOCSTRING_REGEX.search(docstring).group()
help_msg = _strip_lines(help_msg)
except AttributeError:
help_msg = ... | python | {
"resource": ""
} |
q250563 | error2str | train | def error2str(e):
"""returns the formatted stacktrace of the exception `e`.
:param BaseException e: an exception to format into str
:rtype: str
"""
| python | {
"resource": ""
} |
q250564 | get_runner | train | def get_runner(worker_type, max_workers=None, workers_window=None):
"""returns a runner callable.
:param str worker_type: one of `simple` or `thread`.
:param int max_workers: max workers the runner can spawn in parallel.
:param in workers_window: max number of jobs waiting to be done by the
worke... | python | {
"resource": ""
} |
q250565 | get_inline_func | train | def get_inline_func(inline_str, modules=None, **stream_kwargs):
"""returns a function decorated by `cbox.stream` decorator.
:param str inline_str: the inline function to execute,
can use `s` - local variable as the input line/char/raw
(according to `input_type` param).
:param str modules: comma... | python | {
"resource": ""
} |
q250566 | setmode | train | def setmode(mode):
"""
You must call this method prior to using all other calls.
:param mode: the mode, one of :py:attr:`GPIO.BOARD`, :py:attr:`GPIO.BCM`,
:py:attr:`GPIO.SUNXI`, or a `dict` or `object` representing a custom
pin mapping.
"""
if hasattr(mode, '__getitem__'):
| python | {
"resource": ""
} |
q250567 | setup | train | def setup(channel, direction, initial=None, pull_up_down=None):
"""
You need to set up every channel you are using as an input or an output.
:param channel: the channel based on the numbering system you have specified
(:py:attr:`GPIO.BOARD`, :py:attr:`GPIO.BCM` or :py:attr:`GPIO.SUNXI`).
:param... | python | {
"resource": ""
} |
q250568 | input | train | def input(channel):
"""
Read the value of a GPIO pin.
:param channel: the channel based on the numbering system you have specified
(:py:attr:`GPIO.BOARD`, :py:attr:`GPIO.BCM` or :py:attr:`GPIO.SUNXI`).
:returns: This will return either :py:attr:`0` / :py:attr:`GPIO.LOW` /
| python | {
"resource": ""
} |
q250569 | output | train | def output(channel, state):
"""
Set the output state of a GPIO pin.
:param channel: the channel based on the numbering system you have specified
(:py:attr:`GPIO.BOARD`, :py:attr:`GPIO.BCM` or :py:attr:`GPIO.SUNXI`).
:param state: can be :py:attr:`0` / :py:attr:`GPIO.LOW` / :py:attr:`False`
... | python | {
"resource": ""
} |
q250570 | wait_for_edge | train | def wait_for_edge(channel, trigger, timeout=-1):
"""
This function is designed to block execution of your program until an edge
is detected.
:param channel: the channel based on the numbering system you have specified
(:py:attr:`GPIO.BOARD`, :py:attr:`GPIO.BCM` or :py:attr:`GPIO.SUNXI`).
:p... | python | {
"resource": ""
} |
q250571 | is_swapped | train | def is_swapped(app_label, model):
"""
Returns the value of the swapped setting, or False if the model hasn't
been swapped.
"""
default_model = | python | {
"resource": ""
} |
q250572 | get_model_names | train | def get_model_names(app_label, models):
"""
Map model names to their swapped equivalents for the given app
"""
return dict(
| python | {
"resource": ""
} |
q250573 | AttributeDict.update | train | def update(self, entries = {}, *args, **kwargs):
"""
Update dictionary.
@example:
object.update({'foo': {'bar': 1}})
"""
if isinstance(entries, dict):
entries = self._reject_reserved_keys(entries)
for key, value in dict(entries, *args, **kwargs... | python | {
"resource": ""
} |
q250574 | read_table | train | def read_table(filename, usecols=(0, 1), sep='\t', comment='#', encoding='utf-8', skip=0):
"""Parse data files from the data directory
Parameters
----------
filename: string
Full path to file
usecols: list, default [0, 1]
A list of two elements representing the columns to be parsed... | python | {
"resource": ""
} |
q250575 | build_index | train | def build_index():
"""Load information from the data directory
Returns
-------
A namedtuple with three fields: nationalities cities countries
"""
nationalities = read_table(get_data_path('nationalities.txt'), sep=':')
# parse http://download.geonames.org/export/dump/countryInfo.txt
co... | python | {
"resource": ""
} |
q250576 | _find_executables | train | def _find_executables(name):
""" Try to find an executable.
"""
exe_name = name + '.exe' * sys.platform.startswith('win')
env_path = os.environ.get(name.upper()+ '_PATH', '')
possible_locations = []
def add(*dirs):
for d in dirs:
if d and d not in possible_locations and ... | python | {
"resource": ""
} |
q250577 | get_elastix_exes | train | def get_elastix_exes():
""" Get the executables for elastix and transformix. Raises an error
if they cannot be found.
"""
if EXES:
if EXES[0]:
return EXES
else:
raise RuntimeError('No Elastix executable.')
# Find exe
elastix, ver = _find_executables('... | python | {
"resource": ""
} |
q250578 | _clear_dir | train | def _clear_dir(dirName):
""" Remove a directory and it contents. Ignore any failures.
"""
# If we got here, clear dir
for fname in os.listdir(dirName):
try:
os.remove( os.path.join(dirName, fname) )
| python | {
"resource": ""
} |
q250579 | get_tempdir | train | def get_tempdir():
""" Get the temporary directory where pyelastix stores its temporary
files. The directory is specific to the current process and the
calling thread. Generally, the user does not need this; directories
are automatically cleaned up. Though Elastix log files are also
written here.
... | python | {
"resource": ""
} |
q250580 | _clear_temp_dir | train | def _clear_temp_dir():
""" Clear the temporary directory.
"""
tempdir = get_tempdir()
for fname in os.listdir(tempdir):
try:
| python | {
"resource": ""
} |
q250581 | _get_image_paths | train | def _get_image_paths(im1, im2):
""" If the images are paths to a file, checks whether the file exist
and return the paths. If the images are numpy arrays, writes them
to disk and returns the paths of the new files.
"""
paths = []
for im in [im1, im2]:
if im is None:
# Gr... | python | {
"resource": ""
} |
q250582 | _system3 | train | def _system3(cmd, verbose=False):
""" Execute the given command in a subprocess and wait for it to finish.
A thread is run that prints output of the process if verbose is True.
"""
# Init flag
interrupted = False
# Create progress
if verbose > 0:
progress = Progress()
... | python | {
"resource": ""
} |
q250583 | _get_dtype_maps | train | def _get_dtype_maps():
""" Get dictionaries to map numpy data types to ITK types and the
other way around.
"""
# Define pairs
tmp = [ (np.float32, 'MET_FLOAT'), (np.float64, 'MET_DOUBLE'),
(np.uint8, 'MET_UCHAR'), (np.int8, 'MET_CHAR'),
(np.uint16, 'MET_USHORT'), (... | python | {
"resource": ""
} |
q250584 | _read_image_data | train | def _read_image_data( mhd_file):
""" Read the resulting image data and return it as a numpy array.
"""
tempdir = get_tempdir()
# Load description from mhd file
fname = tempdir + '/' + mhd_file
des = open(fname, 'r').read()
# Get data filename and load raw data
match = re.findal... | python | {
"resource": ""
} |
q250585 | _get_fixed_params | train | def _get_fixed_params(im):
""" Parameters that the user has no influence on. Mostly chosen
bases on the input images.
"""
p = Parameters()
if not isinstance(im, np.ndarray):
return p
# Dimension of the inputs
p.FixedImageDimension = im.ndim
p.MovingImageDimension =... | python | {
"resource": ""
} |
q250586 | get_advanced_params | train | def get_advanced_params():
""" Get `Parameters` struct with parameters that most users do not
want to think about.
"""
p = Parameters()
# Internal format used during the registration process
p.FixedInternalImagePixelType = "float"
p.MovingInternalImagePixelType = "float"
#... | python | {
"resource": ""
} |
q250587 | _write_parameter_file | train | def _write_parameter_file(params):
""" Write the parameter file in the format that elaxtix likes.
"""
# Get path
path = os.path.join(get_tempdir(), 'params.txt')
# Define helper function
def valToStr(val):
if val in [True, False]:
return '"%s"' % str(val).lower()
... | python | {
"resource": ""
} |
q250588 | _highlight | train | def _highlight(html):
"""Syntax-highlights HTML-rendered Markdown.
Plucks sections to highlight that conform the the GitHub fenced code info
string as defined at https://github.github.com/gfm/#info-string.
Args:
html (str): The rendered HTML.
Returns:
str: The HTML with Pygments s... | python | {
"resource": ""
} |
q250589 | Check.check_restructuredtext | train | def check_restructuredtext(self):
"""
Checks if the long string fields are reST-compliant.
"""
# Warn that this command is deprecated
# Don't use self.warn() because it will cause the check to fail.
Command.warn(
self,
"This command has been deprec... | python | {
"resource": ""
} |
q250590 | render_code | train | def render_code(code, filetype, pygments_style):
"""Renders a piece of code into HTML. Highlights syntax if filetype is specfied"""
if filetype:
lexer = pygments.lexers.get_lexer_by_name(filetype)
| python | {
"resource": ""
} |
q250591 | GraphAPI.fql | train | def fql(self, query, args=None, post_args=None):
"""FQL query.
Example query: "SELECT affiliations FROM user WHERE uid = me()"
"""
args = args or {}
if self.access_token:
if post_args is not None:
post_args["access_token"] = self.access_token
... | python | {
"resource": ""
} |
q250592 | _constraint_lb_and_ub_to_gurobi_sense_rhs_and_range_value | train | def _constraint_lb_and_ub_to_gurobi_sense_rhs_and_range_value(lb, ub):
"""Helper function used by Constraint and Model"""
if lb is None and ub is None:
raise Exception("Free constraint ...")
elif lb is None:
sense = '<'
rhs = float(ub)
range_value = 0.
elif ub is None:
... | python | {
"resource": ""
} |
q250593 | parse_optimization_expression | train | def parse_optimization_expression(obj, linear=True, quadratic=False, expression=None, **kwargs):
"""
Function for parsing the expression of a Constraint or Objective object.
Parameters
----------
object: Constraint or Objective
The optimization expression to be parsed
linear: Boolean
... | python | {
"resource": ""
} |
q250594 | _parse_quadratic_expression | train | def _parse_quadratic_expression(expression, expanded=False):
"""
Parse a quadratic expression. It is assumed that the expression is known to be quadratic or linear.
The 'expanded' parameter tells whether the expression has already been expanded. If it hasn't the parsing
might fail and will expand the e... | python | {
"resource": ""
} |
q250595 | Variable.clone | train | def clone(cls, variable, **kwargs):
"""
Make a copy of another variable. The variable being copied can be of the same type or belong to
a different solver interface.
Example
----------
| python | {
"resource": ""
} |
q250596 | Variable.set_bounds | train | def set_bounds(self, lb, ub):
"""
Change the lower and upper bounds of a variable.
"""
if lb is not None and ub is not None and lb > ub:
raise ValueError(
"The provided lower bound {} is larger than the provided upper bound {}".format(lb, ub)
)
... | python | {
"resource": ""
} |
q250597 | Variable.to_json | train | def to_json(self):
"""
Returns a json-compatible object from the Variable that can be saved using the json module.
Example
--------
>>> import json
>>> with open("path_to_file.json", "w") as outfile:
>>> json.dump(var.to_json(), outfile)
"""
| python | {
"resource": ""
} |
q250598 | Constraint.clone | train | def clone(cls, constraint, model=None, **kwargs):
"""
Make a copy of another constraint. The constraint being copied can be of the same type or belong to
a different solver interface.
Parameters
----------
constraint: interface.Constraint (or subclass)
The co... | python | {
"resource": ""
} |
q250599 | Constraint.to_json | train | def to_json(self):
"""
Returns a json-compatible object from the constraint that can be saved using the json module.
Example
--------
>>> import json
>>> with open("path_to_file.json", "w") as outfile:
>>> json.dump(constraint.to_json(), outfile)
"""
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.