function stringlengths 11 56k | repo_name stringlengths 5 60 | features list |
|---|---|---|
def simple_trace_to_wkt_linestring(trace):
'''
Coverts a simple fault trace to well-known text format
:param trace:
Fault trace as instance of :class: openquake.hazardlib.geo.line.Line
:returns:
Well-known text (WKT) Linstring representation of the trace
'''
trace_str = ""
... | gem/oq-hazardlib | [
23,
49,
23,
9,
1323944086
] |
def init(name):
settings = get_xblock_settings()
sleep_seconds = settings.get("sleep_timeout", 10)
providers = settings.get("providers")
config = providers.get(name)
if config and isinstance(config, dict):
provider_type = config.get("type")
if provider_typ... | hastexo/hastexo-xblock | [
16,
9,
16,
4,
1444516845
] |
def set_logger(self, logger):
"""Set a logger other than the standard one.
This is meant to be used from Celery tasks, which usually
would want to use their task logger for logging.
"""
self.logger = logger | hastexo/hastexo-xblock | [
16,
9,
16,
4,
1444516845
] |
def set_capacity(self, capacity):
if capacity in (None, "None"):
capacity = -1
else:
try:
capacity = int(capacity)
except (TypeError, ValueError):
# Invalid capacity: disable the provider
capacity = 0
self.capac... | hastexo/hastexo-xblock | [
16,
9,
16,
4,
1444516845
] |
def set_environment(self, environment):
if not environment:
error_msg = ("No environment provided for provider %s" % self.name)
raise ProviderException(error_msg)
self.environment = environment | hastexo/hastexo-xblock | [
16,
9,
16,
4,
1444516845
] |
def generate_key_pair(self, encodeb64=False):
keypair = {}
pkey = paramiko.RSAKey.generate(1024)
keypair["public_key"] = pkey.get_base64()
s = StringIO()
pkey.write_private_key(s)
k = s.getvalue()
s.close()
if encodeb64:
k = base64.b64encode(b... | hastexo/hastexo-xblock | [
16,
9,
16,
4,
1444516845
] |
def get_stacks(self):
raise NotImplementedError() | hastexo/hastexo-xblock | [
16,
9,
16,
4,
1444516845
] |
def create_stack(self):
raise NotImplementedError() | hastexo/hastexo-xblock | [
16,
9,
16,
4,
1444516845
] |
def suspend_stack(self):
raise NotImplementedError() | hastexo/hastexo-xblock | [
16,
9,
16,
4,
1444516845
] |
def __init__(self, provider, config, sleep):
super(OpenstackProvider, self).__init__(provider, config, sleep)
self.heat_c = self._get_heat_client()
self.nova_c = self._get_nova_client() | hastexo/hastexo-xblock | [
16,
9,
16,
4,
1444516845
] |
def _get_nova_client(self):
return NovaWrapper(**self.credentials).get_client() | hastexo/hastexo-xblock | [
16,
9,
16,
4,
1444516845
] |
def get_stacks(self):
stacks = []
try:
heat_stacks = self.heat_c.stacks.list()
except HTTPNotFound:
return stacks
except (HTTPException, HttpError) as e:
raise ProviderException(e)
if heat_stacks:
for heat_stack in heat_stacks:
... | hastexo/hastexo-xblock | [
16,
9,
16,
4,
1444516845
] |
def create_stack(self, name, run):
if not self.template:
raise ProviderException("Template not set for provider %s." %
self.name)
try:
self.logger.info('Creating OpenStack Heat stack [%s]' % name)
res = self.heat_c.stacks.create(
... | hastexo/hastexo-xblock | [
16,
9,
16,
4,
1444516845
] |
def suspend_stack(self, name, wait=True):
try:
self.logger.info("Suspending OpenStack Heat stack [%s]" % name)
self.heat_c.actions.suspend(stack_id=name)
except (HTTPException, HttpError) as e:
raise ProviderException(e)
status = SUSPEND_IN_PROGRESS
... | hastexo/hastexo-xblock | [
16,
9,
16,
4,
1444516845
] |
def __init__(self, provider, config, sleep):
super(GcloudProvider, self).__init__(provider, config, sleep)
self.ds = self._get_deployment_service()
self.cs = self._get_compute_service()
self.project = config.get("gc_project_id") | hastexo/hastexo-xblock | [
16,
9,
16,
4,
1444516845
] |
def _get_compute_service(self):
return GcloudComputeEngine(**self.credentials).get_service() | hastexo/hastexo-xblock | [
16,
9,
16,
4,
1444516845
] |
def _get_deployment_servers(self, deployment_name):
try:
response = self.ds.resources().list(
project=self.project,
deployment=deployment_name,
filter='type = "compute.v1.instance"'
).execute()
except GcloudApiError as e:
... | hastexo/hastexo-xblock | [
16,
9,
16,
4,
1444516845
] |
def _encode_name(self, name):
"""
GCP enforces strict resource naming policies (regex
'[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?'), so we work around it by naming
the stack with a hash.
"""
digest = hashlib.sha1(b(name)).hexdigest()
return '%s%s' % (self.deployment_name_... | hastexo/hastexo-xblock | [
16,
9,
16,
4,
1444516845
] |
def get_stack(self, name):
deployment_name = self._encode_name(name)
try:
self.logger.debug('Fetching information on '
'Google Cloud deployment [%s]' % deployment_name)
response = self.ds.deployments().get(
project=self.project, depl... | hastexo/hastexo-xblock | [
16,
9,
16,
4,
1444516845
] |
def delete_stack(self, name, wait=True):
deployment_name = self._encode_name(name)
try:
self.logger.info('Deleting Google Cloud deployment '
'[%s]' % deployment_name)
operation = self.ds.deployments().delete(
project=self.project, dep... | hastexo/hastexo-xblock | [
16,
9,
16,
4,
1444516845
] |
def create_url(endpoint):
url = '{}{}'.format(BASE_URL, endpoint)
return url | openmotics/gateway | [
30,
12,
30,
27,
1481877206
] |
def pretty_print_output(output):
try:
json_dict = json.loads(output)
json_str = json.dumps(json_dict, indent=4)
return json_str
except Exception:
return output | openmotics/gateway | [
30,
12,
30,
27,
1481877206
] |
def login(verbose=None):
global TOKEN
if verbose == None:
verbose = VERBOSE
params = {'username': USERNAME, 'password': PASSWD}
resp = api_call('login', params=params, authenticated=False, verbose=verbose)
resp_json = resp.json()
if 'token' in resp_json:
token = resp.json()['toke... | openmotics/gateway | [
30,
12,
30,
27,
1481877206
] |
def get_news_text_from_html(data):
""" Given a string of data, locate the span that has the id "textstire" and
that ends in </span>. It needs to support nested spans.
Arguments:
data: A string with the entire html page.
Returns:
A string with just the content text.
"""
# From the data, get just the... | pistruiatul/hartapoliticii | [
58,
23,
58,
36,
1326573089
] |
def __init__(self, error_code, error_msg):
self.error_code = error_code
self.error_msg = error_msg
super(XQueueAddToQueueError, self).__init__(unicode(self)) | Stanford-Online/edx-platform | [
41,
19,
41,
1,
1374606346
] |
def __init__(self, request=None):
# Get basic auth (username/password) for
# xqueue connection if it's in the settings
if settings.XQUEUE_INTERFACE.get('basic_auth') is not None:
requests_auth = HTTPBasicAuth(
*settings.XQUEUE_INTERFACE['basic_auth'])
else:
... | Stanford-Online/edx-platform | [
41,
19,
41,
1,
1374606346
] |
def del_cert(self, student, course_id):
"""
Arguments:
student - User.object
course_id - courseenrollment.course_id (string)
Removes certificate for a student, will change
the certificate status to 'deleting'.
Certificate must be in the 'error' or 'download... | Stanford-Online/edx-platform | [
41,
19,
41,
1,
1374606346
] |
def add_cert(self, student, course_id, course=None, forced_grade=None, template_file=None, designation=None, generate_pdf=True):
"""
Request a new certificate for a student.
Arguments:
student - User.object
course_id - courseenrollment.course_id (CourseKey)
force... | Stanford-Online/edx-platform | [
41,
19,
41,
1,
1374606346
] |
def add_example_cert(self, example_cert):
"""Add a task to create an example certificate.
Unlike other certificates, an example certificate is
not associated with any particular user and is never
shown to students.
If an error occurs when adding the example certificate
... | Stanford-Online/edx-platform | [
41,
19,
41,
1,
1374606346
] |
def find_worksheets_feed(self):
return self.find_url(WORKSHEETS_REL) | pistruiatul/hartapoliticii | [
58,
23,
58,
36,
1326573089
] |
def get_table_id(self):
if self.id.text:
return self.id.text.split('/')[-1]
return None | pistruiatul/hartapoliticii | [
58,
23,
58,
36,
1326573089
] |
def value_for_index(self, column_index):
for field in self.field:
if field.index == column_index:
return field.text
raise FieldMissing('There is no field for %s' % column_index) | pistruiatul/hartapoliticii | [
58,
23,
58,
36,
1326573089
] |
def value_for_name(self, name):
for field in self.field:
if field.name == name:
return field.text
raise FieldMissing('There is no field for %s' % name) | pistruiatul/hartapoliticii | [
58,
23,
58,
36,
1326573089
] |
def get_value(self, column_name):
"""Returns the displayed text for the desired column in this row.
The formula or input which generated the displayed value is not accessible
through the list feed, to see the user's input, use the cells feed.
If a column is not present in this spreadsheet, or there i... | pistruiatul/hartapoliticii | [
58,
23,
58,
36,
1326573089
] |
def batch_set_cell(row, col, input):
pass | pistruiatul/hartapoliticii | [
58,
23,
58,
36,
1326573089
] |
def sqlite_column_reflect_listener(inspector, table, column_info):
"""Adds parenthesis around SQLite datetime defaults for utcnow."""
if column_info['default'] == "datetime('now', 'utc')":
column_info['default'] = utcnow_server_default | magfest/ubersystem | [
44,
49,
44,
436,
1391223385
] |
def upgrade():
op.create_table('guest_autograph',
sa.Column('id', residue.UUID(), nullable=False),
sa.Column('guest_id', residue.UUID(), nullable=False),
sa.Column('num', sa.Integer(), server_default='0', nullable=False),
sa.Column('length', sa.Integer(), server_default='60', nullable=False),
sa... | magfest/ubersystem | [
44,
49,
44,
436,
1391223385
] |
def __levenshtein__(str1, str2):
str1 = str1.encode('utf-8')
str2 = str2.encode('utf-8')
return Levenshtein.distance(str1.lower(),str2.lower()) | stratosphereips/Manati | [
109,
28,
109,
11,
1505115163
] |
def __dist_registrar__(registrar_a, registrar_b):
registrar_a = registrar_a if not registrar_a is None else ''
registrar_b = registrar_b if not registrar_b is None else ''
registrar_a = registrar_a.encode('utf-8') if not isinstance(registrar_a, list) else registrar_a[0].encode('utf-8')
registrar_b = reg... | stratosphereips/Manati | [
109,
28,
109,
11,
1505115163
] |
def __dist_org_by_min_dist__(orgs_a=[], orgs_b=[]):
orgs_seed = orgs_a.split(',') if not isinstance(orgs_a, list) else orgs_a
orgs_file = orgs_b.split(',') if not isinstance(orgs_b, list) else orgs_b
if not orgs_seed and not orgs_file:
return float(0)
elif not orgs_seed:
orgs_seed = ['']... | stratosphereips/Manati | [
109,
28,
109,
11,
1505115163
] |
def get_date_aux(date):
try:
return datetime.datetime.strptime(date, '%d-%m-%Y') \
if not isinstance(date, datetime.datetime) else date
except Exception as ex:
return dateutil.parser.parse(date) | stratosphereips/Manati | [
109,
28,
109,
11,
1505115163
] |
def get_diff_ttl(creation_date_a, creation_date_b,expiration_date_a, expiration_date_b):
if not creation_date_a and not creation_date_b and not expiration_date_a and not expiration_date_a:
return float(0)
elif not creation_date_a and not creation_date_b and expiration_date_a and expiration_date_b:
... | stratosphereips/Manati | [
109,
28,
109,
11,
1505115163
] |
def get_diff_emails_by_min_dist(emails_a=[], emails_b=[]):
emails_seed = emails_a.split(',') if not isinstance(emails_a, list) else emails_a
emails_file = emails_b.split(',') if not isinstance(emails_b, list) else emails_b
if not emails_seed and not emails_file:
return float(0)
elif not emails_s... | stratosphereips/Manati | [
109,
28,
109,
11,
1505115163
] |
def get_diff_name_servers_by_min_dist(name_servers_a=[], name_servers_b=[]):
if name_servers_a is None:
name_servers_a = []
if name_servers_b is None:
name_servers_b = []
name_servers_seed = name_servers_a.split(',') if not isinstance(name_servers_a, list) else name_servers_a
name_server... | stratosphereips/Manati | [
109,
28,
109,
11,
1505115163
] |
def features_domains(whois_info_a={}, whois_info_b={}):
domain_name_a = whois_info_a.get(KEY_DOMAIN_NAME,'')
registrar_a = whois_info_a.get(KEY_REGISTRAR,'')
name_a = whois_info_a.get(KEY_NAME,'')
orgs_a = whois_info_a.get(KEY_ORG,[]) # []
zipcode_a = whois_info_a.get(KEY_ZIPCODE,[]) # []
cre... | stratosphereips/Manati | [
109,
28,
109,
11,
1505115163
] |
def get_input_and_target_from(dmfs):
inputs = []
target = []
for dmf in dmfs:
inputs.append([1] + dmf.get_features().values())
target.append(dmf.related)
return inputs, target | stratosphereips/Manati | [
109,
28,
109,
11,
1505115163
] |
def distance_related_by_whois_obj(external_module,domain_a, domain_b):
global weights
result = WhoisConsult.get_features_info_by_set_url(external_module, [domain_a,domain_b])
domains = result.keys()
try:
whois_info_a = result[domains[0]]
whois_info_b = result[domains[1]]
except Excep... | stratosphereips/Manati | [
109,
28,
109,
11,
1505115163
] |
def testZeroMag(self):
mags = [0,0,0,0,0]
freqs = [23, 500, 3200, 9000, 10000]
self.assertEqualVector(
Tristimulus()(freqs, mags),
[0,0,0]) | MTG/essentia | [
2331,
490,
2331,
378,
1370271227
] |
def test4Freqs(self):
mags = [1,2,3,4]
freqs = [100, 435, 6547, 24324]
self.assertAlmostEqualVector(
Tristimulus()(freqs, mags),
[.1, .9, 0]) | MTG/essentia | [
2331,
490,
2331,
378,
1370271227
] |
def testFrequencyOrder(self):
freqs = [1,2,1.1]
mags = [0,0,0]
self.assertComputeFails(Tristimulus(), freqs, mags) | MTG/essentia | [
2331,
490,
2331,
378,
1370271227
] |
def testEmpty(self):
freqs = []
mags = []
self.assertEqualVector(Tristimulus()([],[]), [0,0,0]) | MTG/essentia | [
2331,
490,
2331,
378,
1370271227
] |
def upgrade():
try:
op.create_table('smtpserver',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('identifier', sa.Unicode(length=255), nullable=False),
sa.Column('server', sa.Unicode(length=255), nullable=False),
sa.Column('port', sa.Integer(), nullable=True),
... | privacyidea/privacyidea | [
1321,
287,
1321,
217,
1401806822
] |
def __init__(self):
super(Simrad, self).__init__()
self.desc = "Simrad"
self._ext.add('ssp')
self._ext.add('s??') | hydroffice/hyo_soundspeed | [
15,
18,
15,
3,
1459123919
] |
def _parse_header(self):
meta = {}
m = re.search(r'''\$[A-Z][A-Z](?P<fmt>S\d\d), #fmt is between 00 and 53
(?P<id>\d+),
(?P<nmeasure>\d+),
(?P<hour>\d\d)(?P<minute>\d\d)(?P<second>\d\d),
(?P<day>\d\d),
... | hydroffice/hyo_soundspeed | [
15,
18,
15,
3,
1459123919
] |
def _rule(word, count, min_count):
if word == "human":
return utils.RULE_DISCARD # throw out
else:
return utils.RULE_DEFAULT # apply default rule, i.e. min_count | gojomo/gensim | [
14,
13,
14,
1,
1401498617
] |
def testBuildVocabFromFreq(self):
"""Test that the algorithm is able to build vocabulary from given
frequency table"""
freq_dict = {
'minors': 2, 'graph': 3, 'system': 4,
'trees': 3, 'eps': 2, 'computer': 2,
'survey': 2, 'user': 3, 'human': 2,
'time': 2, 'interfac... | gojomo/gensim | [
14,
13,
14,
1,
1401498617
] |
def testTotalWordCount(self):
model = word2vec.Word2Vec(vector_size=10, min_count=0, seed=42)
total_words = model.scan_vocab(sentences)[0]
self.assertEqual(total_words, 29) | gojomo/gensim | [
14,
13,
14,
1,
1401498617
] |
def testOnlineLearning(self):
"""Test that the algorithm is able to add new words to the
vocabulary and to a trained model when using a sorted vocabulary"""
model_hs = word2vec.Word2Vec(sentences, vector_size=10, min_count=0, seed=42, hs=1, negative=0)
model_neg = word2vec.Word2Vec(sente... | gojomo/gensim | [
14,
13,
14,
1,
1401498617
] |
def testOnlineLearningFromFile(self):
"""Test that the algorithm is able to add new words to the
vocabulary and to a trained model when using a sorted vocabulary"""
with temporary_file(get_tmpfile('gensim_word2vec1.tst')) as corpus_file,\
temporary_file(get_tmpfile('gensim_word2v... | gojomo/gensim | [
14,
13,
14,
1,
1401498617
] |
def testOnlineLearningAfterSaveFromFile(self):
"""Test that the algorithm is able to add new words to the
vocabulary and to a trained model when using a sorted vocabulary"""
with temporary_file(get_tmpfile('gensim_word2vec1.tst')) as corpus_file,\
temporary_file(get_tmpfile('gens... | gojomo/gensim | [
14,
13,
14,
1,
1401498617
] |
def test_sg_hs_online(self):
"""Test skipgram w/ hierarchical softmax"""
model = word2vec.Word2Vec(sg=1, window=5, hs=1, negative=0, min_count=3, epochs=10, seed=42, workers=2)
self.onlineSanity(model) | gojomo/gensim | [
14,
13,
14,
1,
1401498617
] |
def test_cbow_hs_online(self):
"""Test CBOW w/ hierarchical softmax"""
model = word2vec.Word2Vec(
sg=0, cbow_mean=1, alpha=0.05, window=5, hs=1, negative=0,
min_count=3, epochs=20, seed=42, workers=2
)
self.onlineSanity(model) | gojomo/gensim | [
14,
13,
14,
1,
1401498617
] |
def testPersistence(self):
"""Test storing/loading the entire model."""
tmpf = get_tmpfile('gensim_word2vec.tst')
model = word2vec.Word2Vec(sentences, min_count=1)
model.save(tmpf)
self.models_equal(model, word2vec.Word2Vec.load(tmpf))
# test persistence of the KeyedVect... | gojomo/gensim | [
14,
13,
14,
1,
1401498617
] |
def testPersistenceFromFile(self):
"""Test storing/loading the entire model trained with corpus_file argument."""
with temporary_file(get_tmpfile('gensim_word2vec.tst')) as corpus_file:
utils.save_as_line_sentence(sentences, corpus_file)
tmpf = get_tmpfile('gensim_word2vec.tst')... | gojomo/gensim | [
14,
13,
14,
1,
1401498617
] |
def testRuleWithMinCount(self):
"""Test that returning RULE_DEFAULT from trim_rule triggers min_count."""
model = word2vec.Word2Vec(sentences + [["occurs_only_once"]], min_count=2, trim_rule=_rule)
self.assertTrue("human" not in model.wv)
self.assertTrue("occurs_only_once" not in model.w... | gojomo/gensim | [
14,
13,
14,
1,
1401498617
] |
def testLambdaRule(self):
"""Test that lambda trim_rule works."""
def rule(word, count, min_count):
return utils.RULE_DISCARD if word == "human" else utils.RULE_DEFAULT
model = word2vec.Word2Vec(sentences, min_count=1, trim_rule=rule)
self.assertTrue("human" not in model.wv) | gojomo/gensim | [
14,
13,
14,
1,
1401498617
] |
def testLoadPreKeyedVectorModelCFormat(self):
"""Test loading pre-KeyedVectors word2vec model saved in word2vec format"""
model = keyedvectors.KeyedVectors.load_word2vec_format(datapath('word2vec_pre_kv_c'))
self.assertTrue(model.vectors.shape[0] == len(model)) | gojomo/gensim | [
14,
13,
14,
1,
1401498617
] |
def testNoTrainingCFormat(self):
tmpf = get_tmpfile('gensim_word2vec.tst')
model = word2vec.Word2Vec(sentences, min_count=1)
model.wv.save_word2vec_format(tmpf, binary=True)
kv = keyedvectors.KeyedVectors.load_word2vec_format(tmpf, binary=True)
binary_model = word2vec.Word2Vec()
... | gojomo/gensim | [
14,
13,
14,
1,
1401498617
] |
def testTooShortTextWord2VecFormat(self):
tfile = get_tmpfile('gensim_word2vec.tst')
model = word2vec.Word2Vec(sentences, min_count=1)
model.wv.save_word2vec_format(tfile, binary=False)
f = open(tfile, 'r+b')
f.write(b'13') # write wrong (too-long) vector count
f.close()... | gojomo/gensim | [
14,
13,
14,
1,
1401498617
] |
def testPersistenceWord2VecFormatWithVocab(self):
"""Test storing/loading the entire model and vocabulary in word2vec format."""
tmpf = get_tmpfile('gensim_word2vec.tst')
model = word2vec.Word2Vec(sentences, min_count=1)
testvocab = get_tmpfile('gensim_word2vec.vocab')
model.wv.s... | gojomo/gensim | [
14,
13,
14,
1,
1401498617
] |
def testPersistenceWord2VecFormatCombinationWithStandardPersistence(self):
"""Test storing/loading the entire model and vocabulary in word2vec format chained with
saving and loading via `save` and `load` methods`.
It was possible prior to 1.0.0 release, now raises Exception"""
tmpf = g... | gojomo/gensim | [
14,
13,
14,
1,
1401498617
] |
def testVocab(self):
"""Test word2vec vocabulary building."""
corpus = LeeCorpus()
total_words = sum(len(sentence) for sentence in corpus)
# try vocab building explicitly, using all words
model = word2vec.Word2Vec(min_count=1, hs=1, negative=0)
model.build_vocab(corpus)
... | gojomo/gensim | [
14,
13,
14,
1,
1401498617
] |
def testTrainingFromFile(self):
"""Test word2vec training with corpus_file argument."""
# build vocabulary, don't train yet
with temporary_file(get_tmpfile('gensim_word2vec.tst')) as tf:
utils.save_as_line_sentence(sentences, tf)
model = word2vec.Word2Vec(vector_size=2, ... | gojomo/gensim | [
14,
13,
14,
1,
1401498617
] |
def testLocking(self):
"""Test word2vec training doesn't change locked vectors."""
corpus = LeeCorpus()
# build vocabulary, don't train yet
for sg in range(2): # test both cbow and sg
model = word2vec.Word2Vec(vector_size=4, hs=1, negative=5, min_count=1, sg=sg, window=5)
... | gojomo/gensim | [
14,
13,
14,
1,
1401498617
] |
def testEvaluateWordPairs(self):
"""Test Spearman and Pearson correlation coefficients give sane results on similarity datasets"""
corpus = word2vec.LineSentence(datapath('head500.noblanks.cor.bz2'))
model = word2vec.Word2Vec(corpus, min_count=3, epochs=20)
correlation = model.wv.evaluat... | gojomo/gensim | [
14,
13,
14,
1,
1401498617
] |
def testEvaluateWordPairsFromFile(self):
"""Test Spearman and Pearson correlation coefficients give sane results on similarity datasets"""
with temporary_file(get_tmpfile('gensim_word2vec.tst')) as tf:
utils.save_as_line_sentence(word2vec.LineSentence(datapath('head500.noblanks.cor.bz2')), t... | gojomo/gensim | [
14,
13,
14,
1,
1401498617
] |
def test_sg_hs(self):
"""Test skipgram w/ hierarchical softmax"""
model = word2vec.Word2Vec(sg=1, window=4, hs=1, negative=0, min_count=5, epochs=10, workers=2)
self.model_sanity(model) | gojomo/gensim | [
14,
13,
14,
1,
1401498617
] |
def test_sg_hs_fromfile(self):
model = word2vec.Word2Vec(sg=1, window=4, hs=1, negative=0, min_count=5, epochs=10, workers=2)
self.model_sanity(model, with_corpus_file=True) | gojomo/gensim | [
14,
13,
14,
1,
1401498617
] |
def test_sg_neg_fromfile(self):
model = word2vec.Word2Vec(sg=1, window=4, hs=0, negative=15, min_count=5, epochs=10, workers=2)
self.model_sanity(model, with_corpus_file=True) | gojomo/gensim | [
14,
13,
14,
1,
1401498617
] |
def test_method_in_bulk(self):
"""Not run by default testing, but can be run locally to help tune stochastic aspects of tests
to very-very-rarely fail. EG:
% BULK_TEST_REPS=200 METHOD_NAME=test_cbow_hs pytest test_word2vec.py -k "test_method_in_bulk"
Method must accept `ranks` keyword-ar... | gojomo/gensim | [
14,
13,
14,
1,
1401498617
] |
def test_cbow_hs_fromfile(self):
model = word2vec.Word2Vec(
sg=0, cbow_mean=1, alpha=0.1, window=2, hs=1, negative=0,
min_count=5, epochs=60, workers=2, batch_words=1000
)
self.model_sanity(model, with_corpus_file=True) | gojomo/gensim | [
14,
13,
14,
1,
1401498617
] |
def test_cbow_neg_fromfile(self):
model = word2vec.Word2Vec(
sg=0, cbow_mean=1, alpha=0.05, window=5, hs=0, negative=15,
min_count=5, epochs=10, workers=2, sample=0
)
self.model_sanity(model, with_corpus_file=True) | gojomo/gensim | [
14,
13,
14,
1,
1401498617
] |
def testTrainingCbow(self):
"""Test CBOW word2vec training."""
# to test training, make the corpus larger by repeating its sentences over and over
# build vocabulary, don't train yet
model = word2vec.Word2Vec(vector_size=2, min_count=1, sg=0, hs=1, negative=0)
model.build_vocab(s... | gojomo/gensim | [
14,
13,
14,
1,
1401498617
] |
def testTrainingCbowNegative(self):
"""Test CBOW (negative sampling) word2vec training."""
# to test training, make the corpus larger by repeating its sentences over and over
# build vocabulary, don't train yet
model = word2vec.Word2Vec(vector_size=2, min_count=1, sg=0, hs=0, negative=2)... | gojomo/gensim | [
14,
13,
14,
1,
1401498617
] |
def testSimilarBy(self):
"""Test word2vec similar_by_word and similar_by_vector."""
model = word2vec.Word2Vec(sentences, vector_size=2, min_count=1, hs=1, negative=0)
wordsims = model.wv.similar_by_word('graph', topn=10)
wordsims2 = model.wv.most_similar(positive='graph', topn=10)
... | gojomo/gensim | [
14,
13,
14,
1,
1401498617
] |
def testRNG(self):
"""Test word2vec results identical with identical RNG seed."""
model = word2vec.Word2Vec(sentences, min_count=2, seed=42, workers=1)
model2 = word2vec.Word2Vec(sentences, min_count=2, seed=42, workers=1)
self.models_equal(model, model2) | gojomo/gensim | [
14,
13,
14,
1,
1401498617
] |
def testPredictOutputWord(self):
'''Test word2vec predict_output_word method handling for negative sampling scheme'''
# under normal circumstances
model_with_neg = word2vec.Word2Vec(sentences, min_count=1)
predictions_with_neg = model_with_neg.predict_output_word(['system', 'human'], top... | gojomo/gensim | [
14,
13,
14,
1,
1401498617
] |
def testLoadOldModelSeparates(self):
"""Test loading an old word2vec model of indeterminate version"""
# Model stored in multiple files
model_file = 'word2vec_old_sep'
model = word2vec.Word2Vec.load(datapath(model_file))
self.assertTrue(model.wv.vectors.shape == (12, 100))
... | gojomo/gensim | [
14,
13,
14,
1,
1401498617
] |
def test_load_old_models_1_x(self):
"""Test loading 1.x models"""
old_versions = [
'1.0.0', '1.0.1',
]
for old_version in old_versions:
self._check_old_version(old_version) | gojomo/gensim | [
14,
13,
14,
1,
1401498617
] |
def test_load_old_models_3_x(self):
"""Test loading 3.x models"""
# test for max_final_vocab for model saved in 3.3
model_file = 'word2vec_3.3'
model = word2vec.Word2Vec.load(datapath(model_file))
self.assertEqual(model.max_final_vocab, None)
self.assertEqual(model.max_f... | gojomo/gensim | [
14,
13,
14,
1,
1401498617
] |
def testBuildVocabWarning(self, loglines):
"""Test if warning is raised on non-ideal input to a word2vec model"""
sentences = ['human', 'machine']
model = word2vec.Word2Vec()
model.build_vocab(sentences)
warning = "Each 'sentences' item should be a list of words (usually unicode ... | gojomo/gensim | [
14,
13,
14,
1,
1401498617
] |
def testTrainWarning(self, loglines):
"""Test if warning is raised if alpha rises during subsequent calls to train()"""
sentences = [
['human'],
['graph', 'trees']
]
model = word2vec.Word2Vec(min_count=1)
model.build_vocab(sentences)
for epoch in r... | gojomo/gensim | [
14,
13,
14,
1,
1401498617
] |
def test_sentences_should_not_be_a_generator(self):
"""
Is sentences a generator object?
"""
gen = (s for s in sentences)
self.assertRaises(TypeError, word2vec.Word2Vec, (gen,)) | gojomo/gensim | [
14,
13,
14,
1,
1401498617
] |
def test_reset_from(self):
"""Test if reset_from() uses pre-built structures from other model"""
model = word2vec.Word2Vec(sentences, min_count=1)
other_model = word2vec.Word2Vec(new_sentences, min_count=1)
model.reset_from(other_model)
self.assertEqual(model.wv.key_to_index, oth... | gojomo/gensim | [
14,
13,
14,
1,
1401498617
] |
def testNonzero(self):
'''Test basic functionality with a test sentence.'''
model = word2vec.Word2Vec(sentences, min_count=2, seed=42, workers=1)
sentence1 = ['human', 'interface', 'computer']
sentence2 = ['survey', 'user', 'computer', 'system', 'response', 'time']
distance = mo... | gojomo/gensim | [
14,
13,
14,
1,
1401498617
] |
def testSymmetry(self):
'''Check that distance is symmetric.'''
model = word2vec.Word2Vec(sentences, min_count=2, seed=42, workers=1)
sentence1 = ['human', 'interface', 'computer']
sentence2 = ['survey', 'user', 'computer', 'system', 'response', 'time']
distance1 = model.wv.wmdi... | gojomo/gensim | [
14,
13,
14,
1,
1401498617
] |
def testIdenticalSentences(self):
'''Check that the distance from a sentence to itself is zero.'''
model = word2vec.Word2Vec(sentences, min_count=1)
sentence = ['survey', 'user', 'computer', 'system', 'response', 'time']
distance = model.wv.wmdistance(sentence, sentence)
self.as... | gojomo/gensim | [
14,
13,
14,
1,
1401498617
] |
def testLineSentenceWorksWithFilename(self):
"""Does LineSentence work with a filename argument?"""
with utils.open(datapath('lee_background.cor'), 'rb') as orig:
sentences = word2vec.LineSentence(datapath('lee_background.cor'))
for words in sentences:
self.assert... | gojomo/gensim | [
14,
13,
14,
1,
1401498617
] |
def testCythonLineSentenceWorksWithFilename(self):
"""Does CythonLineSentence work with a filename argument?"""
from gensim.models import word2vec_corpusfile
with utils.open(datapath('lee_background.cor'), 'rb') as orig:
sentences = word2vec_corpusfile.CythonLineSentence(datapath('le... | gojomo/gensim | [
14,
13,
14,
1,
1401498617
] |
def testLineSentenceWorksWithNormalFile(self):
"""Does LineSentence work with a file object argument, rather than filename?"""
with utils.open(datapath('head500.noblanks.cor'), 'rb') as orig:
with utils.open(datapath('head500.noblanks.cor'), 'rb') as fin:
sentences = word2vec... | gojomo/gensim | [
14,
13,
14,
1,
1401498617
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.