_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q42800 | connect | train | def connect(slug, config_loader):
"""
Ensure .cs50.yaml and tool key exists, raises Error otherwise
Check that all required files as per .cs50.yaml are present
Returns tool specific portion of .cs50.yaml
"""
with ProgressBar(_("Connecting")):
# Parse slug
slug = Slug(slug)
... | python | {
"resource": ""
} |
q42801 | authenticate | train | def authenticate(org):
"""
Authenticate with GitHub via SSH if possible
Otherwise authenticate via HTTPS
Returns an authenticated User
"""
with ProgressBar(_("Authenticating")) as progress_bar:
user = _authenticate_ssh(org)
progress_bar.stop()
if user is None:
... | python | {
"resource": ""
} |
q42802 | prepare | train | def prepare(tool, branch, user, included):
"""
Prepare git for pushing
Check that there are no permission errors
Add necessities to git config
Stage files
Stage files via lfs if necessary
Check that atleast one file is staged
"""
with ProgressBar(_("Preparing")) as progress_bar, work... | python | {
"resource": ""
} |
q42803 | upload | train | def upload(branch, user, tool):
"""
Commit + push to branch
Returns username, commit hash
"""
with ProgressBar(_("Uploading")):
language = os.environ.get("LANGUAGE")
commit_message = [_("automated commit by {}").format(tool)]
# If LANGUAGE environment variable is set, we nee... | python | {
"resource": ""
} |
q42804 | _run | train | def _run(command, quiet=False, timeout=None):
"""Run a command, returns command output."""
try:
with _spawn(command, quiet, timeout) as child:
command_output = child.read().strip().replace("\r\n", "\n")
except pexpect.TIMEOUT:
logger.info(f"command {command} timed out")
r... | python | {
"resource": ""
} |
q42805 | _glob | train | def _glob(pattern, skip_dirs=False):
"""Glob pattern, expand directories, return all files that matched."""
# Implicit recursive iff no / in pattern and starts with *
if "/" not in pattern and pattern.startswith("*"):
files = glob.glob(f"**/{pattern}", recursive=True)
else:
files = glob.... | python | {
"resource": ""
} |
q42806 | _lfs_add | train | def _lfs_add(files, git):
"""
Add any oversized files with lfs.
Throws error if a file is bigger than 2GB or git-lfs is not installed.
"""
# Check for large files > 100 MB (and huge files > 2 GB)
# https://help.github.com/articles/conditions-for-large-files/
# https://help.github.com/article... | python | {
"resource": ""
} |
q42807 | _authenticate_ssh | train | def _authenticate_ssh(org):
"""Try authenticating via ssh, if succesful yields a User, otherwise raises Error."""
# Try to get username from git config
username = os.environ.get(f"{org.upper()}_USERNAME")
# Require ssh-agent
child = pexpect.spawn("ssh -T git@github.com", encoding="utf8")
# GitHu... | python | {
"resource": ""
} |
q42808 | _authenticate_https | train | def _authenticate_https(org):
"""Try authenticating via HTTPS, if succesful yields User, otherwise raises Error."""
_CREDENTIAL_SOCKET.parent.mkdir(mode=0o700, exist_ok=True)
try:
Git.cache = f"-c credential.helper= -c credential.helper='cache --socket {_CREDENTIAL_SOCKET}'"
git = Git(Git.ca... | python | {
"resource": ""
} |
q42809 | _prompt_username | train | def _prompt_username(prompt="Username: ", prefill=None):
"""Prompt the user for username."""
if prefill:
readline.set_startup_hook(lambda: readline.insert_text(prefill))
try:
return input(prompt).strip()
except EOFError:
print()
finally:
readline.set_startup_hook() | python | {
"resource": ""
} |
q42810 | _prompt_password | train | def _prompt_password(prompt="Password: "):
"""Prompt the user for password, printing asterisks for each character"""
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
tty.setraw(fd)
print(prompt, end="", flush=True)
password = []
try:
while True:
ch = sys.stdi... | python | {
"resource": ""
} |
q42811 | ProgressBar.stop | train | def stop(self):
"""Stop the progress bar."""
if self._progressing:
self._progressing = False
self._thread.join() | python | {
"resource": ""
} |
q42812 | make_url | train | def make_url(path, protocol=None, hosts=None):
"""Make an URL given a path, and optionally, a protocol and set of
hosts to select from randomly.
:param path: The Archive.org path.
:type path: str
:param protocol: (optional) The HTTP protocol to use. "https://" is
used by defau... | python | {
"resource": ""
} |
q42813 | metadata_urls | train | def metadata_urls(identifiers, protocol=None, hosts=None):
"""An Archive.org metadata URL generator.
:param identifiers: A set of Archive.org identifiers for which to
make metadata URLs.
:type identifiers: iterable
:param protocol: (optional) The HTTP protocol to use. "https://... | python | {
"resource": ""
} |
q42814 | lang_direction | train | def lang_direction(request):
"""
Sets lang_direction context variable to whether the language is RTL or LTR
"""
if lang_direction.rtl_langs is None:
lang_direction.rtl_langs = getattr(settings, "RTL_LANGUAGES", set())
return {"lang_direction": "rtl" if request.LANGUAGE_CODE in lang_directio... | python | {
"resource": ""
} |
q42815 | Lists.lists | train | def lists(self, **kwargs):
"""Gets the top-level lists available from the API.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_path('lists')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
... | python | {
"resource": ""
} |
q42816 | Lists.movie_lists | train | def movie_lists(self, **kwargs):
"""Gets the movie lists available from the API.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_path('movie_lists')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
... | python | {
"resource": ""
} |
q42817 | Lists.movies_box_office | train | def movies_box_office(self, **kwargs):
"""Gets the top box office earning movies from the API.
Sorted by most recent weekend gross ticket sales.
Args:
limit (optional): limits the number of movies returned, default=10
country (optional): localized data for selected countr... | python | {
"resource": ""
} |
q42818 | Lists.movies_in_theaters | train | def movies_in_theaters(self, **kwargs):
"""Gets the movies currently in theaters from the API.
Args:
page_limit (optional): number of movies to show per page, default=16
page (optional): results page number, default=1
country (optional): localized data for selected country... | python | {
"resource": ""
} |
q42819 | Lists.dvd_lists | train | def dvd_lists(self, **kwargs):
"""Gets the dvd lists available from the API.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_path('dvd_lists')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
... | python | {
"resource": ""
} |
q42820 | create_regex_patterns | train | def create_regex_patterns(symbols):
u"""create regex patterns for text, google, docomo, kddi and softbank via `symbols`
create regex patterns for finding emoji character from text. the pattern character use
`unicode` formatted character so you have to decode text which is not decoded.
"""
patte... | python | {
"resource": ""
} |
q42821 | vtquery | train | def vtquery(apikey, checksums):
"""Performs the query dealing with errors and throttling requests."""
data = {'apikey': apikey,
'resource': isinstance(checksums, str) and checksums
or ', '.join(checksums)}
while 1:
response = requests.post(VT_REPORT_URL, data=dat... | python | {
"resource": ""
} |
q42822 | chunks | train | def chunks(iterable, size=1):
"""Splits iterator in chunks."""
iterator = iter(iterable)
for element in iterator:
yield chain([element], islice(iterator, size - 1)) | python | {
"resource": ""
} |
q42823 | VTScanner.scan | train | def scan(self, filetypes=None):
"""Iterates over the content of the disk and queries VirusTotal
to determine whether it's malicious or not.
filetypes is a list containing regular expression patterns.
If given, only the files which type will match with one or more of
the given pa... | python | {
"resource": ""
} |
q42824 | compute_training_sizes | train | def compute_training_sizes(train_perc, class_sizes, stratified=True):
"""Computes the maximum training size that the smallest class can provide """
size_per_class = np.int64(np.around(train_perc * class_sizes))
if stratified:
print("Different classes in training set are stratified to match smalles... | python | {
"resource": ""
} |
q42825 | MultiDataset._load | train | def _load(self, dataset_spec):
"""Actual loading of datasets"""
for idx, ds in enumerate(dataset_spec):
self.append(ds, idx) | python | {
"resource": ""
} |
q42826 | MultiDataset.append | train | def append(self, dataset, identifier):
"""
Adds a dataset, if compatible with the existing ones.
Parameters
----------
dataset : MLDataset or compatible
identifier : hashable
String or integer or another hashable to uniquely identify this dataset
"... | python | {
"resource": ""
} |
q42827 | MultiDataset.holdout | train | def holdout(self,
train_perc=0.7,
num_rep=50,
stratified=True,
return_ids_only=False,
format='MLDataset'):
"""
Builds a generator for train and test sets for cross-validation.
"""
ids_in_class = {cid: self.... | python | {
"resource": ""
} |
q42828 | MultiDataset._get_data | train | def _get_data(self, id_list, format='MLDataset'):
"""Returns the data, from all modalities, for a given list of IDs"""
format = format.lower()
features = list() # returning a dict would be better if AutoMKL() can handle it
for modality, data in self._modalities.items():
if... | python | {
"resource": ""
} |
q42829 | ListCommand.can_be_updated | train | def can_be_updated(cls, dist, latest_version):
"""Determine whether package can be updated or not."""
scheme = get_scheme('default')
name = dist.project_name
dependants = cls.get_dependants(name)
for dependant in dependants:
requires = dependant.requires()
... | python | {
"resource": ""
} |
q42830 | ListCommand.get_dependants | train | def get_dependants(cls, dist):
"""Yield dependant user packages for a given package name."""
for package in cls.installed_distributions:
for requirement_package in package.requires():
requirement_name = requirement_package.project_name
# perform case-insensiti... | python | {
"resource": ""
} |
q42831 | ListCommand.get_requirement | train | def get_requirement(name, requires):
"""
Yield matching requirement strings.
The strings are presented in the format demanded by
pip._vendor.distlib.util.parse_requirement. Hopefully
I'll be able to figure out a better way to handle this
in the future. Perhaps figure out... | python | {
"resource": ""
} |
q42832 | ListCommand.output_package | train | def output_package(dist):
"""Return string displaying package information."""
if dist_is_editable(dist):
return '%s (%s, %s)' % (
dist.project_name,
dist.version,
dist.location,
)
return '%s (%s)' % (dist.project_name, dist.... | python | {
"resource": ""
} |
q42833 | ListCommand.run_outdated | train | def run_outdated(cls, options):
"""Print outdated user packages."""
latest_versions = sorted(
cls.find_packages_latest_versions(cls.options),
key=lambda p: p[0].project_name.lower())
for dist, latest_version, typ in latest_versions:
if latest_version > dist.p... | python | {
"resource": ""
} |
q42834 | softmax | train | def softmax(x):
"""Can be replaced once scipy 1.3 is released, although numeric stability should be checked."""
e_x = np.exp(x - np.max(x))
return e_x / e_x.sum(axis=1)[:, None] | python | {
"resource": ""
} |
q42835 | BaseBoosting.iter_predict | train | def iter_predict(self, X, include_init=False):
"""Returns the predictions for ``X`` at every stage of the boosting procedure.
Args:
X (array-like or sparse matrix of shape (n_samples, n_features): The input samples.
Sparse matrices are accepted only if they are supported by ... | python | {
"resource": ""
} |
q42836 | BaseBoosting.predict | train | def predict(self, X):
"""Returns the predictions for ``X``.
Under the hood this method simply goes through the outputs of ``iter_predict`` and returns
the final one.
Arguments:
X (array-like or sparse matrix of shape (n_samples, n_features)): The input samples.
... | python | {
"resource": ""
} |
q42837 | BoostingClassifier.iter_predict_proba | train | def iter_predict_proba(self, X, include_init=False):
"""Returns the predicted probabilities for ``X`` at every stage of the boosting procedure.
Arguments:
X (array-like or sparse matrix of shape (n_samples, n_features)): The input samples.
Sparse matrices are accepted only i... | python | {
"resource": ""
} |
q42838 | BoostingClassifier.iter_predict | train | def iter_predict(self, X, include_init=False):
"""Returns the predicted classes for ``X`` at every stage of the boosting procedure.
Arguments:
X (array-like or sparse matrix of shape (n_samples, n_features)): The input samples.
Sparse matrices are accepted only if they are s... | python | {
"resource": ""
} |
q42839 | BoostingClassifier.predict_proba | train | def predict_proba(self, X):
"""Returns the predicted probabilities for ``X``.
Arguments:
X (array-like or sparse matrix of shape (n_samples, n_features)): The input samples.
Sparse matrices are accepted only if they are supported by the weak model.
Returns:
... | python | {
"resource": ""
} |
q42840 | PandocAttributes.parse_pandoc | train | def parse_pandoc(self, attrs):
"""Read pandoc attributes."""
id = attrs[0]
classes = attrs[1]
kvs = OrderedDict(attrs[2])
return id, classes, kvs | python | {
"resource": ""
} |
q42841 | PandocAttributes.parse_markdown | train | def parse_markdown(self, attr_string):
"""Read markdown attributes."""
attr_string = attr_string.strip('{}')
splitter = re.compile(self.split_regex(separator=self.spnl))
attrs = splitter.split(attr_string)[1::2]
# match single word attributes e.g. ```python
if len(attrs)... | python | {
"resource": ""
} |
q42842 | PandocAttributes.parse_html | train | def parse_html(self, attr_string):
"""Read a html string to attributes."""
splitter = re.compile(self.split_regex(separator=self.spnl))
attrs = splitter.split(attr_string)[1::2]
idre = re.compile(r'''id=["']?([\w ]*)['"]?''')
clsre = re.compile(r'''class=["']?([\w ]*)['"]?''')
... | python | {
"resource": ""
} |
q42843 | PandocAttributes.parse_dict | train | def parse_dict(self, attrs):
"""Read a dict to attributes."""
attrs = attrs or {}
ident = attrs.get("id", "")
classes = attrs.get("classes", [])
kvs = OrderedDict((k, v) for k, v in attrs.items()
if k not in ("classes", "id"))
return ident, clas... | python | {
"resource": ""
} |
q42844 | PandocAttributes.to_markdown | train | def to_markdown(self, format='{id} {classes} {kvs}', surround=True):
"""Returns attributes formatted as markdown with optional
format argument to determine order of attribute contents.
"""
id = '#' + self.id if self.id else ''
classes = ' '.join('.' + cls for cls in self.classes)... | python | {
"resource": ""
} |
q42845 | PandocAttributes.to_html | train | def to_html(self):
"""Returns attributes formatted as html."""
id, classes, kvs = self.id, self.classes, self.kvs
id_str = 'id="{}"'.format(id) if id else ''
class_str = 'class="{}"'.format(' '.join(classes)) if classes else ''
key_str = ' '.join('{}={}'.format(k, v) for k, v in ... | python | {
"resource": ""
} |
q42846 | PandocAttributes.to_dict | train | def to_dict(self):
"""Returns attributes formatted as a dictionary."""
d = {'id': self.id, 'classes': self.classes}
d.update(self.kvs)
return d | python | {
"resource": ""
} |
q42847 | Rocket.from_socket | train | def from_socket(controller, host=None, port=None, track_path=None, log_level=logging.ERROR):
"""Create rocket instance using socket connector"""
rocket = Rocket(controller, track_path=track_path, log_level=log_level)
rocket.connector = SocketConnector(controller=controller,
... | python | {
"resource": ""
} |
q42848 | Rocket.value | train | def value(self, name):
"""get value of a track at the current time"""
return self.tracks.get(name).row_value(self.controller.row) | python | {
"resource": ""
} |
q42849 | compare_filesystems | train | def compare_filesystems(fs0, fs1, concurrent=False):
"""Compares the two given filesystems.
fs0 and fs1 are two mounted GuestFS instances
containing the two disks to be compared.
If the concurrent flag is True,
two processes will be used speeding up the comparison on multiple CPUs.
Returns a ... | python | {
"resource": ""
} |
q42850 | file_comparison | train | def file_comparison(files0, files1):
"""Compares two dictionaries of files returning their difference.
{'created_files': [<files in files1 and not in files0>],
'deleted_files': [<files in files0 and not in files1>],
'modified_files': [<files in both files0 and files1 but different>]}
... | python | {
"resource": ""
} |
q42851 | extract_files | train | def extract_files(filesystem, files, path):
"""Extracts requested files.
files must be a list of files in the format
{"C:\\Windows\\System32\\NTUSER.DAT": "sha1_hash"} for windows
{"/home/user/text.txt": "sha1_hash"} for other FS.
files will be extracted into path which must exist beforeh... | python | {
"resource": ""
} |
q42852 | registry_comparison | train | def registry_comparison(registry0, registry1):
"""Compares two dictionaries of registry keys returning their difference."""
comparison = {'created_keys': {},
'deleted_keys': [],
'created_values': {},
'deleted_values': {},
'modified_values':... | python | {
"resource": ""
} |
q42853 | compare_values | train | def compare_values(values0, values1):
"""Compares all the values of a single registry key."""
values0 = {v[0]: v[1:] for v in values0}
values1 = {v[0]: v[1:] for v in values1}
created = [(k, v[0], v[1]) for k, v in values1.items() if k not in values0]
deleted = [(k, v[0], v[1]) for k, v in values0.... | python | {
"resource": ""
} |
q42854 | compare_hives | train | def compare_hives(fs0, fs1):
"""Compares all the windows registry hive files
returning those which differ.
"""
registries = []
for path in chain(registries_path(fs0.fsroot), user_registries(fs0, fs1)):
if fs0.checksum(path) != fs1.checksum(path):
registries.append(path)
re... | python | {
"resource": ""
} |
q42855 | user_registries | train | def user_registries(fs0, fs1):
"""Returns the list of user registries present on both FileSystems."""
for user in fs0.ls('{}Users'.format(fs0.fsroot)):
for path in user_registries_path(fs0.fsroot, user):
if fs1.exists(path):
yield path | python | {
"resource": ""
} |
q42856 | files_type | train | def files_type(fs0, fs1, files):
"""Inspects the file type of the given files."""
for file_meta in files['deleted_files']:
file_meta['type'] = fs0.file(file_meta['path'])
for file_meta in files['created_files'] + files['modified_files']:
file_meta['type'] = fs1.file(file_meta['path'])
r... | python | {
"resource": ""
} |
q42857 | files_size | train | def files_size(fs0, fs1, files):
"""Gets the file size of the given files."""
for file_meta in files['deleted_files']:
file_meta['size'] = fs0.stat(file_meta['path'])['size']
for file_meta in files['created_files'] + files['modified_files']:
file_meta['size'] = fs1.stat(file_meta['path'])['s... | python | {
"resource": ""
} |
q42858 | parse_registries | train | def parse_registries(filesystem, registries):
"""Returns a dictionary with the content of the given registry hives.
{"\\Registry\\Key\\", (("ValueKey", "ValueType", ValueValue))}
"""
results = {}
for path in registries:
with NamedTemporaryFile(buffering=0) as tempfile:
filesys... | python | {
"resource": ""
} |
q42859 | makedirs | train | def makedirs(path):
"""Creates the directory tree if non existing."""
path = Path(path)
if not path.exists():
path.mkdir(parents=True) | python | {
"resource": ""
} |
q42860 | DiskComparator.compare | train | def compare(self, concurrent=False, identify=False, size=False):
"""Compares the two disks according to flags.
Generates the following report:
::
{'created_files': [{'path': '/file/in/disk1/not/in/disk0',
'sha1': 'sha1_of_the_file'}],
'... | python | {
"resource": ""
} |
q42861 | DiskComparator.extract | train | def extract(self, disk, files, path='.'):
"""Extracts the given files from the given disk.
Disk must be an integer (1 or 2) indicating from which of the two disks
to extract.
Files must be a list of dictionaries containing
the keys 'path' and 'sha1'.
Files will be extr... | python | {
"resource": ""
} |
q42862 | ComodoTLSService._create_error | train | def _create_error(self, status_code):
"""
Construct an error message in jsend format.
:param int status_code: The status code to translate into an error message
:return: A dictionary in jsend format with the error and the code
:rtype: dict
"""
return jsend.error... | python | {
"resource": ""
} |
q42863 | ComodoTLSService.get_cert_types | train | def get_cert_types(self):
"""
Collect the certificate types that are available to the customer.
:return: A list of dictionaries of certificate types
:rtype: list
"""
result = self.client.service.getCustomerCertTypes(authData=self.auth)
if result.statusCode == 0:... | python | {
"resource": ""
} |
q42864 | ComodoTLSService.collect | train | def collect(self, cert_id, format_type):
"""
Poll for certificate availability after submission.
:param int cert_id: The certificate ID
:param str format_type: The format type to use (example: 'X509 PEM Certificate only')
:return: The certificate_id or the certificate depending ... | python | {
"resource": ""
} |
q42865 | ComodoTLSService.submit | train | def submit(self, cert_type_name, csr, revoke_password, term, subject_alt_names='',
server_type='OTHER'):
"""
Submit a certificate request to Comodo.
:param string cert_type_name: The full cert type name (Example: 'PlatinumSSL Certificate') the supported
... | python | {
"resource": ""
} |
q42866 | L1Loss.gradient | train | def gradient(self, y_true, y_pred):
"""Returns the gradient of the L1 loss with respect to each prediction.
Example:
>>> import starboost as sb
>>> y_true = [0, 0, 1]
>>> y_pred = [0.3, 0, 0.8]
>>> sb.losses.L1Loss().gradient(y_true, y_pred)
a... | python | {
"resource": ""
} |
q42867 | get_parents | train | def get_parents():
"""Return sorted list of names of packages without dependants."""
distributions = get_installed_distributions(user_only=ENABLE_USER_SITE)
remaining = {d.project_name.lower() for d in distributions}
requirements = {r.project_name.lower() for d in distributions for
r... | python | {
"resource": ""
} |
q42868 | get_realnames | train | def get_realnames(packages):
"""
Return list of unique case-correct package names.
Packages are listed in a case-insensitive sorted order.
"""
return sorted({get_distribution(p).project_name for p in packages},
key=lambda n: n.lower()) | python | {
"resource": ""
} |
q42869 | OpenIdMixin.authenticate_redirect | train | def authenticate_redirect(self, callback_uri=None,
ask_for=["name", "email", "language", "username"]):
"""
Performs a redirect to the authentication URL for this service.
After authentication, the service will redirect back to the given
callback URI.
... | python | {
"resource": ""
} |
q42870 | GoogleAuth._on_auth | train | def _on_auth(self, user):
"""
This is called when login with OpenID succeeded and it's not
necessary to figure out if this is the users's first login or not.
"""
app = current_app._get_current_object()
if not user:
# Google auth failed.
login_error... | python | {
"resource": ""
} |
q42871 | GoogleAuth.required | train | def required(self, fn):
"""Request decorator. Forces authentication."""
@functools.wraps(fn)
def decorated(*args, **kwargs):
if (not self._check_auth()
# Don't try to force authentication if the request is part
# of the authentication process - otherwise... | python | {
"resource": ""
} |
q42872 | parse_journal_file | train | def parse_journal_file(journal_file):
"""Iterates over the journal's file taking care of paddings."""
counter = count()
for block in read_next_block(journal_file):
block = remove_nullchars(block)
while len(block) > MIN_RECORD_SIZE:
header = RECORD_HEADER.unpack_from(block)
... | python | {
"resource": ""
} |
q42873 | parse_record | train | def parse_record(header, record):
"""Parses a record according to its version."""
major_version = header[1]
try:
return RECORD_PARSER[major_version](header, record)
except (KeyError, struct.error) as error:
raise RuntimeError("Corrupted USN Record") from error | python | {
"resource": ""
} |
q42874 | usn_v2_record | train | def usn_v2_record(header, record):
"""Extracts USN V2 record information."""
length, major_version, minor_version = header
fields = V2_RECORD.unpack_from(record, RECORD_HEADER.size)
return UsnRecord(length,
float('{}.{}'.format(major_version, minor_version)),
f... | python | {
"resource": ""
} |
q42875 | usn_v4_record | train | def usn_v4_record(header, record):
"""Extracts USN V4 record information."""
length, major_version, minor_version = header
fields = V4_RECORD.unpack_from(record, RECORD_HEADER.size)
raise NotImplementedError('Not implemented') | python | {
"resource": ""
} |
q42876 | unpack_flags | train | def unpack_flags(value, flags):
"""Multiple flags might be packed in the same field."""
try:
return [flags[value]]
except KeyError:
return [flags[k] for k in sorted(flags.keys()) if k & value > 0] | python | {
"resource": ""
} |
q42877 | read_next_block | train | def read_next_block(infile, block_size=io.DEFAULT_BUFFER_SIZE):
"""Iterates over the file in blocks."""
chunk = infile.read(block_size)
while chunk:
yield chunk
chunk = infile.read(block_size) | python | {
"resource": ""
} |
q42878 | remove_nullchars | train | def remove_nullchars(block):
"""Strips NULL chars taking care of bytes alignment."""
data = block.lstrip(b'\00')
padding = b'\00' * ((len(block) - len(data)) % 8)
return padding + data | python | {
"resource": ""
} |
q42879 | timetopythonvalue | train | def timetopythonvalue(time_val):
"Convert a time or time range from ArcGIS REST server format to Python"
if isinstance(time_val, sequence):
return map(timetopythonvalue, time_val)
elif isinstance(time_val, numeric):
return datetime.datetime(*(time.gmtime(time_val))[:6])
elif isinstance(t... | python | {
"resource": ""
} |
q42880 | pythonvaluetotime | train | def pythonvaluetotime(time_val):
"Convert a time or time range from Python datetime to ArcGIS REST server"
if time_val is None:
return None
elif isinstance(time_val, numeric):
return str(long(time_val * 1000.0))
elif isinstance(time_val, date):
dtlist = [time_val.year, time_val.m... | python | {
"resource": ""
} |
q42881 | AnsibleInventory.get_hosts | train | def get_hosts(self, group=None):
'''
Get the hosts
'''
hostlist = []
if group:
groupobj = self.inventory.groups.get(group)
if not groupobj:
print "Group [%s] not found in inventory" % group
return None
groupdic... | python | {
"resource": ""
} |
q42882 | make_random_MLdataset | train | def make_random_MLdataset(max_num_classes = 20,
min_class_size = 20,
max_class_size = 50,
max_dim = 100,
stratified = True):
"Generates a random MLDataset for use in testing."
smallest = min(min_class_size, ... | python | {
"resource": ""
} |
q42883 | Observer.bindToEndPoint | train | def bindToEndPoint(self,bindingEndpoint):
"""
2-way binds the target endpoint to all other registered endpoints.
"""
self.bindings[bindingEndpoint.instanceId] = bindingEndpoint
bindingEndpoint.valueChangedSignal.connect(self._updateEndpoints) | python | {
"resource": ""
} |
q42884 | Observer._updateEndpoints | train | def _updateEndpoints(self,*args,**kwargs):
"""
Updates all endpoints except the one from which this slot was called.
Note: this method is probably not complete threadsafe. Maybe a lock is needed when setter self.ignoreEvents
"""
sender = self.sender()
if not self.ignore... | python | {
"resource": ""
} |
q42885 | HyperTransformer._anonymize_table | train | def _anonymize_table(cls, table_data, pii_fields):
"""Anonymize in `table_data` the fields in `pii_fields`.
Args:
table_data (pandas.DataFrame): Original dataframe/table.
pii_fields (list[dict]): Metadata for the fields to transform.
Result:
pandas.DataFrame... | python | {
"resource": ""
} |
q42886 | HyperTransformer._get_tables | train | def _get_tables(self, base_dir):
"""Load the contents of meta_file and the corresponding data.
If fields containing Personally Identifiable Information are detected in the metadata
they are anonymized before asign them into `table_dict`.
Args:
base_dir(str): Root folder of ... | python | {
"resource": ""
} |
q42887 | HyperTransformer._get_transformers | train | def _get_transformers(self):
"""Load the contents of meta_file and extract information about the transformers.
Returns:
dict: tuple(str, str) -> Transformer.
"""
transformer_dict = {}
for table in self.metadata['tables']:
table_name = table['name']
... | python | {
"resource": ""
} |
q42888 | HyperTransformer._fit_transform_column | train | def _fit_transform_column(self, table, metadata, transformer_name, table_name):
"""Transform a column from table using transformer and given parameters.
Args:
table (pandas.DataFrame): Dataframe containing column to transform.
metadata (dict): Metadata for given column.
... | python | {
"resource": ""
} |
q42889 | HyperTransformer._reverse_transform_column | train | def _reverse_transform_column(self, table, metadata, table_name):
"""Reverses the transformtion on a column from table using the given parameters.
Args:
table (pandas.DataFrame): Dataframe containing column to transform.
metadata (dict): Metadata for given column.
ta... | python | {
"resource": ""
} |
q42890 | HyperTransformer.fit_transform_table | train | def fit_transform_table(
self, table, table_meta, transformer_dict=None, transformer_list=None, missing=None):
"""Create, apply and store the specified transformers for `table`.
Args:
table(pandas.DataFrame): Contents of the table to be transformed.
table_meta(di... | python | {
"resource": ""
} |
q42891 | HyperTransformer.transform_table | train | def transform_table(self, table, table_meta, missing=None):
"""Apply the stored transformers to `table`.
Args:
table(pandas.DataFrame): Contents of the table to be transformed.
table_meta(dict): Metadata for the given table.
missing(bool): Wheter or not ... | python | {
"resource": ""
} |
q42892 | HyperTransformer.reverse_transform_table | train | def reverse_transform_table(self, table, table_meta, missing=None):
"""Transform a `table` back to its original format.
Args:
table(pandas.DataFrame): Contents of the table to be transformed.
table_meta(dict): Metadata for the given table.
missing(bool): ... | python | {
"resource": ""
} |
q42893 | HyperTransformer.fit_transform | train | def fit_transform(
self, tables=None, transformer_dict=None, transformer_list=None, missing=None):
"""Create, apply and store the specified transformers for the given tables.
Args:
tables(dict): Mapping of table names to `tuple` where each tuple is on the form
... | python | {
"resource": ""
} |
q42894 | HyperTransformer.transform | train | def transform(self, tables, table_metas=None, missing=None):
"""Apply all the saved transformers to `tables`.
Args:
tables(dict): mapping of table names to `tuple` where each tuple is on the form
(`pandas.DataFrame`, `dict`). The `DataFrame` contains the table ... | python | {
"resource": ""
} |
q42895 | HyperTransformer.reverse_transform | train | def reverse_transform(self, tables, table_metas=None, missing=None):
"""Transform data back to its original format.
Args:
tables(dict): mapping of table names to `tuple` where each tuple is on the form
(`pandas.DataFrame`, `dict`). The `DataFrame` contains the ... | python | {
"resource": ""
} |
q42896 | echo | train | def echo(msg, *args, **kwargs):
'''Wraps click.echo, handles formatting and check encoding'''
file = kwargs.pop('file', None)
nl = kwargs.pop('nl', True)
err = kwargs.pop('err', False)
color = kwargs.pop('color', None)
msg = safe_unicode(msg).format(*args, **kwargs)
click.echo(msg, file=file... | python | {
"resource": ""
} |
q42897 | warning | train | def warning(msg, *args, **kwargs):
'''Display a warning message'''
msg = '{0} {1}'.format(yellow(WARNING), msg)
echo(msg, *args, **kwargs) | python | {
"resource": ""
} |
q42898 | error | train | def error(msg, details=None, *args, **kwargs):
'''Display an error message with optionnal details'''
msg = '{0} {1}'.format(red(KO), white(msg))
if details:
msg = '\n'.join((msg, safe_unicode(details)))
echo(format_multiline(msg), *args, **kwargs) | python | {
"resource": ""
} |
q42899 | load | train | def load(patterns, full_reindex):
'''
Load one or more CADA CSV files matching patterns
'''
header('Loading CSV files')
for pattern in patterns:
for filename in iglob(pattern):
echo('Loading {}'.format(white(filename)))
with open(filename) as f:
reader... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.