code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if url[-3:] == 'xml' or url[1][-4:] == 'atom':
print("Added your feed as %s" % str(add_feed(url)))
elif is_feed(url):
print("Added your feed as %s" % str(add_feed(url)))
elif force:
print("Added your feed as %s" % str(add_feed(url)))
else:
print("Hitman doesn't think... | def add(url, force=False) | Add a atom or RSS feed by url.
If it doesn't end in .atom or .rss we'll do some guessing. | 4.79964 | 4.419863 | 1.085925 |
with Database("settings") as settings:
if value in ['0', 'false', 'no', 'off', 'False']:
del settings[key]
print("Disabled setting")
else:
print(value)
settings[key] = value
print("Setting saved") | def set_settings(key, value) | Set Hitman internal settings. | 5.054574 | 5.112557 | 0.988659 |
with Database("settings") as s:
if all:
for k, v in zip(list(s.keys()), list(s.values())):
print("{} = {}".format(k, v))
elif key:
print("{} = {}".format(key, s[key]))
else:
print("Don't know what you want? Try --all") | def get_settings(all,key) | View Hitman internal settings. Use 'all' for all keys | 3.448206 | 3.603253 | 0.95697 |
seed = hb_decode(dict['seed'])
index = dict['index']
return Challenge(seed, index) | def fromdict(dict) | Takes a dictionary as an argument and returns a new Challenge
object from the dictionary.
:param dict: the dictionary to convert | 14.430925 | 16.084658 | 0.897186 |
tree = MerkleTree.fromdict(dict['tree'])
chunksz = dict['chunksz']
filesz = dict['filesz']
return Tag(tree, chunksz, filesz) | def fromdict(dict) | Takes a dictionary as an argument and returns a new Tag object
from the dictionary.
:param dict: the dictionary to convert | 6.410982 | 7.723381 | 0.830075 |
return {'index': self.index,
'seed': hb_encode(self.seed),
'n': self.n,
'root': hb_encode(self.root),
'hmac': hb_encode(self.hmac),
'timestamp': self.timestamp} | def todict(self) | Returns a dictionary fully representing the state of this object | 4.529803 | 4.508873 | 1.004642 |
index = dict['index']
seed = hb_decode(dict['seed'])
n = dict['n']
root = hb_decode(dict['root'])
hmac = hb_decode(dict['hmac'])
timestamp = dict['timestamp']
self = State(index, seed, n, root, hmac, timestamp)
return self | def fromdict(dict) | Takes a dictionary as an argument and returns a new State object
from the dictionary.
:param dict: the dictionary to convert | 4.218308 | 4.497605 | 0.937901 |
h = HMAC.new(key, None, SHA256)
h.update(str(self.index).encode())
h.update(self.seed)
h.update(str(self.n).encode())
h.update(self.root)
h.update(str(self.timestamp).encode())
return h.digest() | def get_hmac(self, key) | Returns the keyed HMAC for authentication of this state data.
:param key: the key for the keyed hash function | 2.663937 | 2.976481 | 0.894995 |
key = hb_decode(dict['key'])
check_fraction = dict['check_fraction']
return Merkle(check_fraction, key) | def fromdict(dict) | Takes a dictionary as an argument and returns a new Proof object
from the dictionary.
:param dict: the dictionary to convert | 14.603592 | 20.450865 | 0.714082 |
if (seed is None):
seed = os.urandom(DEFAULT_KEY_SIZE)
if (filesz is None):
file.seek(0, 2)
filesz = file.tell()
if (chunksz is None):
if (self.check_fraction is not None):
chunksz = int(self.check_fraction * filesz)
... | def encode(self,
file,
n=DEFAULT_CHALLENGE_COUNT,
seed=None,
chunksz=None,
filesz=None) | This function generates a merkle tree with the leaves as seed file
hashes, the seed for each leaf being a deterministic seed generated
from a key.
:param file: a file like object that supports the `read()`, `seek()`
and `tell()` methods
:param n: the number of challenges to gene... | 3.03516 | 2.954436 | 1.027323 |
state.checksig(self.key)
if (state.index >= state.n):
raise HeartbeatError("Out of challenges.")
state.seed = MerkleHelper.get_next_seed(self.key, state.seed)
chal = Challenge(state.seed, state.index)
state.index += 1
state.sign(self.key)
retu... | def gen_challenge(self, state) | returns the next challenge and increments the seed and index
in the state.
:param state: the state to use for generating the challenge. will
verify the integrity of the state object before using it to generate
a challenge. it will then modify the state by incrementing the seed
... | 6.194399 | 5.473469 | 1.131714 |
leaf = MerkleLeaf(challenge.index,
MerkleHelper.get_chunk_hash(file,
challenge.seed,
filesz=tag.filesz,
chunksz=tag... | def prove(self, file, challenge, tag) | Returns a proof of ownership of the given file based on the
challenge. The proof consists of a hash of the specified file chunk
and the complete merkle branch.
:param file: a file that supports `read()`, `seek()` and `tell()`
:param challenge: the challenge to use for generating this p... | 9.770316 | 8.477519 | 1.152497 |
state.checksig(self.key)
if (proof.leaf.index != challenge.index):
return False
return MerkleTree.verify_branch(proof.leaf,
proof.branch,
state.root) | def verify(self, proof, challenge, state) | returns true if the proof matches the challenge. verifies that the
server possesses the encoded file.
:param proof: the proof that was returned from the server
:param challenge: the challenge provided to the server
:param state: the state of the file, which includes the merkle root of
... | 9.313857 | 10.563844 | 0.881673 |
return hmac.new(key, seed, hashlib.sha256).digest() | def get_next_seed(key, seed) | This takes a seed and generates the next seed in the sequence.
it simply calculates the hmac of the seed with the key. It returns
the next seed
:param key: the key to use for the HMAC
:param seed: the seed to permutate | 4.641924 | 5.050104 | 0.919174 |
h = hmac.new(seed, None, hashlib.sha256)
while (True):
buffer = file.read(bufsz)
h.update(buffer)
if (len(buffer) != bufsz):
break
return h.digest() | def get_file_hash(file, seed, bufsz=DEFAULT_BUFFER_SIZE) | This method generates a secure hash of the given file. Returns the
hash
:param file: a file like object to get a hash of. should support
`read()`
:param seed: the seed to use for key of the HMAC function
:param bufsz: an optional buffer size to use for reading the file | 2.862066 | 3.230668 | 0.885905 |
if (filesz is None):
file.seek(0, 2)
filesz = file.tell()
if (filesz < chunksz):
chunksz = filesz
prf = KeyedPRF(seed, filesz - chunksz + 1)
i = prf.eval(0)
file.seek(i)
h = hmac.new(seed, None, hashlib.sha256)
while (T... | def get_chunk_hash(file,
seed,
filesz=None,
chunksz=DEFAULT_CHUNK_SIZE,
bufsz=DEFAULT_BUFFER_SIZE) | returns a hash of a chunk of the file provided. the position of
the chunk is determined by the seed. additionally, the hmac of the
chunk is calculated from the seed.
:param file: a file like object to get the chunk hash from. should
support `read()`, `seek()` and `tell()`.
:p... | 2.645083 | 2.753114 | 0.96076 |
domain = cls()
join_with = cls.AND
for query in queries:
if query in [cls.OR, cls.AND]:
join_with = query
else:
domain.add_query(query, join_with)
return domain | def from_tuple(cls, queries) | Create a ``Domain`` given a set of complex query tuples.
Args:
queries (iter): An iterator of complex queries. Each iteration
should contain either:
* A data-set compatible with :func:`~domain.Domain.add_query`
* A string to switch the join type
... | 3.67114 | 3.767413 | 0.974446 |
if not isinstance(query, DomainCondition):
query = DomainCondition.from_tuple(query)
if len(self.query):
self.query.append(join_with)
self.query.append(query) | def add_query(self, query, join_with=AND) | Join a new query to existing queries on the stack.
Args:
query (tuple or list or DomainCondition): The condition for the
query. If a ``DomainCondition`` object is not provided, the
input should conform to the interface defined in
:func:`~.domain.Domai... | 3.395972 | 2.76224 | 1.229427 |
field, query = query[0], query[1:]
try:
cls = TYPES[type(query[0])]
except KeyError:
# We just fallback to the base class if unknown type.
pass
return cls(field, *query) | def from_tuple(cls, query) | Create a condition from a query tuple.
Args:
query (tuple or list): Tuple or list that contains a query domain
in the format of ``(field_name, field_value,
field_value_to)``. ``field_value_to`` is only applicable in
the case of a date search.
... | 6.21943 | 7.341776 | 0.847129 |
for name, backend_settings in settings.storage.iteritems():
backend_path = backend_settings['backend']
backend_module, backend_cls = backend_path.rsplit('.', 1)
backend_module = import_module(backend_module)
# Create an instance of the configured backend.
backend_constructor = get... | def load_backends(self) | Loads all the backends setup in settings.py. | 3.377055 | 3.191722 | 1.058067 |
validate_stream(stream)
default_prefix = ''
longest_prefix = default_prefix
for prefix in self.prefix_confs[namespace]:
if prefix == default_prefix:
continue
if not stream.startswith(prefix):
continue
if len(prefix) <= len(longest_prefix):
continue
lo... | def get_matching_prefix(self, namespace, stream) | We look at the stream prefixs configured in stream.yaml and match stream
to the longest prefix. | 3.701826 | 3.374786 | 1.096907 |
if namespace not in self.namespaces:
raise NamespaceMissing('`{}` namespace is not configured'
.format(namespace))
return self.prefix_confs[namespace][self.get_matching_prefix(namespace,
stream)] | def backends_to_mutate(self, namespace, stream) | Return all the backends enabled for writing for `stream`. | 9.526165 | 8.961304 | 1.063033 |
if namespace not in self.namespaces:
raise NamespaceMissing('`{}` namespace is not configured'
.format(namespace))
stream_prefix = self.get_matching_prefix(namespace, stream)
read_backend = self.prefix_read_backends[namespace][stream_prefix]
return (read_backend,
... | def backend_to_retrieve(self, namespace, stream) | Return backend enabled for reading for `stream`. | 5.567568 | 4.864129 | 1.144618 |
cls(
'/hooks.json',
data=web_hook.to_api(),
request_type=RequestPaginator.POST,
session=session,
)
return True | def create(cls, session, web_hook) | Create a web hook.
Note that creating a new web hook will overwrite the web hook that is
already configured for this company. There is also no way to
programmatically determine if a web hook already exists for the
company. This is a limitation of the HelpScout API and cannot be
... | 12.150986 | 16.146814 | 0.752531 |
if value:
try:
value = value.read()
except AttributeError:
pass
b64 = base64.b64encode(value.encode('utf-8'))
self.data = b64.decode('utf-8') | def raw_data(self, value) | Set the base64 encoded data using a raw value or file object. | 2.788536 | 2.325828 | 1.198943 |
code = request.form['code']
interval = int(request.form['interval'])
task_id = binascii.b2a_hex(os.urandom(5))
new_task = Task(id=task_id)
new_task.active = True
new_task.code = code
new_task.interval = interval
# TODO(derek): Assert there is only one other_task
other_task = Task.query.filter_by(... | def schedule() | HTTP endpoint for scheduling tasks
If a task with the same code already exists, the one with the shorter
interval will be made active. | 2.692241 | 2.539106 | 1.06031 |
task_id = request.form['id']
task = Task.query.get(task_id)
if not task:
return json.dumps({
'status': 'success',
'id': None,
})
task.delete()
if task.active:
current_app.scheduler.cancel(task_id)
code = task.code
other_task = Task.query.filter_by(code=code).order_by('in... | def cancel() | HTTP endpoint for canceling tasks
If an active task is cancelled, an inactive task with the same code and the
smallest interval will be activated if it exists. | 2.595394 | 2.305521 | 1.12573 |
try:
self._dest_coll(ns).insert(raw['o'], safe=True)
except DuplicateKeyError, e:
logging.warning(e) | def insert(self, ns, docid, raw, **kw) | Perform a single insert operation.
{'docid': ObjectId('4e95ae77a20e6164850761cd'),
'ns': u'mydb.tweets',
'raw': {u'h': -1469300750073380169L,
u'ns': u'mydb.tweets',
u'o': {u'_id': ObjectId('4e95ae77a20e6164850761cd'),
... | 6.796626 | 5.295691 | 1.283426 |
self._dest_coll(ns).update(raw['o2'], raw['o'], safe=True) | def update(self, ns, docid, raw, **kw) | Perform a single update operation.
{'docid': ObjectId('4e95ae3616692111bb000001'),
'ns': u'mydb.tweets',
'raw': {u'h': -5295451122737468990L,
u'ns': u'mydb.tweets',
u'o': {u'$set': {u'content': u'Lorem ipsum'}},
u'o2':... | 19.208776 | 8.907022 | 2.156588 |
self._dest_coll(ns).remove(raw['o'], safe=True) | def delete(self, ns, docid, raw, **kw) | Perform a single delete operation.
{'docid': ObjectId('4e959ea11669210edc002902'),
'ns': u'mydb.tweets',
'raw': {u'b': True,
u'h': -8347418295715732480L,
u'ns': u'mydb.tweets',
u'o': {u'_id': ObjectId('4e959ea11669210e... | 22.513159 | 14.073355 | 1.599701 |
dbname = raw['ns'].split('.', 1)[0]
collname = raw['o']['dropIndexes']
self.dest[dbname][collname].drop_index(raw['o']['index']) | def drop_index(self, raw) | Executes a drop index command.
{ "op" : "c",
"ns" : "testdb.$cmd",
"o" : { "dropIndexes" : "testcoll",
"index" : "nuie_1" } } | 7.308544 | 3.42614 | 2.133172 |
try:
dbname = raw['ns'].split('.', 1)[0]
self.dest[dbname].command(raw['o'], check=True)
except OperationFailure, e:
logging.warning(e) | def command(self, ns, raw, **kw) | Executes command.
{ "op" : "c",
"ns" : "testdb.$cmd",
"o" : { "drop" : "fs.files"}
} | 9.628068 | 5.487822 | 1.754443 |
if isinstance(mailbox_or_id, Mailbox):
mailbox_or_id = mailbox_or_id.id
return cls(
'/mailboxes/%d/folders.json' % mailbox_or_id,
session=session,
out_type=Folder,
) | def get_folders(cls, session, mailbox_or_id) | List the folders for the mailbox.
Args:
mailbox_or_id (helpscout.models.Mailbox or int): Mailbox or the ID
of the mailbox to get the folders for.
Returns:
RequestPaginator(output_type=helpscout.models.Folder): Folders
iterator. | 2.9574 | 3.535862 | 0.836401 |
if step == 0:
raise ValueError("slice() arg 3 must not be zero")
if start==stop:
raise StopIteration
previous = start
next = start + step
while next < stop:
yield previous, next
previous += step
next += step
yield previous, stop | def _slice(start, stop, step) | Generate pairs so that you can slice from start to stop, step elements at a time
:param start: The start of the generated series
:param stop: The last of the generated series
:param step: The difference between the first element of the returned pair and the second
:return: A pair that you can use to sli... | 3.492445 | 3.64778 | 0.957416 |
summoners_league = defaultdict(set)
for start, end in _slice(0, len(summoner_ids), 10):
for id, leagues in get_league_entries_by_summoner(summoner_ids[start:end]).items():
for league in leagues:
if Queue[league.queue]==queue:
summoners_league[Tier.par... | def leagues_by_summoner_ids(summoner_ids, queue=Queue.RANKED_SOLO_5x5) | Takes in a list of players ids and divide them by league tiers.
:param summoner_ids: a list containing the ids of players
:param queue: the queue to consider
:return: a dictionary tier -> set of ids | 3.72545 | 3.874497 | 0.961531 |
leagues = leagues_by_summoner_ids([p.player.summonerId for p in participantsIdentities], queue)
match_tier = max(leagues.keys(), key=operator.attrgetter('value'))
return match_tier, {league: ids for league, ids in leagues.items() if league.is_better_or_equal(minimum_tier)} | def get_tier_from_participants(participantsIdentities, minimum_tier=Tier.bronze, queue=Queue.RANKED_SOLO_5x5) | Returns the tier of the lowest tier and the participantsIDs divided by tier
player in the match
:param participantsIdentities: the match participants
:param minimum_tier: the minimum tier that a participant must be in order to be added
:param queue: the queue over which the tier of the player is conside... | 4.186599 | 4.701394 | 0.890502 |
ids = {}
for start, end in _slice(0, len(summoners), 40):
result = get_summoners_by_name(summoners[start:end])
for name, summoner in result.items():
ids[name] = summoner.id
return ids | def summoner_names_to_id(summoners) | Gets a list of summoners names and return a dictionary mapping the player name to his/her summoner id
:param summoners: a list of player names
:return: a dictionary name -> id | 3.189208 | 3.317625 | 0.961292 |
if self.board_data:
board_dict = json.loads(self.board_data)
board_dict['id'] = self.id
del board_dict['__version__']
else:
board_dict = {
'id': self.id,
'title': '',
'panels': []
}
return board_dict
| def json(self) | A JSON-encoded description of this board.
Format:
{'id': board_id,
'title': 'The title of the board',
'panels': [{
'title': 'The title of the panel'
'data_source': {
'source_type': PanelSource.TYPE,
'refresh_seconds': 600,
...source_specific_details...
... | 3.671517 | 3.104526 | 1.182634 |
def get(dataset = None, include_metadata = False, mnemonics = None, **dim_values):
if not dataset and not mnemonics:
raise ValueError('Dataset id is not specified')
if mnemonics and dim_values:
raise ValueError('The function does not support specifying mnemonics and selection in a ... | Use this function to get data from Knoema dataset. | null | null | null | |
def upload(file_path, dataset=None, public=False):
config = ApiConfig()
client = ApiClient(config.host, config.app_id, config.app_secret)
return client.upload(file_path, dataset, public) | Use this function to upload data to Knoema dataset. | null | null | null | |
def delete(dataset):
config = ApiConfig()
client = ApiClient(config.host, config.app_id, config.app_secret)
client.check_correct_host()
client.delete(dataset)
return ('Dataset {} has been deleted successfully'.format(dataset)) | Use this function to delete dataset by it's id. | null | null | null | |
def verify(dataset, publication_date, source, refernce_url):
config = ApiConfig()
client = ApiClient(config.host, config.app_id, config.app_secret)
client.check_correct_host()
client.verify(dataset, publication_date, source, refernce_url) | Use this function to verify a dataset. | null | null | null | |
oplog = self.connection.local['oplog.rs']
if self.ts is None:
cursor = oplog.find().sort('$natural', -1)
obj = cursor[0]
if obj:
self.ts = obj['ts']
else:
# In case no oplogs are present.
self.ts = ... | def start(self) | Starts the OplogWatcher. | 3.609816 | 3.399043 | 1.062009 |
# Compute the document id of the document that will be altered
# (in case of insert, update or delete).
docid = self.__get_id(raw)
op = raw['op']
if op == 'i':
self.insert(ns=ns, docid=docid, raw=raw)
elif op == 'u':
self.update(ns=ns, do... | def process_op(self, ns, raw) | Processes a single operation from the oplog.
Performs a switch by raw['op']:
"i" insert
"u" update
"d" delete
"c" db cmd
"db" declares presence of a database
"n" no op | 2.940027 | 2.348738 | 1.251748 |
bin_ = min(bins, key=lambda bin_: bin_.weights_sum)
bin_.add(item, weight)
return frozenbag(frozenbag(bin_.items) for bin_ in bins) | def multi_way_partitioning(items, bin_count): #TODO rename bin_count -> bins
'''
Greedily divide weighted items equally across bins.
This approximately solves a multi-way partition problem, minimising the
difference between the largest and smallest sum of weights in a bin.
Parameters
---------... | Greedily divide weighted items equally across bins.
This approximately solves a multi-way partition problem, minimising the
difference between the largest and smallest sum of weights in a bin.
Parameters
----------
items : ~typing.Iterable[~typing.Tuple[~typing.Any, float]]
Weighted items ... | 5.524887 | 8.465307 | 0.65265 |
graph.add_nodes_from(toset)
graph.add_edges_from(windowed(reversed(toset)))
# No cycles allowed
if not nx.is_directed_acyclic_graph(graph): #TODO could rely on NetworkXUnfeasible https://networkx.github.io/documentation/networkx-1.9/reference/generated/networkx.algorithms.dag.topological_sort.h... | def toset_from_tosets(*tosets): # Note: a setlist is perfect representation of a toset as it's totally ordered and it's a set, i.e. a toset
'''
Create totally ordered set (toset) from tosets.
These tosets, when merged, form a partially ordered set. The linear
extension of this poset, a toset, is retur... | Create totally ordered set (toset) from tosets.
These tosets, when merged, form a partially ordered set. The linear
extension of this poset, a toset, is returned.
.. warning:: untested
Parameters
----------
tosets : Iterable[~collections_extended.setlist]
Tosets to merge.
Raises
... | 4.430452 | 5.033979 | 0.880109 |
if not len(groupKeys) == len(groupLimits)-1:
raise ValueError('len(groupKeys) must equal len(grouplimits)-1 got \nkeys:{0} \nlimits:{1}'.format(groupKeys,
groupLimits))
if math.isnan(value):
... | def _sortValueIntoGroup(groupKeys, groupLimits, value) | returns the Key of the group a value belongs to
:param groupKeys: a list/tuple of keys ie ['1-3', '3-5', '5-8', '8-10', '10+']
:param groupLimits: a list of the limits for the group [1,3,5,8,10,float('inf')] note the first value is an absolute
minimum and the last an absolute maximum. You can therefore use ... | 3.521891 | 3.378314 | 1.0425 |
if size == 'small':
self._set_size_small()
elif size == 'large':
self._set_size_large()
else:
raise ValueError('Size must be large or small') | def set_size(self, size) | choose a preset size for the plot
:param size: 'small' for documents or 'large' for presentations | 2.687771 | 2.518682 | 1.067134 |
'''For the specified axes, sets the color of the frame, major ticks,
tick labels, axis labels, title and legend
'''
ax = self.ax
for tl in ax.get_xticklines() + ax.get_yticklines():
tl.set_color(color)
for spine in ax.spines:
ax.spine... | def set_foregroundcolor(self, color) | For the specified axes, sets the color of the frame, major ticks,
tick labels, axis labels, title and legend | 2.022585 | 1.704996 | 1.186269 |
'''Sets the background color of the current axes (and legend).
Use 'None' (with quotes) for transparent. To get transparent
background on saved figures, use:
pp.savefig("fig1.svg", transparent=True)
'''
ax = self.ax
ax.patch.set_facecolor(color)... | def set_backgroundcolor(self, color) | Sets the background color of the current axes (and legend).
Use 'None' (with quotes) for transparent. To get transparent
background on saved figures, use:
pp.savefig("fig1.svg", transparent=True) | 7.114439 | 2.204717 | 3.226917 |
firstObject = self.objectList[0]
if isinstance(firstObject, ac.Planet):
if 'star.' in param:
return _starPars[param[5:]] # cut off star. part
else:
return _planetPars[param]
elif isinstance(firstObject, ac.Star):
ret... | def _getParLabelAndUnit(self, param) | checks param to see if it contains a parent link (ie star.) then returns the correct unit and label for the
job from the parDicts
:return: | 5.269151 | 5.226017 | 1.008254 |
resultsByClass = self._genEmptyResults()
for astroObject in self.objectList:
sortKey = self._getSortKey(astroObject)
resultsByClass[sortKey] += 1
return resultsByClass | def _processResults(self) | Checks each result can meet SNR requirments, adds to count
:return: | 7.95503 | 7.210464 | 1.103262 |
resultsByClass = self.resultsByClass
try:
if resultsByClass['Uncertain'] == 0: # remove uncertain tag if present and = 0
resultsByClass.pop('Uncertain', None)
except KeyError:
pass
plotData = list(zip(*resultsByClass.items())) # (label... | def _getPlotData(self) | Turns the resultsByClass Dict into a list of bin groups skipping the uncertain group if empty
return: (label list, ydata list)
:rtype: tuple(list(str), list(float)) | 6.884244 | 3.957484 | 1.739551 |
allowedKeys = self._allowedKeys
keysDict = OrderedDict() # Note: list comprehension take 0 then 2 then 1 then 3 etc for some reason. we want strict order
for k in allowedKeys:
keysDict[k] = 0
resultsByClass = keysDict
return resultsByClass | def _genEmptyResults(self) | Uses allowed keys to generate a empty dict to start counting from
:return: | 16.490347 | 13.326323 | 1.237427 |
value = eval('planet.'+self._planetProperty)
# TODO some sort of data validation, either before or using try except
if self.unit is not None:
try:
value = value.rescale(self.unit)
except AttributeError: # either nan or unitless
... | def _getSortKey(self, planet) | Takes a planet and turns it into a key to be sorted by
:param planet:
:return: | 16.923229 | 17.184954 | 0.98477 |
binlimits = self._binlimits
allowedKeys = []
midbinlimits = binlimits
if binlimits[0] == -float('inf'):
midbinlimits = binlimits[1:] # remove the bottom limit
allowedKeys.append('<{0}'.format(midbinlimits[0]))
if binlimits[-1] == float('inf'):... | def _genKeysBins(self) | Generates keys from bins, sets self._allowedKeys normally set in _classVariables | 2.898314 | 2.667737 | 1.086432 |
if unit is None:
unit = self._getParLabelAndUnit(param)[1] # use the default unit defined in this class
self._xaxis_unit = unit
self._xaxis = self._set_axis(param, unit)
if label is None:
self.xlabel = self._gen_label(param, unit)
else:
... | def set_xaxis(self, param, unit=None, label=None) | Sets the value of use on the x axis
:param param: value to use on the xaxis, should be a variable or function of the objects in objectList. ie 'R'
for the radius variable and 'calcDensity()' for the calcDensity function
:param unit: the unit to scale the values to, None will use the default
... | 4.861671 | 4.435606 | 1.096056 |
if unit is None:
unit = self._getParLabelAndUnit(param)[1] # use the default unit defined in this class
self._yaxis_unit = unit
self._yaxis = self._set_axis(param, unit)
if label is None:
self.ylabel = self._gen_label(param, unit)
else:
... | def set_yaxis(self, param, unit=None, label=None) | Sets the value of use on the yaxis
:param param: value to use on the yaxis, should be a variable or function of the objects in objectList. ie 'R'
for the radius variable and 'calcDensity()' for the calcDensity function
:param unit: the unit to scale the values to
:type unit: quantities ... | 5.061086 | 5.08765 | 0.994779 |
axisValues = []
for astroObject in self.objectList:
try:
value = eval('astroObject.{0}'.format(param))
except ac.HierarchyError: # ie trying to call planet.star and one planet is a lone ranger
value = np.nan
if unit is None: ... | def _set_axis(self, param, unit) | this should take a variable or a function and turn it into a list by evaluating on each planet | 10.934277 | 9.502334 | 1.150694 |
# TODO allow a colour set per another variable
self._marker_color = color
self._edge_color = edgecolor | def set_marker_color(self, color='#3ea0e4', edgecolor='k') | set the marker color used in the plot
:param color: matplotlib color (ie 'r', '#000000') | 16.83783 | 18.392044 | 0.915495 |
discovery_methods = {}
discovery_years = {}
nan_list = []
# Initial Loop to get keys
for planet in self.planet_list:
if 'Solar System' in planet.params['list'] and self.skip_solar_system_planets:
continue
try:
dis... | def setup_keys(self) | Build the initial data dictionary to store the values | 3.84732 | 3.662032 | 1.050597 |
if method_labels is None:
method_labels = self.methods_to_plot
plot_matrix, year_list, discovery_years = self.generate_data()
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ind = np.arange(len(year_list))
# output from seaborn.color_palette("Se... | def plot(self, method_labels=None, exodata_credit=True) | :param method_labels: list of legend labels for the methods, i.e. give
'Radial Velocity' rather than 'RV'
:return: | 4.34296 | 4.336095 | 1.001583 |
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print("Normalized confusion matrix")
else:
print('Confusion matrix, without normalization')
print(cm)
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_m... | def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=plt.cm.Blues) | This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`. | 1.086309 | 1.086681 | 0.999658 |
return all(map(lambda x: isinstance(x, (int, float, long)), s.values())) | def is_zsettable(s) | quick check that all values in a dict are reals | 4.59425 | 3.405482 | 1.349075 |
return self.client.ltrim(self.name, start, stop - 1) | def trim(self, start, stop) | Trim the list to the specified range of elements. | 8.320351 | 9.883188 | 0.841869 |
count = self.client.lrem(self.name, value, num=count)
if not count:
raise ValueError("%s not in list" % value)
return count | def remove(self, value, count=1) | Remove occurences of ``value`` from the list.
:keyword count: Number of matching values to remove.
Default is to remove a single value. | 5.053455 | 8.153478 | 0.619791 |
if not self.client.srem(self.name, member):
raise KeyError(member) | def remove(self, member) | Remove element from set; it must be a member.
:raises KeyError: if the element is not a member. | 7.515504 | 7.778785 | 0.966154 |
member = self.client.spop(self.name)
if member is not None:
return member
raise KeyError() | def pop(self) | Remove and return an arbitrary set element.
:raises KeyError: if the set is empty. | 7.838932 | 8.202017 | 0.955732 |
if isinstance(other, self.__class__):
return self.client.sunion([self.name, other.name])
else:
return self._as_set().union(other) | def union(self, other) | Return the union of sets as a new set.
(i.e. all elements that are in either set.)
Operates on either redish.types.Set or __builtins__.set. | 4.581062 | 3.749323 | 1.221837 |
if isinstance(other, self.__class__):
return self.client.sunionstore(self.name, [self.name, other.name])
else:
return map(self.add, other) | def update(self, other) | Update this set with the union of itself and others. | 4.742308 | 4.268248 | 1.111067 |
if isinstance(other, self.__class__):
return self.client.sinter([self.name, other.name])
else:
return self._as_set().intersection(other) | def intersection(self, other) | Return the intersection of two sets as a new set.
(i.e. all elements that are in both sets.)
Operates on either redish.types.Set or __builtins__.set. | 4.272982 | 3.736511 | 1.143575 |
return self.client.sinterstore(self.name, [self.name, other.name]) | def intersection_update(self, other) | Update the set with the intersection of itself and another. | 7.002424 | 6.992667 | 1.001395 |
if all([isinstance(a, self.__class__) for a in others]):
return self.client.sdiff([self.name] + [other.name for other in others])
else:
othersets = filter(lambda x: isinstance(x, set), others)
otherTypes = filter(lambda x: isinstance(x, self.__class__), other... | def difference(self, *others) | Return the difference of two or more sets as a new :class:`set`.
(i.e. all elements that are in this set but not the others.)
Operates on either redish.types.Set or __builtins__.set. | 3.078997 | 2.993834 | 1.028446 |
return self.client.sdiffstore(self.name, [self.name, other.name]) | def difference_update(self, other) | Remove all elements of another set from this set. | 8.214013 | 8.061095 | 1.01897 |
return self.client.zadd(self.name, member, score) | def add(self, member, score) | Add the specified member to the sorted set, or update the score
if it already exist. | 4.74013 | 3.846312 | 1.232383 |
if not self.client.zrem(self.name, member):
raise KeyError(member) | def remove(self, member) | Remove member. | 7.623734 | 6.160178 | 1.237583 |
return self.client.zincrby(self.name, member, amount) | def increment(self, member, amount=1) | Increment the score of ``member`` by ``amount``. | 6.239008 | 5.08749 | 1.226343 |
return self.client.zrangebyscore(self.name, min, max, num=num,
withscores=withscores) | def range_by_score(self, min, max, num=None, withscores=False) | Return all the elements with score >= min and score <= max
(a range query) from the sorted set. | 2.918647 | 2.958941 | 0.986382 |
try:
val = self[key]
except KeyError:
if len(args):
return args[0]
if "default" in kwargs:
return kwargs["default"]
raise
try:
del(self[key])
except KeyError:
pass
r... | def pop(self, key, *args, **kwargs) | Remove specified key and return the corresponding value.
:keyword default: If key is not found, ``default`` is returned if given,
otherwise :exc:`KeyError` is raised. | 2.416232 | 2.511882 | 0.961921 |
return self.maxsize and len(self.list) >= self.maxsize or False | def full(self) | Return ``True`` if the queue is full, ``False``
otherwise (not reliable!).
Only applicable if :attr:`maxsize` is set. | 13.191041 | 10.282168 | 1.282905 |
if not block:
return self.get_nowait()
item = self._bpop([self.name], timeout=timeout)
if item is not None:
return item
raise Empty | def get(self, block=True, timeout=None) | Remove and return an item from the queue.
If optional args ``block`` is ``True`` and ``timeout`` is
``None`` (the default), block if necessary until an item is
available. If ``timeout`` is a positive number, it blocks at
most ``timeout`` seconds and raises the :exc:`Queue.Empty` except... | 5.26326 | 4.845141 | 1.086296 |
if self.full():
raise Full()
self._append(item) | def put(self, item, **kwargs) | Put an item into the queue. | 8.936568 | 6.781602 | 1.317767 |
self._dict[member] += amount
return self._dict[member] | def increment(self, member, amount=1) | Increment the score of ``member`` by ``amount``. | 5.558607 | 5.853174 | 0.949674 |
data = self.items()
keys = [r[1] for r in data]
start = bisect.bisect_left(keys, min)
end = bisect.bisect_right(keys, max, start)
return self._as_set()[start:end] | def range_by_score(self, min, max) | Return all the elements with score >= min and score <= max
(a range query) from the sorted set. | 3.891019 | 3.876568 | 1.003728 |
if not self.connected:
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.connect(self.address)
self.connected = True | def connect(self) | Connect to the given socket | 2.093815 | 1.944639 | 1.076711 |
self._send_data(int_to_hex(len(data)))
self._send_data(data) | def send(self, data) | Send a formatted message to the ADB server | 5.251048 | 5.970686 | 0.879471 |
total_sent = 0
while total_sent < len(data):
# Send only the bytes that haven't been
# sent yet
sent = self.socket.send(data[total_sent:].encode("ascii"))
if sent == 0:
self.close()
raise RuntimeError("Socket conn... | def _send_data(self, data) | Send data to the ADB server | 4.068805 | 4.03822 | 1.007574 |
if self.receive_fixed_length(4) != "OKAY":
raise SocketError("Socket communication failed: "
"the server did not return a valid response")
# The time at which the receive starts
start_time = time.clock()
output = ""
while True... | def receive_until_end(self, timeout=None) | Reads and blocks until the socket closes
Used for the "shell" command, where STDOUT and STDERR
are just redirected to the terminal with no length | 4.176089 | 4.146751 | 1.007075 |
for name, data in PARAMETERS.iteritems():
kwargs[name] = kwargs.get(name) or getattr(self, name)
if 'transform' in data:
kwargs[name] = data['transform'](kwargs[name])
return f(self, *args, **kwargs) | def defaults(f, self, *args, **kwargs) | For ``PARAMETERS`` keys, replace None ``kwargs`` with ``self`` attr values.
Should be applied on the top of any decorator stack so other decorators see
the "right" kwargs.
Will also apply transformations found in ``TRANSFORMS``. | 3.311182 | 3.34493 | 0.989911 |
def requires(f, self, *args, **kwargs):
missing = filter(lambda x: kwargs.get(x) is None, params)
if missing:
msgs = ", ".join([PARAMETERS[x]['msg'] for x in missing])
raise ValueError("Missing the following parameters: %s" % msgs)
return f(self, *args, **kwargs)... | def requires(*params) | Raise ValueError if any ``params`` are omitted from the decorated kwargs.
None values are considered omissions.
Example usage on an AWS() method:
@requires('zone', 'security_groups')
def my_aws_method(self, custom_args, **kwargs):
# We'll only get here if 'kwargs' contained non-No... | 3.603776 | 4.185661 | 0.860981 |
# Memoize entire list of groups
if not hasattr(self, '_security_groups'):
self._security_groups = {}
for group in self.get_all_security_groups():
self._security_groups[group.name] = group.id
return self._security_groups[name] | def get_security_group_id(self, name) | Take name string, give back security group ID.
To get around VPC's API being stupid. | 2.827523 | 2.688595 | 1.051673 |
# TODO: we have to do this here since we are monkeypatching Instance.
# If we switch to custom Instance (sub)class then we could do it in the
# object, provided it has access to the configuration data.
if instance.subnet_id:
# Account for omitted 'subnet-'
... | def get_instance_subnet_name(self, instance) | Return a human readable name for given instance's subnet, or None.
Uses stored config mapping of subnet IDs to names. | 13.68549 | 12.21993 | 1.119932 |
for subnet_id, subnet_name in self.config['subnets'].iteritems():
if subnet_name == name:
return subnet_id
return name | def get_subnet_id(self, name) | Return subnet ID for given ``name``, if it exists.
E.g. with a subnet mapping of ``{'abc123': 'ops', '67fd56': 'prod'}``,
``get_subnet_id('ops')`` would return ``'abc123'``. If the map has
non-unique values, the first matching key will be returned.
If no match is found, the given ``nam... | 3.470334 | 3.548691 | 0.977919 |
# Create
creating = "Creating '%s' (a %s instance of %s)" % (
hostname, kwargs['size'], kwargs['ami']
)
with self.msg(creating):
instance = self._create(hostname, kwargs)
# Name
with self.msg("Tagging as '%s'" % hostname):
try... | def create(self, hostname, **kwargs) | Create new EC2 instance named ``hostname``.
You may specify keyword arguments matching those of ``__init__`` (e.g.
``size``, ``ami``) to override any defaults given when the object was
created, or to fill in parameters not given at initialization time.
Additional parameters that are in... | 6.334318 | 6.023996 | 1.051514 |
try:
reservations = self.get_all_instances(filters={'tag:Name': [arg]})
instance = reservations[0].instances[0]
except IndexError:
try:
instance = self.get_all_instances([arg])[0].instances[0]
except (_ResponseError, IndexError):
... | def get(self, arg) | Return instance object with given EC2 ID or nametag. | 4.893456 | 4.196341 | 1.166124 |
instance = self.get(arg)
filters = {'attachment.instance-id': instance.id}
if device is not None:
filters['attachment.device'] = device
return self.get_all_volumes(filters=filters) | def get_volumes_for_instance(self, arg, device=None) | Return all EC2 Volume objects attached to ``arg`` instance name or ID.
May specify ``device`` to limit to the (single) volume attached as that
device. | 3.021197 | 2.909894 | 1.03825 |
instance = self.get(arg)
with self.msg("Terminating %s (%s): " % (instance.name, instance.id)):
instance.rename("old-%s" % instance.name)
instance.terminate()
while instance.state != 'terminated':
time.sleep(5)
self.log(".", en... | def terminate(self, arg) | Terminate instance with given EC2 ID or nametag. | 5.157668 | 4.518069 | 1.141565 |
data, stat = self.zk.get(self.path)
if not len(data):
return {}, stat.version
if self.OLD_SEPARATOR in data:
return self._get_old()
return json.loads(data), stat.version | def _get(self) | get and parse data stored in self.path. | 7.136172 | 5.806317 | 1.229036 |
self.zk.set(self.path, json.dumps(data), version) | def _set(self, data, version) | serialize and set data to self.path. | 7.427697 | 4.984676 | 1.490106 |
def _deserialize(d):
if not len(d):
return {}
return dict(l.split(self.OLD_SEPARATOR) for l in d.split('\n'))
data, stat = self.zk.get(self.path)
return _deserialize(data.decode('utf8')), stat.version | def _get_old(self) | get and parse data stored in self.path. | 6.387663 | 5.334023 | 1.197532 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.