_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q263400 | PyMataCommandHandler._string_data | validation | def _string_data(self, data):
"""
This method handles the incoming string data message from Firmata.
The string is printed to the console
:param data: Message data from Firmata
:return: No return value.s
"""
print("_string_data:")
string_to_print = []
... | python | {
"resource": ""
} |
q263401 | PyMataCommandHandler.run | validation | def run(self):
"""
This method starts the thread that continuously runs to receive and interpret
messages coming from Firmata. This must be the last method in this file
It also checks the deque for messages to be sent to Firmata.
"""
# To add a command to the command disp... | python | {
"resource": ""
} |
q263402 | Haul.retrieve_url | validation | def retrieve_url(self, url):
"""
Use requests to fetch remote content
"""
try:
r = requests.get(url)
except requests.ConnectionError:
raise exceptions.RetrieveError('Connection fail')
if r.status_code >= 400:
raise exceptions.Retrieve... | python | {
"resource": ""
} |
q263403 | HaulResult.image_urls | validation | def image_urls(self):
"""
Combine finder_image_urls and extender_image_urls,
remove duplicate but keep order
"""
all_image_urls = self.finder_image_urls[:]
for image_url in self.extender_image_urls:
if image_url not in all_image_urls:
all_imag... | python | {
"resource": ""
} |
q263404 | background_image_finder | validation | def background_image_finder(pipeline_index,
soup,
finder_image_urls=[],
*args, **kwargs):
"""
Find image URL in background-image
Example:
<div style="width: 100%; height: 100%; background-image: url(http://distilleryima... | python | {
"resource": ""
} |
q263405 | StrictRedisCluster._getnodenamefor | validation | def _getnodenamefor(self, name):
"Return the node name where the ``name`` would land to"
return 'node_' + str(
(abs(binascii.crc32(b(name)) & 0xffffffff) % self.no_servers) + 1) | python | {
"resource": ""
} |
q263406 | StrictRedisCluster.getnodefor | validation | def getnodefor(self, name):
"Return the node where the ``name`` would land to"
node = self._getnodenamefor(name)
return {node: self.cluster['nodes'][node]} | python | {
"resource": ""
} |
q263407 | StrictRedisCluster.object | validation | def object(self, infotype, key):
"Return the encoding, idletime, or refcount about the key"
redisent = self.redises[self._getnodenamefor(key) + '_slave']
return getattr(redisent, 'object')(infotype, key) | python | {
"resource": ""
} |
q263408 | StrictRedisCluster._rc_brpoplpush | validation | def _rc_brpoplpush(self, src, dst, timeout=0):
"""
Pop a value off the tail of ``src``, push it on the head of ``dst``
and then return it.
This command blocks until a value is in ``src`` or until ``timeout``
seconds elapse, whichever is first. A ``timeout`` value of 0 blocks
... | python | {
"resource": ""
} |
q263409 | StrictRedisCluster._rc_rpoplpush | validation | def _rc_rpoplpush(self, src, dst):
"""
RPOP a value off of the ``src`` list and LPUSH it
on to the ``dst`` list. Returns the value.
"""
rpop = self.rpop(src)
if rpop is not None:
self.lpush(dst, rpop)
return rpop
return None | python | {
"resource": ""
} |
q263410 | StrictRedisCluster._rc_smove | validation | def _rc_smove(self, src, dst, value):
"""
Move ``value`` from set ``src`` to set ``dst``
not atomic
"""
if self.type(src) != b("set"):
return self.smove(src + "{" + src + "}", dst, value)
if self.type(dst) != b("set"):
return self.smove(dst + "{" +... | python | {
"resource": ""
} |
q263411 | StrictRedisCluster._rc_sunion | validation | def _rc_sunion(self, src, *args):
"""
Returns the members of the set resulting from the union between
the first set and all the successive sets.
"""
args = list_or_args(src, args)
src_set = self.smembers(args.pop(0))
if src_set is not set([]):
for key ... | python | {
"resource": ""
} |
q263412 | StrictRedisCluster._rc_sunionstore | validation | def _rc_sunionstore(self, dst, src, *args):
"""
Store the union of sets ``src``, ``args`` into a new
set named ``dest``. Returns the number of keys in the new set.
"""
args = list_or_args(src, args)
result = self.sunion(*args)
if result is not set([]):
... | python | {
"resource": ""
} |
q263413 | StrictRedisCluster._rc_msetnx | validation | def _rc_msetnx(self, mapping):
"""
Sets each key in the ``mapping`` dict to its corresponding value if
none of the keys are already set
"""
for k in iterkeys(mapping):
if self.exists(k):
return False
return self._rc_mset(mapping) | python | {
"resource": ""
} |
q263414 | StrictRedisCluster._rc_rename | validation | def _rc_rename(self, src, dst):
"""
Rename key ``src`` to ``dst``
"""
if src == dst:
return self.rename(src + "{" + src + "}", src)
if not self.exists(src):
return self.rename(src + "{" + src + "}", src)
self.delete(dst)
ktype = self.type(... | python | {
"resource": ""
} |
q263415 | StrictRedisCluster._rc_renamenx | validation | def _rc_renamenx(self, src, dst):
"Rename key ``src`` to ``dst`` if ``dst`` doesn't already exist"
if self.exists(dst):
return False
return self._rc_rename(src, dst) | python | {
"resource": ""
} |
q263416 | StrictRedisCluster._rc_keys | validation | def _rc_keys(self, pattern='*'):
"Returns a list of keys matching ``pattern``"
result = []
for alias, redisent in iteritems(self.redises):
if alias.find('_slave') == -1:
continue
result.extend(redisent.keys(pattern))
return result | python | {
"resource": ""
} |
q263417 | StrictRedisCluster._rc_dbsize | validation | def _rc_dbsize(self):
"Returns the number of keys in the current database"
result = 0
for alias, redisent in iteritems(self.redises):
if alias.find('_slave') == -1:
continue
result += redisent.dbsize()
return result | python | {
"resource": ""
} |
q263418 | Base.prepare | validation | def prepare(self):
"""Prepare the date in the instance state for serialization.
"""
# Create a collection for the attributes and elements of
# this instance.
attributes, elements = OrderedDict(), []
# Initialize the namespace map.
nsmap = dict([self.meta.namespa... | python | {
"resource": ""
} |
q263419 | verify | validation | def verify(xml, stream):
"""
Verify the signaure of an XML document with the given certificate.
Returns `True` if the document is signed with a valid signature.
Returns `False` if the document is not signed or if the signature is
invalid.
:param lxml.etree._Element xml: The document to sign
... | python | {
"resource": ""
} |
q263420 | GalleryAdmin.get_queryset | validation | def get_queryset(self, request):
"""
Add number of photos to each gallery.
"""
qs = super(GalleryAdmin, self).get_queryset(request)
return qs.annotate(photo_count=Count('photos')) | python | {
"resource": ""
} |
q263421 | GalleryAdmin.save_model | validation | def save_model(self, request, obj, form, change):
"""
Set currently authenticated user as the author of the gallery.
"""
obj.author = request.user
obj.save() | python | {
"resource": ""
} |
q263422 | GalleryAdmin.save_formset | validation | def save_formset(self, request, form, formset, change):
"""
For each photo set it's author to currently authenticated user.
"""
instances = formset.save(commit=False)
for instance in instances:
if isinstance(instance, Photo):
instance.author = request.... | python | {
"resource": ""
} |
q263423 | Ranges.parse_byteranges | validation | def parse_byteranges(cls, environ):
"""
Outputs a list of tuples with ranges or the empty list
According to the rfc, start or end values can be omitted
"""
r = []
s = environ.get(cls.header_range, '').replace(' ','').lower()
if s:
l = s.split('=')
... | python | {
"resource": ""
} |
q263424 | Ranges.check_ranges | validation | def check_ranges(cls, ranges, length):
"""Removes errored ranges"""
result = []
for start, end in ranges:
if isinstance(start, int) or isinstance(end, int):
if isinstance(start, int) and not (0 <= start < length):
continue
elif isin... | python | {
"resource": ""
} |
q263425 | Ranges.convert_ranges | validation | def convert_ranges(cls, ranges, length):
"""Converts to valid byte ranges"""
result = []
for start, end in ranges:
if end is None:
result.append( (start, length-1) )
elif start is None:
s = length - end
result.append( (0 if ... | python | {
"resource": ""
} |
q263426 | Ranges.condense_ranges | validation | def condense_ranges(cls, ranges):
"""Sorts and removes overlaps"""
result = []
if ranges:
ranges.sort(key=lambda tup: tup[0])
result.append(ranges[0])
for i in range(1, len(ranges)):
if result[-1][1] + 1 >= ranges[i][0]:
res... | python | {
"resource": ""
} |
q263427 | social_widget_render | validation | def social_widget_render(parser, token):
""" Renders the selected social widget. You can specify optional settings
that will be passed to widget template.
Sample usage:
{% social_widget_render widget_template ke1=val1 key2=val2 %}
For example to render Twitter follow button you can use code like ... | python | {
"resource": ""
} |
q263428 | Sparse3DMatrix.add | validation | def add(self, addend_mat, axis=1):
"""
In-place addition
:param addend_mat: A matrix to be added on the Sparse3DMatrix object
:param axis: The dimension along the addend_mat is added
:return: Nothing (as it performs in-place operations)
"""
if self.finalized:
... | python | {
"resource": ""
} |
q263429 | Sparse3DMatrix.multiply | validation | def multiply(self, multiplier, axis=None):
"""
In-place multiplication
:param multiplier: A matrix or vector to be multiplied
:param axis: The dim along which 'multiplier' is multiplied
:return: Nothing (as it performs in-place operations)
"""
if self.finalized:
... | python | {
"resource": ""
} |
q263430 | EMfactory.update_probability_at_read_level | validation | def update_probability_at_read_level(self, model=3):
"""
Updates the probability of read origin at read level
:param model: Normalization model (1: Gene->Allele->Isoform, 2: Gene->Isoform->Allele, 3: Gene->Isoform*Allele, 4: Gene*Isoform*Allele)
:return: Nothing (as it performs in-place... | python | {
"resource": ""
} |
q263431 | EMfactory.run | validation | def run(self, model, tol=0.001, max_iters=999, verbose=True):
"""
Runs EM iterations
:param model: Normalization model (1: Gene->Allele->Isoform, 2: Gene->Isoform->Allele, 3: Gene->Isoform*Allele, 4: Gene*Isoform*Allele)
:param tol: Tolerance for termination
:param max_iters: Ma... | python | {
"resource": ""
} |
q263432 | EMfactory.report_read_counts | validation | def report_read_counts(self, filename, grp_wise=False, reorder='as-is', notes=None):
"""
Exports expected read counts
:param filename: File name for output
:param grp_wise: whether the report is at isoform level or gene level
:param reorder: whether the report should be either '... | python | {
"resource": ""
} |
q263433 | EMfactory.report_depths | validation | def report_depths(self, filename, tpm=True, grp_wise=False, reorder='as-is', notes=None):
"""
Exports expected depths
:param filename: File name for output
:param grp_wise: whether the report is at isoform level or gene level
:param reorder: whether the report should be either '... | python | {
"resource": ""
} |
q263434 | EMfactory.export_posterior_probability | validation | def export_posterior_probability(self, filename, title="Posterior Probability"):
"""
Writes the posterior probability of read origin
:param filename: File name for output
:param title: The title of the posterior probability matrix
:return: Nothing but the method writes a file in... | python | {
"resource": ""
} |
q263435 | AlignmentPropertyMatrix.print_read | validation | def print_read(self, rid):
"""
Prints nonzero rows of the read wanted
"""
if self.rname is not None:
print self.rname[rid]
print '--'
r = self.get_read_data(rid)
aligned_loci = np.unique(r.nonzero()[1])
for locus in aligned_loci:... | python | {
"resource": ""
} |
q263436 | _roman | validation | def _roman(data, scheme_map, **kw):
"""Transliterate `data` with the given `scheme_map`. This function is used
when the source scheme is a Roman scheme.
:param data: the data to transliterate
:param scheme_map: a dict that maps between characters in the old scheme
and characters in the new... | python | {
"resource": ""
} |
q263437 | _brahmic | validation | def _brahmic(data, scheme_map, **kw):
"""Transliterate `data` with the given `scheme_map`. This function is used
when the source scheme is a Brahmic scheme.
:param data: the data to transliterate
:param scheme_map: a dict that maps between characters in the old scheme
and characters in the... | python | {
"resource": ""
} |
q263438 | detect | validation | def detect(text):
"""Detect the input's transliteration scheme.
:param text: some text data, either a `unicode` or a `str` encoded
in UTF-8.
"""
if sys.version_info < (3, 0):
# Verify encoding
try:
text = text.decode('utf-8')
except UnicodeError:
pass
# Brahmic s... | python | {
"resource": ""
} |
q263439 | _setup | validation | def _setup():
"""Add a variety of default schemes."""
s = str.split
if sys.version_info < (3, 0):
# noinspection PyUnresolvedReferences
s = unicode.split
def pop_all(some_dict, some_list):
for scheme in some_list:
some_dict.pop(scheme)
global SCHEMES
... | python | {
"resource": ""
} |
q263440 | to_utf8 | validation | def to_utf8(y):
"""
converts an array of integers to utf8 string
"""
out = []
for x in y:
if x < 0x080:
out.append(x)
elif x < 0x0800:
out.append((x >> 6) | 0xC0)
out.append((x & 0x3F) | 0x80)
elif x < 0x10000:
out.append((x ... | python | {
"resource": ""
} |
q263441 | Parser.set_script | validation | def set_script(self, i):
"""
set the value of delta to reflect the current codepage
"""
if i in range(1, 10):
n = i - 1
else:
raise IllegalInput("Invalid Value for ATR %s" % (hex(i)))
if n > -1: # n = -1 is the default script ..
... | python | {
"resource": ""
} |
q263442 | _unrecognised | validation | def _unrecognised(chr):
""" Handle unrecognised characters. """
if options['handleUnrecognised'] == UNRECOGNISED_ECHO:
return chr
elif options['handleUnrecognised'] == UNRECOGNISED_SUBSTITUTE:
return options['substituteChar']
else:
raise (KeyError, chr) | python | {
"resource": ""
} |
q263443 | DevanagariCharacterBlock._equivalent | validation | def _equivalent(self, char, prev, next, implicitA):
""" Transliterate a Latin character equivalent to Devanagari.
Add VIRAMA for ligatures.
Convert standalone to dependent vowels.
"""
result = []
if char.isVowel == False:
result.append(char.c... | python | {
"resource": ""
} |
q263444 | Scheme.from_devanagari | validation | def from_devanagari(self, data):
"""A convenience method"""
from indic_transliteration import sanscript
return sanscript.transliterate(data=data, _from=sanscript.DEVANAGARI, _to=self.name) | python | {
"resource": ""
} |
q263445 | generate | validation | def generate(grammar=None, num=1, output=sys.stdout, max_recursion=10, seed=None):
"""Load and generate ``num`` number of top-level rules from the specified grammar.
:param list grammar: The grammar file to load and generate data from
:param int num: The number of times to generate data
:param output: ... | python | {
"resource": ""
} |
q263446 | Q.build | validation | def build(self, pre=None, shortest=False):
"""Build the ``Quote`` instance
:param list pre: The prerequisites list
:param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated.
"""
res = super(Q, self).build(pre, short... | python | {
"resource": ""
} |
q263447 | make_present_participles | validation | def make_present_participles(verbs):
"""Make the list of verbs into present participles
E.g.:
empower -> empowering
drive -> driving
"""
res = []
for verb in verbs:
parts = verb.split()
if parts[0].endswith("e"):
parts[0] = parts[0][:-1] + "ing"
... | python | {
"resource": ""
} |
q263448 | MailerMessageManager.clear_sent_messages | validation | def clear_sent_messages(self, offset=None):
""" Deletes sent MailerMessage records """
if offset is None:
offset = getattr(settings, 'MAILQUEUE_CLEAR_OFFSET', defaults.MAILQUEUE_CLEAR_OFFSET)
if type(offset) is int:
offset = datetime.timedelta(hours=offset)
dele... | python | {
"resource": ""
} |
q263449 | _loadNamelistIncludes | validation | def _loadNamelistIncludes(item, unique_glyphs, cache):
"""Load the includes of an encoding Namelist files.
This is an implementation detail of readNamelist.
"""
includes = item["includes"] = []
charset = item["charset"] = set() | item["ownCharset"]
noCharcode = item["noCharcode"] = set() | item["ownNoChar... | python | {
"resource": ""
} |
q263450 | __readNamelist | validation | def __readNamelist(cache, filename, unique_glyphs):
"""Return a dict with the data of an encoding Namelist file.
This is an implementation detail of readNamelist.
"""
if filename in cache:
item = cache[filename]
else:
cps, header, noncodes = parseNamelist(filename)
item = {
"fileName": file... | python | {
"resource": ""
} |
q263451 | _readNamelist | validation | def _readNamelist(currentlyIncluding, cache, namFilename, unique_glyphs):
""" Detect infinite recursion and prevent it.
This is an implementation detail of readNamelist.
Raises NamelistRecursionError if namFilename is in the process of being included
"""
# normalize
filename = os.path.abspath(os.path.norm... | python | {
"resource": ""
} |
q263452 | codepointsInNamelist | validation | def codepointsInNamelist(namFilename, unique_glyphs=False, cache=None):
"""Returns the set of codepoints contained in a given Namelist file.
This is a replacement CodepointsInSubset and implements the "#$ include"
header format.
Args:
namFilename: The path to the Namelist file.
unique_glyphs: Optiona... | python | {
"resource": ""
} |
q263453 | TTFont.get_orthographies | validation | def get_orthographies(self, _library=library):
''' Returns list of CharsetInfo about supported orthographies '''
results = []
for charset in _library.charsets:
if self._charsets:
cn = getattr(charset, 'common_name', False)
abbr = getattr(charset, 'abbr... | python | {
"resource": ""
} |
q263454 | BaseOAuth.generate_oauth2_headers | validation | def generate_oauth2_headers(self):
"""Generates header for oauth2
"""
encoded_credentials = base64.b64encode(('{0}:{1}'.format(self.consumer_key,self.consumer_secret)).encode('utf-8'))
headers={
'Authorization':'Basic {0}'.format(encoded_credentials.decode('utf-8')),
... | python | {
"resource": ""
} |
q263455 | BaseOAuth.oauth2_access_parser | validation | def oauth2_access_parser(self, raw_access):
"""Parse oauth2 access
"""
parsed_access = json.loads(raw_access.content.decode('utf-8'))
self.access_token = parsed_access['access_token']
self.token_type = parsed_access['token_type']
self.refresh_token = parsed_access['refres... | python | {
"resource": ""
} |
q263456 | BaseOAuth.refresh_access_token | validation | def refresh_access_token(self,):
"""Refresh access token
"""
logger.debug("REFRESHING TOKEN")
self.token_time = time.time()
credentials = {
'token_time': self.token_time
}
if self.oauth_version == 'oauth1':
self.access_token, self.access_t... | python | {
"resource": ""
} |
q263457 | get_data | validation | def get_data(filename):
"""Calls right function according to file extension
"""
name, ext = get_file_extension(filename)
func = json_get_data if ext == '.json' else yaml_get_data
return func(filename) | python | {
"resource": ""
} |
q263458 | write_data | validation | def write_data(data, filename):
"""Call right func to save data according to file extension
"""
name, ext = get_file_extension(filename)
func = json_write_data if ext == '.json' else yaml_write_data
return func(data, filename) | python | {
"resource": ""
} |
q263459 | json_write_data | validation | def json_write_data(json_data, filename):
"""Write json data into a file
"""
with open(filename, 'w') as fp:
json.dump(json_data, fp, indent=4, sort_keys=True, ensure_ascii=False)
return True
return False | python | {
"resource": ""
} |
q263460 | json_get_data | validation | def json_get_data(filename):
"""Get data from json file
"""
with open(filename) as fp:
json_data = json.load(fp)
return json_data
return False | python | {
"resource": ""
} |
q263461 | yaml_get_data | validation | def yaml_get_data(filename):
"""Get data from .yml file
"""
with open(filename, 'rb') as fd:
yaml_data = yaml.load(fd)
return yaml_data
return False | python | {
"resource": ""
} |
q263462 | yaml_write_data | validation | def yaml_write_data(yaml_data, filename):
"""Write data into a .yml file
"""
with open(filename, 'w') as fd:
yaml.dump(yaml_data, fd, default_flow_style=False)
return True
return False | python | {
"resource": ""
} |
q263463 | RBFize.transform | validation | def transform(self, X):
'''
Turns distances into RBF values.
Parameters
----------
X : array
The raw pairwise distances.
Returns
-------
X_rbf : array of same shape as X
The distances in X passed through the RBF kernel.
''... | python | {
"resource": ""
} |
q263464 | ProjectPSD.fit | validation | def fit(self, X, y=None):
'''
Learn the linear transformation to clipped eigenvalues.
Note that if min_eig isn't zero and any of the original eigenvalues
were exactly zero, this will leave those eigenvalues as zero.
Parameters
----------
X : array, shape [n, n]
... | python | {
"resource": ""
} |
q263465 | FlipPSD.fit | validation | def fit(self, X, y=None):
'''
Learn the linear transformation to flipped eigenvalues.
Parameters
----------
X : array, shape [n, n]
The *symmetric* input similarities. If X is asymmetric, it will be
treated as if it were symmetric based on its lower-trian... | python | {
"resource": ""
} |
q263466 | FlipPSD.transform | validation | def transform(self, X):
'''
Transforms X according to the linear transformation corresponding to
flipping the input eigenvalues.
Parameters
----------
X : array, shape [n_test, n]
The test similarities to training points.
Returns
-------
... | python | {
"resource": ""
} |
q263467 | FlipPSD.fit_transform | validation | def fit_transform(self, X, y=None):
'''
Flips the negative eigenvalues of X.
Parameters
----------
X : array, shape [n, n]
The *symmetric* input similarities. If X is asymmetric, it will be
treated as if it were symmetric based on its lower-triangular par... | python | {
"resource": ""
} |
q263468 | ShiftPSD.fit | validation | def fit(self, X, y=None):
'''
Learn the transformation to shifted eigenvalues. Only depends
on the input dimension.
Parameters
----------
X : array, shape [n, n]
The *symmetric* input similarities.
'''
n = X.shape[0]
if X.shape != (n, ... | python | {
"resource": ""
} |
q263469 | ShiftPSD.transform | validation | def transform(self, X):
'''
Transforms X according to the linear transformation corresponding to
shifting the input eigenvalues to all be at least ``self.min_eig``.
Parameters
----------
X : array, shape [n_test, n]
The test similarities to training points.
... | python | {
"resource": ""
} |
q263470 | L2DensityTransformer.fit | validation | def fit(self, X, y=None):
'''
Picks the elements of the basis to use for the given data.
Only depends on the dimension of X. If it's more convenient, you can
pass a single integer for X, which is the dimension to use.
Parameters
----------
X : an integer, a :cla... | python | {
"resource": ""
} |
q263471 | L2DensityTransformer.transform | validation | def transform(self, X):
'''
Transform a list of bag features into its projection series
representation.
Parameters
----------
X : :class:`skl_groups.features.Features` or list of bag feature arrays
New data to transform. The data should all lie in [0, 1];
... | python | {
"resource": ""
} |
q263472 | VersiontoolsEnchancedDistributionMetadata.get_version | validation | def get_version(self):
"""
Get distribution version.
This method is enhanced compared to original distutils implementation.
If the version string is set to a special value then instead of using
the actual value the real version is obtained by querying versiontools.
If ... | python | {
"resource": ""
} |
q263473 | VersiontoolsEnchancedDistributionMetadata.__get_live_version | validation | def __get_live_version(self):
"""
Get a live version string using versiontools
"""
try:
import versiontools
except ImportError:
return None
else:
return str(versiontools.Version.from_expression(self.name)) | python | {
"resource": ""
} |
q263474 | BagPreprocesser.fit | validation | def fit(self, X, y=None, **params):
'''
Fit the transformer on the stacked points.
Parameters
----------
X : :class:`Features` or list of arrays of shape ``[n_samples[i], n_features]``
Training set. If a Features object, it will be stacked.
any other keyword... | python | {
"resource": ""
} |
q263475 | BagPreprocesser.transform | validation | def transform(self, X, **params):
'''
Transform the stacked points.
Parameters
----------
X : :class:`Features` or list of bag feature arrays
New data to transform.
any other keyword argument :
Passed on as keyword arguments to the transformer's ... | python | {
"resource": ""
} |
q263476 | BagPreprocesser.fit_transform | validation | def fit_transform(self, X, y=None, **params):
'''
Fit and transform the stacked points.
Parameters
----------
X : :class:`Features` or list of bag feature arrays
Data to train on and transform.
any other keyword argument :
Passed on as keyword ar... | python | {
"resource": ""
} |
q263477 | MinMaxScaler.fit | validation | def fit(self, X, y=None):
"""Compute the minimum and maximum to be used for later scaling.
Parameters
----------
X : array-like, shape [n_samples, n_features]
The data used to compute the per-feature minimum and maximum
used for later scaling along the features a... | python | {
"resource": ""
} |
q263478 | MinMaxScaler.transform | validation | def transform(self, X):
"""Scaling features of X according to feature_range.
Parameters
----------
X : array-like with shape [n_samples, n_features]
Input data that will be transformed.
"""
X = check_array(X, copy=self.copy)
X *= self.scale_
X... | python | {
"resource": ""
} |
q263479 | MinMaxScaler.inverse_transform | validation | def inverse_transform(self, X):
"""Undo the scaling of X according to feature_range.
Note that if truncate is true, any truncated points will not
be restored exactly.
Parameters
----------
X : array-like with shape [n_samples, n_features]
Input data that wil... | python | {
"resource": ""
} |
q263480 | BagOfWords.fit | validation | def fit(self, X, y=None):
'''
Choose the codewords based on a training set.
Parameters
----------
X : :class:`skl_groups.features.Features` or list of arrays of shape ``[n_samples[i], n_features]``
Training set. If a Features object, it will be stacked.
'''
... | python | {
"resource": ""
} |
q263481 | BagOfWords.transform | validation | def transform(self, X):
'''
Transform a list of bag features into its bag-of-words representation.
Parameters
----------
X : :class:`skl_groups.features.Features` or list of bag feature arrays
New data to transform.
Returns
-------
X_new : in... | python | {
"resource": ""
} |
q263482 | is_categorical_type | validation | def is_categorical_type(ary):
"Checks whether the array is either integral or boolean."
ary = np.asanyarray(ary)
return is_integer_type(ary) or ary.dtype.kind == 'b' | python | {
"resource": ""
} |
q263483 | as_integer_type | validation | def as_integer_type(ary):
'''
Returns argument as an integer array, converting floats if convertable.
Raises ValueError if it's a float array with nonintegral values.
'''
ary = np.asanyarray(ary)
if is_integer_type(ary):
return ary
rounded = np.rint(ary)
if np.any(rounded != ary)... | python | {
"resource": ""
} |
q263484 | ProgressLogger.start | validation | def start(self, total):
'''
Signal the start of the process.
Parameters
----------
total : int
The total number of steps in the process, or None if unknown.
'''
self.logger.info(json.dumps(['START', self.name, total])) | python | {
"resource": ""
} |
q263485 | _build_indices | validation | def _build_indices(X, flann_args):
"Builds FLANN indices for each bag."
# TODO: should probably multithread this
logger.info("Building indices...")
indices = [None] * len(X)
for i, bag in enumerate(plog(X, name="index building")):
indices[i] = idx = FLANNIndex(**flann_args)
idx.build... | python | {
"resource": ""
} |
q263486 | _get_rhos | validation | def _get_rhos(X, indices, Ks, max_K, save_all_Ks, min_dist):
"Gets within-bag distances for each bag."
logger.info("Getting within-bag distances...")
if max_K >= X.n_pts.min():
msg = "asked for K = {}, but there's a bag with only {} points"
raise ValueError(msg.format(max_K, X.n_pts.min()))... | python | {
"resource": ""
} |
q263487 | linear | validation | def linear(Ks, dim, num_q, rhos, nus):
r'''
Estimates the linear inner product \int p q between two distributions,
based on kNN distances.
'''
return _get_linear(Ks, dim)(num_q, rhos, nus) | python | {
"resource": ""
} |
q263488 | quadratic | validation | def quadratic(Ks, dim, rhos, required=None):
r'''
Estimates \int p^2 based on kNN distances.
In here because it's used in the l2 distance, above.
Returns array of shape (num_Ks,).
'''
# Estimated with alpha=1, beta=0:
# B_{k,d,1,0} is the same as B_{k,d,0,1} in linear()
# and the ful... | python | {
"resource": ""
} |
q263489 | topological_sort | validation | def topological_sort(deps):
'''
Topologically sort a DAG, represented by a dict of child => set of parents.
The dependency dict is destroyed during operation.
Uses the Kahn algorithm: http://en.wikipedia.org/wiki/Topological_sorting
Not a particularly good implementation, but we're just running it ... | python | {
"resource": ""
} |
q263490 | KNNDivergenceEstimator._get_Ks | validation | def _get_Ks(self):
"Ks as an array and type-checked."
Ks = as_integer_type(self.Ks)
if Ks.ndim != 1:
raise TypeError("Ks should be 1-dim, got shape {}".format(Ks.shape))
if Ks.min() < 1:
raise ValueError("Ks should be positive; got {}".format(Ks.min()))
re... | python | {
"resource": ""
} |
q263491 | KNNDivergenceEstimator._flann_args | validation | def _flann_args(self, X=None):
"The dictionary of arguments to give to FLANN."
args = {'cores': self._n_jobs}
if self.flann_algorithm == 'auto':
if X is None or X.dim > 5:
args['algorithm'] = 'linear'
else:
args['algorithm'] = 'kdtree_singl... | python | {
"resource": ""
} |
q263492 | KNNDivergenceEstimator.fit | validation | def fit(self, X, y=None, get_rhos=False):
'''
Sets up for divergence estimation "from" new data "to" X.
Builds FLANN indices for each bag, and maybe gets within-bag distances.
Parameters
----------
X : list of arrays or :class:`skl_groups.features.Features`
T... | python | {
"resource": ""
} |
q263493 | Features.make_stacked | validation | def make_stacked(self):
"If unstacked, convert to stacked. If stacked, do nothing."
if self.stacked:
return
self._boundaries = bounds = np.r_[0, np.cumsum(self.n_pts)]
self.stacked_features = stacked = np.vstack(self.features)
self.features = np.array(
[s... | python | {
"resource": ""
} |
q263494 | Features.copy | validation | def copy(self, stack=False, copy_meta=False, memo=None):
'''
Copies the Feature object. Makes a copy of the features array.
Parameters
----------
stack : boolean, optional, default False
Whether to stack the copy if this one is unstacked.
copy_meta : boolean... | python | {
"resource": ""
} |
q263495 | Features.bare | validation | def bare(self):
"Make a Features object with no metadata; points to the same features."
if not self.meta:
return self
elif self.stacked:
return Features(self.stacked_features, self.n_pts, copy=False)
else:
return Features(self.features, copy=False) | python | {
"resource": ""
} |
q263496 | MeanMapKernel.fit | validation | def fit(self, X, y=None):
'''
Specify the data to which kernel values should be computed.
Parameters
----------
X : list of arrays or :class:`skl_groups.features.Features`
The bags to compute "to".
'''
self.features_ = as_features(X, stack=True, bare=... | python | {
"resource": ""
} |
q263497 | BagMean.transform | validation | def transform(self, X):
'''
Transform a list of bag features into a matrix of its mean features.
Parameters
----------
X : :class:`skl_groups.features.Features` or list of bag feature arrays
Data to transform.
Returns
-------
X_new : array, s... | python | {
"resource": ""
} |
q263498 | Client.run | validation | def run(self):
"""Start listening to the server"""
logger.info(u'Started listening')
while not self._stop:
xml = self._readxml()
# Exit on invalid XML
if xml is None:
break
# Raw xml only
if not self.modelize:
... | python | {
"resource": ""
} |
q263499 | Client.connect | validation | def connect(self):
"""Connect to the server
:raise ConnectionError: If socket cannot establish a connection
"""
try:
logger.info(u'Connecting %s:%d' % (self.host, self.port))
self.sock.connect((self.host, self.port))
except socket.error:
rais... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.