function stringlengths 11 56k | repo_name stringlengths 5 60 | features list |
|---|---|---|
def preprocess_data(config, force=False):
"""
Ensures that all the necessary data have been inserted in db from the raw
opendata files.
:params config: A config dictionary.
:params force: Whether to force rebuild or not.
:return bool: Whether data have been built or not.
"""
# Check if ... | Phyks/Flatisfy | [
16,
6,
16,
4,
1492106528
] |
def get_band_edges():
"""
Calculate the band edge locations relative to the vacuum level
for a semiconductor. For a metal, returns the fermi level.
Returns:
edges (dict): {'up_cbm': , 'up_vbm': , 'dn_cbm': , 'dn_vbm': , 'efermi'}
"""
# Vacuum level energy from LOCPOT.
locpot = Locpo... | henniggroup/MPInterfaces | [
58,
46,
58,
8,
1435027973
] |
def plot_local_potential(axis=2, ylim=(-20, 0), fmt='pdf'):
"""
Plot data from the LOCPOT file along any of the 3 primary axes.
Useful for determining surface dipole moments and electric
potentials on the interior of the material.
Args:
axis (int): 0 = x, 1 = y, 2 = z
ylim (tuple): ... | henniggroup/MPInterfaces | [
58,
46,
58,
8,
1435027973
] |
def plot_band_structure(ylim=(-5, 5), draw_fermi=False, fmt="pdf"):
"""
Plot a standard band structure with no projections. Requires
EIGENVAL, OUTCAR and KPOINTS files in the current working directory.
Args:
ylim (tuple): minimum and maximum potentials for the plot's y-axis.
draw_fermi ... | henniggroup/MPInterfaces | [
58,
46,
58,
8,
1435027973
] |
def plot_elt_projected_bands(ylim=(-5, 5), fmt='pdf'):
"""
Plot separate band structures for each element where the size of the
markers indicates the elemental character of the eigenvalue.
Args:
ylim (tuple): minimum and maximum energies for the plot's
y-axis.
fmt (str): mat... | henniggroup/MPInterfaces | [
58,
46,
58,
8,
1435027973
] |
def get_effective_mass():
"""
This function is in a beta stage, and its results are not
guaranteed to be useful.
Finds effective masses from a band structure, using parabolic
fitting to determine the band curvature at the CBM
for electrons and at the VBM for holes. This curvature enters
the... | henniggroup/MPInterfaces | [
58,
46,
58,
8,
1435027973
] |
def get_fermi_velocities():
"""
Calculates the fermi velocity of each band that crosses the fermi
level, according to v_F = dE/(h_bar*dk).
Returns:
fermi_velocities (list). The absolute values of the
adjusted slopes of each band, in Angstroms/s.
"""
vr = Vasprun('vasprun.xm... | henniggroup/MPInterfaces | [
58,
46,
58,
8,
1435027973
] |
def __unicode__(self):
return _("%(title)s, from %(author)s") % {
'title': self.title,
'author': self.author.username ,
} | n1k0/djortunes | [
7,
1,
7,
4,
1257240065
] |
def get_absolute_url(self):
"Retrieves the absolute django url of a fortune"
return ('fortune_detail', (), {
'slug': self.slug,
'year': self.pub_date.year,
'month': self.pub_date.month,
'day': self.pub_date.day
}) | n1k0/djortunes | [
7,
1,
7,
4,
1257240065
] |
def initialize(cfg):
# import and initialize plugins
plugin_utils.initialize_plugins(cfg['plugin_dirs'], cfg['load_plugins'])
# entryparser callback is run here first to allow other
# plugins register what file extensions can be used
extensions = tools.run_callback(
"entryparser",
{... | willkg/douglas | [
2,
3,
2,
14,
1385584147
] |
def __init__(self, config, environ, data=None):
"""Sets configuration and environment and creates the Request
object.
:param config: dict containing the configuration variables.
:param environ: dict containing the environment variables.
:param data: dict containing data variable... | willkg/douglas | [
2,
3,
2,
14,
1385584147
] |
def cleanup(self):
"""This cleans up Douglas after a run.
This should be called when Douglas has done everything it
needs to do before exiting.
"""
# Log some useful stuff for debugging.
log = logging.getLogger()
response = self.get_response()
log.debug('... | willkg/douglas | [
2,
3,
2,
14,
1385584147
] |
def get_response(self):
"""Returns the Response object associated with this Request.
"""
return self._request.get_response() | willkg/douglas | [
2,
3,
2,
14,
1385584147
] |
def run_render_one(self, url, headers):
"""Renders a single page from the blog.
:param url: the url to render--this has to be relative to the
base url for this blog.
:param headers: True if you want headers to be rendered and
False if not.
""... | willkg/douglas | [
2,
3,
2,
14,
1385584147
] |
def run_collectstatic(self):
"""Collects static files and copies them to compiledir"""
# FIXME: rewrite using tools.get_static_files(cfg)
cfg = self._request.get_configuration()
self.initialize()
# Copy over static files
print 'Copying over static files ...'
d... | willkg/douglas | [
2,
3,
2,
14,
1385584147
] |
def __init__(self, environ=None, start_response=None, configini=None):
"""
Make WSGI app for Douglas.
:param environ: FIXME
:param start_response: FIXME
:param configini: Dict encapsulating information from a
``config.ini`` file or any other property
... | willkg/douglas | [
2,
3,
2,
14,
1385584147
] |
def __call__(self, env, start_response):
return [self.run_douglas(env, start_response)] | willkg/douglas | [
2,
3,
2,
14,
1385584147
] |
def douglas_app_factory(global_config, **local_config):
"""App factory for paste.
:returns: WSGI application
"""
conf = global_config.copy()
conf.update(local_config)
conf.update(dict(local_config=local_config, global_config=global_config))
if "configpydir" in conf:
sys.path.inser... | willkg/douglas | [
2,
3,
2,
14,
1385584147
] |
def __init__(self, request, env):
"""Wraps an environment (which is a dict) and a request.
:param request: the Request object for this request.
:param env: the environment dict for this request.
"""
dict.__init__(self)
self._request = request
self.update(env) | willkg/douglas | [
2,
3,
2,
14,
1385584147
] |
def __init__(self, config, environ, data):
"""Sets configuration and environment.
Creates the Response object which handles all output related
functionality.
:param config: dict containing configuration variables.
:param environ: dict containing environment variables.
:... | willkg/douglas | [
2,
3,
2,
14,
1385584147
] |
def buffer_input_stream(self):
"""
Buffer the input stream in a StringIO instance. This is done
to have a known/consistent way of accessing incomming data.
For example the input stream passed by mod_python does not
offer the same functionallity as ``sys.stdin``.
"""
... | willkg/douglas | [
2,
3,
2,
14,
1385584147
] |
def get_response(self):
"""Returns the Response for this request."""
return self._response | willkg/douglas | [
2,
3,
2,
14,
1385584147
] |
def get_form(self):
"""Returns the form data submitted by the client. The
``form`` instance is created only when requested to prevent
overhead and unnecessary consumption of the input stream.
:returns: a ``cgi.FieldStorage`` instance.
"""
if self._form is None:
... | willkg/douglas | [
2,
3,
2,
14,
1385584147
] |
def get_configuration(self):
"""Returns the *actual* configuration dict. The configuration
dict holds values that the user sets in their ``config.py``
file.
Modifying the contents of the dict will affect all downstream
processing.
"""
return self._configuration | willkg/douglas | [
2,
3,
2,
14,
1385584147
] |
def get_data(self):
"""Returns the *actual* data dict. Holds run-time data which
is created and transformed by douglas during execution.
Modifying the contents of the dict will affect all downstream
processing.
"""
return self._data | willkg/douglas | [
2,
3,
2,
14,
1385584147
] |
def add_data(self, d):
"""Takes in a dict and adds/overrides values in the existing
data dict with the new values.
"""
self._data.update(d) | willkg/douglas | [
2,
3,
2,
14,
1385584147
] |
def __getattr__(self, name):
if name in ["config", "configuration", "conf"]:
return self._configuration
if name == "data":
return self._data
if name == "http":
return self._http
raise AttributeError(name) | willkg/douglas | [
2,
3,
2,
14,
1385584147
] |
def __init__(self, request):
"""Sets the ``Request`` object that leaded to this response.
Creates a ``StringIO`` that is used as a output buffer.
"""
self._request = request
self._out = StringIO()
self._headers_sent = False
self.headers = {}
self.status = ... | willkg/douglas | [
2,
3,
2,
14,
1385584147
] |
def set_status(self, status):
"""Sets the status code for this response. The status should
be a valid HTTP response status.
Examples:
>>> resp.set_status("200 OK")
>>> resp.set_status("404 Not Found")
:param status: the status string.
"""
self.status ... | willkg/douglas | [
2,
3,
2,
14,
1385584147
] |
def add_header(self, key, value):
"""Populates the HTTP header with lines of text. Sets the
status code on this response object if the given argument list
containes a 'Status' header.
Example:
>>> resp.add_header("Content-type", "text/plain")
>>> resp.add_header("Conte... | willkg/douglas | [
2,
3,
2,
14,
1385584147
] |
def send_headers(self, out):
"""Send HTTP Headers to the given output stream.
.. Note::
This prints the headers and then the ``\\n\\n`` that
separates headers from the body.
:param out: The file-like object to print headers to.
"""
out.write("Status: %s... | willkg/douglas | [
2,
3,
2,
14,
1385584147
] |
def blosxom_handler(request):
"""This is the default blosxom handler.
It calls the renderer callback to get a renderer. If there is no
renderer, it uses the blosxom renderer.
It calls the pathinfo callback to process the path_info http
variable.
It calls the filelist callback to build a list... | willkg/douglas | [
2,
3,
2,
14,
1385584147
] |
def blosxom_file_list_handler(args):
"""This is the default handler for getting entries. It takes the
request object in and figures out which entries based on the
default behavior that we want to show and generates a list of
EntryBase subclass objects which it returns.
:param args: dict containing... | willkg/douglas | [
2,
3,
2,
14,
1385584147
] |
def blosxom_truncate_list_handler(args):
"""If ``config["num_entries"]`` is not 0 and ``data["truncate"]``
is not 0, then this truncates ``args["entry_list"]`` by
``config["num_entries"]``.
:param args: args dict with ``request`` object and ``entry_list``
list of entries
:returns:... | willkg/douglas | [
2,
3,
2,
14,
1385584147
] |
def route_file(cfg, url, data):
path = os.path.join(cfg['datadir'], data['path'].lstrip('/'))
ext = tools.what_ext(cfg['extensions'].keys(), path)
if ext:
data.update({
'root_datadir': path + '.' + ext,
'bl_type': 'entry'
})
return data | willkg/douglas | [
2,
3,
2,
14,
1385584147
] |
def blosxom_process_path_info(args):
"""Process HTTP ``PATH_INFO`` for URI according to path
specifications, fill in data dict accordingly.
The paths specification looks like this:
- ``/foo.html`` and ``/cat/foo.html`` - file foo.* in / and /cat
- ``/cat`` - category
- ``/2002`` - category (if... | willkg/douglas | [
2,
3,
2,
14,
1385584147
] |
def __init__(
self,
plotly_name="enabled",
parent_name="densitymapbox.colorbar.tickformatstop",
**kwargs | plotly/python-api | [
13052,
2308,
13052,
1319,
1385013188
] |
def company_prefix(self) -> str:
"""
:example: 'ห้างหุ้นส่วนจำกัด'
"""
return self.random_element(self.company_prefixes) | joke2k/faker | [
15491,
1733,
15491,
19,
1352761209
] |
def company_limited_suffix(self) -> str:
"""
:example: 'จำกัด'
"""
return self.random_element(self.company_limited_suffixes) | joke2k/faker | [
15491,
1733,
15491,
19,
1352761209
] |
def __init__(self, locale=None): # noqa: E501
"""PreferencesV30Rc1 - a model defined in Swagger""" # noqa: E501
self._locale = None
self.discriminator = None
if locale is not None:
self.locale = locale | Royal-Society-of-New-Zealand/NZ-ORCID-Hub | [
13,
7,
13,
28,
1486087622
] |
def locale(self):
"""Gets the locale of this PreferencesV30Rc1. # noqa: E501
:return: The locale of this PreferencesV30Rc1. # noqa: E501
:rtype: str
"""
return self._locale | Royal-Society-of-New-Zealand/NZ-ORCID-Hub | [
13,
7,
13,
28,
1486087622
] |
def locale(self, locale):
"""Sets the locale of this PreferencesV30Rc1.
:param locale: The locale of this PreferencesV30Rc1. # noqa: E501
:type: str
"""
allowed_values = ["AR", "CS", "DE", "EN", "ES", "FR", "IT", "JA", "KO", "PT", "RU", "ZH_CN", "ZH_TW", "XX"] # noqa: E501
... | Royal-Society-of-New-Zealand/NZ-ORCID-Hub | [
13,
7,
13,
28,
1486087622
] |
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict()) | Royal-Society-of-New-Zealand/NZ-ORCID-Hub | [
13,
7,
13,
28,
1486087622
] |
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, PreferencesV30Rc1):
return False
return self.__dict__ == other.__dict__ | Royal-Society-of-New-Zealand/NZ-ORCID-Hub | [
13,
7,
13,
28,
1486087622
] |
def option_list(self):
"""
For compatibility with Django<1.10
"""
try:
return BaseCommand.option_list + (
make_option('-c', '--clean', **clean_option_kwargs)
)
except:
return None | hzdg/django-staticbuilder | [
76,
4,
76,
6,
1349907733
] |
def handle(self, *args, **options):
self.clean = options['clean']
self.verbosity = int(options.get('verbosity', '1'))
build_dir = settings.STATICBUILDER_BUILD_ROOT
if not build_dir:
raise ImproperlyConfigured('STATICBUILDER_BUILD_ROOT must be set.')
# Copy the stati... | hzdg/django-staticbuilder | [
76,
4,
76,
6,
1349907733
] |
def collect_for_build(self, build_dir):
with patched_finders():
with patched_settings(STATICBUILDER_COLLECT_BUILT=False):
# Patch the static files storage used by collectstatic
storage = BuiltFileStorage()
old_storage = djstorage.staticfiles_storage
... | hzdg/django-staticbuilder | [
76,
4,
76,
6,
1349907733
] |
def clean_built(self, storage):
"""
Clear any static files that aren't from the apps.
"""
build_dirs, built_files = self.find_all(storage)
found_files = set()
for finder in finders.get_finders():
for path, s in finder.list([]):
# Prefix the r... | hzdg/django-staticbuilder | [
76,
4,
76,
6,
1349907733
] |
def queryValue(key, name):
value, type_id = QueryValueEx(key, name)
return value | ActiveState/code | [
1884,
686,
1884,
41,
1500923597
] |
def main():
try:
path = r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment'
reg = ConnectRegistry(None, HKEY_LOCAL_MACHINE)
key = OpenKey(reg, path, 0, KEY_ALL_ACCESS) | ActiveState/code | [
1884,
686,
1884,
41,
1500923597
] |
def password_check(password):
"""
Verify the strength of 'password'
Returns a dict indicating the wrong criteria
A password is considered strong if:
12 characters length or more
1 digit or more
1 symbol or more
1 uppercase letter or more
1 lowercase letter or more... | usnistgov/corr | [
6,
4,
6,
34,
1458070055
] |
def create_admin(email, password, fname, lname):
"""
Creates the first admin user
Returns boolean to indicate if the account was created or not
"""
if not password_check(password):
return False
else:
hash_pwd = hashlib.sha256(('CoRRPassword_%s'%password).encode("ascii")).hexdiges... | usnistgov/corr | [
6,
4,
6,
34,
1458070055
] |
def is_token_allowed(token):
'''
Only allow valid tokens which are not stop words
and punctuation symbols.
'''
# if (not token or not token.string.strip() or token.is_stop or token.is_punct):
if (not token or not token.text.strip() or token.is_stop or token.is_punct):
retu... | bflaven/BlogArticlesExamples | [
6,
4,
6,
49,
1442137714
] |
def main(args):
if len(args) != 2:
print("Usage: python project-diff.py [path-to-project-1] [path-to-project-2]")
return
dir1 = args[0]
dir2 = args[1]
project1 = collect_text_files(dir1)
project2 = collect_text_files(dir2)
files_only_in_1 = []
files_only_in_2 = []
files_in_both = []
perform... | blakeohare/crayon | [
110,
10,
110,
59,
1425530602
] |
def collect_text_files(root):
output = {}
root = root.replace('\\', '/')
if root.endswith('/'):
root = root[:-1]
collect_text_files_impl(root, '', output)
return output | blakeohare/crayon | [
110,
10,
110,
59,
1425530602
] |
def is_text_file(path):
ext = get_file_extension(path)
return ext not in FILE_EXTENSION_IGNORE_LIST | blakeohare/crayon | [
110,
10,
110,
59,
1425530602
] |
def perform_diff(text_1, text_2):
if text_1 == text_2:
return []
lines_1 = text_1.split('\n')
lines_2 = text_2.split('\n')
trimmed_front = 0
trimmed_back = 0
# Remove identical lines at the beginning and end of the file
while len(lines_1) > trimmed_front and len(lines_2) > trimmed_front and lines_1... | blakeohare/crayon | [
110,
10,
110,
59,
1425530602
] |
def __init__(self):
self._fpg = None
self._fp = None
self._spg = None
self._sp = None | funkybob/rattle | [
14,
6,
14,
2,
1394944394
] |
def fpg(self):
if self._fpg is None:
self._fpg = rply.ParserGenerator(
[rule.name for rule in lexers.flg.rules],
precedence=[]
)
return self._fpg | funkybob/rattle | [
14,
6,
14,
2,
1394944394
] |
def fp(self):
if self._fp is None:
self._fp = self.fpg.build()
return self._fp | funkybob/rattle | [
14,
6,
14,
2,
1394944394
] |
def spg(self):
if self._spg is None:
self._spg = rply.ParserGenerator(
[rule.name for rule in lexers.slg.rules],
precedence=[]
)
return self._spg | funkybob/rattle | [
14,
6,
14,
2,
1394944394
] |
def sp(self):
if self._sp is None:
self._sp = self.spg.build()
return self._sp | funkybob/rattle | [
14,
6,
14,
2,
1394944394
] |
def default_backups_directory():
return os.path.join(paths.application_data_directory(), 'Backups') | scottrice/Ice | [
818,
108,
818,
209,
1356404560
] |
def shortcuts_backup_path(directory, user, timestamp_format="%Y%m%d%H%M%S"):
"""
Returns the path for a shortcuts.vdf backup file.
This path is in the designated backup directory, and includes a timestamp
before the extension to allow many backups to exist at once.
"""
assert(directory is not None)
retur... | scottrice/Ice | [
818,
108,
818,
209,
1356404560
] |
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config | Azure/azure-sdk-for-python | [
3526,
2256,
3526,
986,
1335285972
] |
def get_long_running_output(pipeline_response):
response = pipeline_response.http_response
deserialized = self._deserialize('MonitoringSettingResource', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized | Azure/azure-sdk-for-python | [
3526,
2256,
3526,
986,
1335285972
] |
def get_long_running_output(pipeline_response):
response = pipeline_response.http_response
deserialized = self._deserialize('MonitoringSettingResource', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized | Azure/azure-sdk-for-python | [
3526,
2256,
3526,
986,
1335285972
] |
def introMessage():
print '=============================================================================================='
print ' Author: Lewis Mervin\n Email: lhm30@cam.ac.uk\n Supervisor: Dr. A. Bender'
print ' Address: Centre For Molecular Informatics, Dept. Chemistry, Lensfield Road, Cambridge CB2 1EW'
print ... | lhm30/PIDGINv2 | [
28,
8,
28,
1,
1442588431
] |
def calcFingerprints(smiles):
m1 = Chem.MolFromSmiles(smiles)
fp = AllChem.GetMorganFingerprintAsBitVect(m1,2, nBits=2048)
binary = fp.ToBitString()
return list(binary) | lhm30/PIDGINv2 | [
28,
8,
28,
1,
1442588431
] |
def arrayFP(inp):
outfp = []
for i in inp:
try:
outfp.append(calcFingerprints(i))
except:
print 'SMILES Parse Error: ' + i
return outfp | lhm30/PIDGINv2 | [
28,
8,
28,
1,
1442588431
] |
def importQuery(in_file):
query = open(in_file).read().splitlines()
#discard IDs, if present
if len(query[0].split()) > 1:
query = [line.split()[0] for line in query]
matrix = np.empty((len(query), 2048), dtype=np.uint8)
smiles_per_core = int(math.ceil(len(query) / N_cores)+1)
chunked_smiles = [query[x:x+smiles... | lhm30/PIDGINv2 | [
28,
8,
28,
1,
1442588431
] |
def getUniprotInfo():
if os.name == 'nt': sep = '\\'
else: sep = '/'
model_info = [l.split('\t') for l in open(os.path.dirname(os.path.abspath(__file__)) + sep + 'classes_in_model.txt').read().splitlines()]
return_dict = {l[0] : l[0:8] for l in model_info}
return return_dict | lhm30/PIDGINv2 | [
28,
8,
28,
1,
1442588431
] |
def getDisgenetInfo():
if os.name == 'nt': sep = '\\'
else: sep = '/'
return_dict1 = dict()
return_dict2 = dict()
disease_file = [l.split('\t') for l in open(os.path.dirname(os.path.abspath(__file__)) + sep + 'DisGeNET_diseases.txt').read().splitlines()]
for l in disease_file:
try:
return_dict1[l[0]].append(... | lhm30/PIDGINv2 | [
28,
8,
28,
1,
1442588431
] |
def getPathwayInfo():
if os.name == 'nt': sep = '\\'
else: sep = '/'
return_dict1 = dict()
return_dict2 = dict()
pathway_info = [l.split('\t') for l in open(os.path.dirname(os.path.abspath(__file__)) + sep + 'biosystems.txt').read().splitlines()]
for l in pathway_info:
try:
return_dict1[l[0]].append(l[1])
... | lhm30/PIDGINv2 | [
28,
8,
28,
1,
1442588431
] |
def getBGhits(threshold):
if os.name == 'nt': sep = '\\'
else: sep = '/'
bg_column = int((threshold*100)+1)
bg_file = [l.split('\t') for l in open(os.path.dirname(os.path.abspath(__file__)) + sep + 'bg_predictions.txt').read().splitlines()]
bg_file.pop(0)
bg_predictions = {l[0] : int(l[bg_column]) for l in bg_fil... | lhm30/PIDGINv2 | [
28,
8,
28,
1,
1442588431
] |
def calcPredictionRatio(preds1,preds2):
preds1_percentage = float(preds1)/float(len(querymatrix1))
preds2_percentage = float(preds2)/float(2000000)
if preds1 == 0 and preds2 == 0: return None
if preds1 == 0: return 999.0, round(preds1_percentage,3), round(preds2_percentage,3)
if preds2 == 0: return 0.0, round(pred... | lhm30/PIDGINv2 | [
28,
8,
28,
1,
1442588431
] |
def open_Model(mod):
if os.name == 'nt': sep = '\\'
else: sep = '/'
with zipfile.ZipFile(os.path.dirname(os.path.abspath(__file__)) + sep + 'models' + sep + mod + '.pkl.zip', 'r') as zfile:
with zfile.open(mod + '.pkl', 'r') as fid:
clf = cPickle.load(fid)
return clf | lhm30/PIDGINv2 | [
28,
8,
28,
1,
1442588431
] |
def doTargetPrediction(pickled_model_name):
if os.name == 'nt': sep = '\\'
else: sep = '/'
mod = pickled_model_name.split(sep)[-1].split('.')[0]
clf = open_Model(mod)
preds1 = sum(clf.predict_proba(querymatrix1)[:,1] > threshold)
preds2 = bg_preds[mod]
oddsratio, pvalue = stats.fisher_exact([[preds2,2000000-pred... | lhm30/PIDGINv2 | [
28,
8,
28,
1,
1442588431
] |
def performTargetPrediction(models):
prediction_results = []
pool = Pool(processes=N_cores, initializer=initPool, initargs=(querymatrix1,threshold,bg_preds)) # set up resources
jobs = pool.imap_unordered(doTargetPrediction, models)
for i, result in enumerate(jobs):
percent = (float(i)/float(len(models)))*100 + 1... | lhm30/PIDGINv2 | [
28,
8,
28,
1,
1442588431
] |
def updateHits(links,hits,uniprot,hit1,hit2):
try:
for idx in links[uniprot]:
#try checks if pw or dnet
try:
if disease_score[(idx,uniprot)] < dgn_threshold: continue
except KeyError: pass
try:
hits[idx] = hits[idx] + np.array([hit1,hit2])
except KeyError:
hits[idx] = np.array([hit1,hit2])... | lhm30/PIDGINv2 | [
28,
8,
28,
1,
1442588431
] |
def doHitProcess(inp):
idx, hits, n_f1_hits, n_f2_hits = inp
if hits[0] == 0 and hits[1] == 0: return
if hits[0] == 0: return idx, 999.0, 0, 0, hits[1], float(hits[1])/float(n_f2_hits), 'NA', 'NA'
if hits[1] == 0: return idx, 0.0, hits[0], float(hits[0])/float(n_f1_hits), 0, 0, 'NA', 'NA'
h1_p = float(hits[0])/flo... | lhm30/PIDGINv2 | [
28,
8,
28,
1,
1442588431
] |
def processHits(inp_dict):
out_dict = dict()
total_hits = np.array(inp_dict.values()).sum(axis=0)
if total_hits.shape is (): return out_dict, 0, 0
n_f1_hits = total_hits[0]
n_f2_hits = total_hits[1]
tasks = [[idx,hits,n_f1_hits,n_f2_hits] for idx, hits in inp_dict.iteritems()]
pool = Pool(processes=N_cores) # s... | lhm30/PIDGINv2 | [
28,
8,
28,
1,
1442588431
] |
def initPool(querymatrix1_, threshold_, bg_preds_):
global querymatrix1, threshold, bg_preds
querymatrix1 = querymatrix1_
threshold = threshold_
bg_preds = bg_preds_ | lhm30/PIDGINv2 | [
28,
8,
28,
1,
1442588431
] |
def __init__(self, event_type, timestamp, **kwargs):
self.event_type = event_type # All events have these two attributes
self.timestamp = timestamp
for attribute in self.KNOWN_ATTRIBUTES:
self._set(attribute, kwargs.get(attribute)) | thefactory/marathon-python | [
199,
152,
199,
25,
1398275002
] |
def _set(self, attribute_name, attribute):
if not attribute:
return
# Special handling for lists...
if isinstance(attribute, list):
name = self.seq_name_to_singular.get(attribute_name)
attribute = [
self.__to_marathon_object(name, v)
... | thefactory/marathon-python | [
199,
152,
199,
25,
1398275002
] |
def __init__(self):
pass | thefactory/marathon-python | [
199,
152,
199,
25,
1398275002
] |
def _pdfrate_wrapper(ntuple):
'''
A helper function to parallelize calls to gdkde().
'''
try:
return pdfrate_once(*ntuple)
except Exception as e:
return e | uvasrg/EvadeML | [
98,
40,
98,
1,
1449699729
] |
def _pdfrate_feat_wrapper(ntuple):
'''
A helper function to parallelize calls to gdkde().
'''
try:
return pdfrate_feature_once(*ntuple)
except Exception as e:
return e | uvasrg/EvadeML | [
98,
40,
98,
1,
1449699729
] |
def get_classifier():
scenario_name = "FTC"
scenario = _scenarios[scenario_name]
# Set up classifier
classifier = 0
if scenario['classifier'] == 'rf':
classifier = RandomForest()
print 'Using RANDOM FOREST'
elif scenario['classifier'] == 'svm':
classifier = sklearn_SVC()... | uvasrg/EvadeML | [
98,
40,
98,
1,
1449699729
] |
def pdfrate_feature(pdf_file_paths, speed_up = True):
classifier = pdfrate_classifier
scaler = pdfrate_scaler
if not isinstance(pdf_file_paths, list):
pdf_file_paths = [pdf_file_paths]
if speed_up == True:
# The Pool has to be moved outside the function. Otherwise, every call of this f... | uvasrg/EvadeML | [
98,
40,
98,
1,
1449699729
] |
def pdfrate_with_feature(all_feat_np, speed_up = True):
classifier = pdfrate_classifier
scores = classifier.decision_function(all_feat_np)
scores = [s[0] for s in scores]
return scores | uvasrg/EvadeML | [
98,
40,
98,
1,
1449699729
] |
def pdfrate(pdf_file_paths, speed_up = True):
if type(pdf_file_paths) != list:
pdf_file_paths = [pdf_file_paths]
classifier = pdfrate_classifier
all_feat_np = pdfrate_feature(pdf_file_paths, speed_up)
scores = classifier.decision_function(all_feat_np)
scores = [float(s[0]) for s in scores]
... | uvasrg/EvadeML | [
98,
40,
98,
1,
1449699729
] |
def __init__(self, title, *sections):
"""Create a new `Document` with `title` and zero or more `sections`.
:param title: the tile of the document (`Document` or `Element` type)
:param sections: document sections (`Document` or `Element` type)
"""
self._title = promote_to_string... | roman-kutlak/nlglib | [
45,
18,
45,
3,
1444561978
] |
def __hash__(self):
return hash(str(self)) | roman-kutlak/nlglib | [
45,
18,
45,
3,
1444561978
] |
def __str__(self):
if self.title:
return str(self.title) + '\n\n' + '\n\n'.join([str(s) for s in self.sections])
else:
return '\n\n'.join([str(s) for s in self.sections]) | roman-kutlak/nlglib | [
45,
18,
45,
3,
1444561978
] |
def title(self):
return self._title | roman-kutlak/nlglib | [
45,
18,
45,
3,
1444561978
] |
def title(self, value):
self._title = promote_to_string(value) | roman-kutlak/nlglib | [
45,
18,
45,
3,
1444561978
] |
def sections(self):
return self._sections | roman-kutlak/nlglib | [
45,
18,
45,
3,
1444561978
] |
def sections(self, *sections):
self._sections = [promote_to_string(s) for s in sections] | roman-kutlak/nlglib | [
45,
18,
45,
3,
1444561978
] |
def to_xml(self, depth=0, indent=' '):
"""Return an XML representation of the document"
:param depth: the initial indentation offset (depth * indent)
:param indent: the indent for nested elements.
"""
offset = indent * depth
result = offset + '<document>\n'
resu... | roman-kutlak/nlglib | [
45,
18,
45,
3,
1444561978
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.