repo_name stringlengths 5 100 | path stringlengths 4 231 | language stringclasses 1
value | license stringclasses 15
values | size int64 6 947k | score float64 0 0.34 | prefix stringlengths 0 8.16k | middle stringlengths 3 512 | suffix stringlengths 0 8.17k |
|---|---|---|---|---|---|---|---|---|
jeremiahyan/odoo | addons/website/models/ir_module_module.py | Python | gpl-3.0 | 19,278 | 0.004305 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
import os
from collections import OrderedDict
from odoo import api, fields, models
from odoo.addons.base.models.ir_model import MODULE_UNINSTALL_FLAG
from odoo.exceptions import MissingError
from odoo.htt... | chment
# if module B override attachment from dependence A, we update it
if not find and model_name == 'ir.attachment':
find = rec.copy_ids.search([('key', '=', rec.key), ('website_id', '=', website.id)])
| if find:
imd = self.env['ir.model.data'].search([('model', '=', find._name), ('res_id', '=', find.id)])
if imd and imd.noupdate:
_logger.info('Noupdate set for %s (%s)' % (find, imd))
else:
# at up... |
fenderglass/Nano-Align | scripts/flip-blockades.py | Python | bsd-2-clause | 2,322 | 0.004307 | #!/usr/bin/env python2.7
#(c) 2015-2016 by Authors
#This file is a part of Nano-Align program.
#Released under the BSD license (see LICENSE file)
"""
Flips blockades signals according to the protein's AA order
"""
from __future__ import print_function
import sys
import os
nanoalign_root = os.path.dirname(os.path.di... | st > rev_dist:
new_blockades[-1].eventTrace = new_blockades[-1].eventTrace[::-1]
num_reversed += 1
print("Reversed:", num_reversed, "of", len(blockades), file=sys.stderr)
return new_blockades
def main():
if len(sys.argv) != 4:
| print("usage: flip-blockades.py blockades_in model_file flipped_out\n\n"
"Orients blockade signals according to the AA order "
"in the protein of origin")
return 1
blockades_in = sys.argv[1]
blockades_out = sys.argv[3]
svr_file = sys.argv[2]
blockades = read... |
bataeves/kaggle | instacart/imba/arboretum_submition.py | Python | unlicense | 15,544 | 0.005597 | import gc
import pandas as pd
import numpy as np
import os
import arboretum
import json
import sklearn.metrics
from sklearn.metrics import f1_score, roc_auc_score
from sklearn.model_selection import train_test_split
from scipy.sparse import dok_matrix, coo_matrix
from sklearn.utils.multiclass import type_of_target
i... | uct_embeddings[embedings + ['product_id']]
order_train = pd.read_pickle(os.path.join(path, 'chunk_0.pkl'))
order_test = order_train.loc[order_train.eval_set == "test", ['order_id', 'product_id']]
order_train = order_train.loc[order_train.eval_set == "train", ['order_id', 'product_id', 'reordered']]
... | ds_stat.pkl')).fillna(9999)
print(order_train.columns)
###########################
prob = pd.merge(order_prior, orders, on='order_id')
print(prob.columns)
prob = prob.groupby(['product_id', 'user_id'])\
.agg({'reordered':'sum', 'user_id': 'size'})
print(prob.columns)
prob.rename(... |
codyparker/channels-obstruction | game/views/views.py | Python | mit | 3,489 | 0.002006 | from django.contrib.auth.forms import PasswordResetForm
from django.shortcuts import redirect
from django.views.generic import CreateView, TemplateView, View, FormView
from django.contrib.auth import authenticate, login
from game.forms import *
from game.models import User, Game
from django.contrib.auth.forms import Au... | messages
import json
from dj | ango.contrib.auth import get_user
from django.shortcuts import get_object_or_404
class HomeView(TemplateView):
template_name = 'home.html'
def dispatch(self, request, *args, **kwargs):
# if logged in, send them to the lobby
if request.user.is_authenticated:
return redirect('/lobby... |
CalthorpeAnalytics/urbanfootprint | footprint/client/configuration/scag_dm/base/jurisdiction_boundary.py | Python | gpl-3.0 | 1,720 | 0 |
# UrbanFootprint v1.5
# Copyright (C) 2017 C | althorpe Analytics
#
# This file is part o | f UrbanFootprint version 1.5
#
# UrbanFootprint is distributed under the terms of the GNU General
# Public License version 3, as published by the Free Software Foundation. This
# code is distributed WITHOUT ANY WARRANTY, without implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Gen... |
yarikoptic/fail2ban | fail2ban/server/filtersystemd.py | Python | gpl-2.0 | 8,738 | 0.029068 | # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: t -*-
# vi: set ft=python sts=4 ts=4 sw=4 noet :
# This file is part of Fail2Ban.
#
# Fail2Ban is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation;... | Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
__author__ = "Steven Hiscocks"
__copyright__ = "Copyright (c) 2013 Steven Hiscocks"
__license__ = "GPL"
import datetime
import time
from distutils | .version import LooseVersion
from systemd import journal
if LooseVersion(getattr(journal, '__version__', "0")) < '204':
raise ImportError("Fail2Ban requires systemd >= 204")
from .failmanager import FailManagerEmpty
from .filter import JournalFilter, Filter
from .mytime import MyTime
from ..helpers import getLogger,... |
andrewruba/YangLab | JPC simulations 2019/Figure 7 - symmetry compression/simulation.py | Python | gpl-3.0 | 13,921 | 0.037354 | # -*- coding: utf-8 -*-
"""
Created on Thu Apr 20 10:52:38 2017
@author: Andrew Ruba
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at ... | int ('binsize ' + str(binsize))
jkl = []
mm = mm + 0.00001
while len(jkl) < num_points-1:
theta = np.random.random()*360.0
## precision distribution sampling
# ss = choice([3,5,7,9], p=[0.1475,0.2775,0.3075,0.2675])
# ss = ch... | p=[0.02,0.05,0.07,0.11,0.2,0.55])
y_prec = np.random.normal(0.0, ss)
jkl.append(mm*np.cos(theta)+y_prec)
a,b = make_hist(jkl, radius, binsize)
final_unsmooth, final_smooth, final_2d = deconvolution(a, b, radius, binsize)
holdlist = []
addZero = False
for val in list(re... |
rutsky/letsencrypt | letsencrypt/validator.py | Python | apache-2.0 | 2,825 | 0.000354 | """Validators to determine the current webserver configuration"""
import logging
import socket
import requests
import zope.interface
from acme import crypto_util
from acme import errors as acme_errors
from letsencrypt import interfaces
logger = logging.getLogger(__name__)
class Validator(object):
# pylint: dis... | """Test whether webserver redirects to secure connection."""
url = "http://{0}:{1}".format(name, port)
if headers:
response = requests.get(url, headers=headers, allow_redirects=False)
else:
response = requests.get(url, | allow_redirects=False)
if response.status_code not in (301, 303):
return False
redirect_location = response.headers.get("location", "")
if not redirect_location.startswith("https://"):
return False
if response.status_code != 301:
logger.error("Serve... |
ccqpein/Arithmetic-Exercises | Depth-First-Search/DFS.py | Python | apache-2.0 | 3,928 | 0.000255 | class Graph():
pointSet = []
# it should be a dict on {point:[list of point it connects]}
pathDic = dict()
pointTime = dict() # points' discover time and finish time
def __init__(self, points, paths):
if set(paths.keys()) - set(points):
print(
"Warning: Some poi... | # delete grey set
retur | n time
for i in g.pointSet:
if i in blackMark or i in greyMark:
pass
else:
time = DFS_inner(g, i, time)
# format print
for k in g.pointSet:
print("{0} -> discover time is {1} -> finish time is {2}"
.format(k, g.pointTime[k][0], g.pointTime[k][1... |
gavincyi/Telex | src/message.py | Python | apache-2.0 | 2,393 | 0.008776 | #!/bin/python
import datetime
class message():
def __init__(self, msg_id=0, channel_id=0, source_id=0, source_chat_id='',\
msg=''):
curr_datetime = datetime.datetime.now()
self.date = curr_datetime.strftime("%Y%m%d")
self.time = curr_datetime.strftime("%H:%M:%S.%f %z")
... | text, msg text"
@staticmethod
def key_str():
return "msgid"
@staticmethod
def date_index():
return 0
@staticmeth | od
def time_index():
return 1
@staticmethod
def msg_id_index():
return 2
@staticmethod
def channel_id_index():
return 3
@staticmethod
def source_id_index():
return 4
@staticmethod
def source_chat_id_i... |
Nesiehr/osf.io | api_tests/nodes/views/test_node_contributors_list.py | Python | apache-2.0 | 95,975 | 0.003813 | # -*- coding: utf-8 -*-
import random
import mock
from datetime import datetime
from nose.tools import * # flake8: noqa
from rest_framework import exceptions
from api.base.exceptions import Conflict
from api.base.settings.defaults import API_BASE
from api.nodes.serializers import NodeContributorsCreateSerializer
... | self).setUp()
self.private_url = '/{}nodes/{}/contributors/'.format(API_BASE, self.private_project._id)
self.public_url = '/{}nodes/{}/contributors/'.format(API_BASE, self.public_project._id)
def test_concaten | ated_id(self):
res = self.app.get(self.public_url)
assert_equal(res.status_code, 200)
assert_equal(res.json['data'][0]['id'].split('-')[0], self.public_project._id)
assert_equal(res.json['data'][0]['id'].split('-')[1], self.user._id)
def test_permissions_work_with_many_users(self):... |
jnewland/home-assistant | homeassistant/components/xs1/switch.py | Python | apache-2.0 | 1,288 | 0 | """Support for XS1 switches."""
import logging
from homeassistant.helpers.entity import ToggleEntity
from . import ACTUATORS, DOMAIN as COMPONENT_DOMAIN, XS1DeviceEntity
_LOGGER = logging.getLogger(__name__)
async def async_setup_platform(
hass, config, async_add_entities, discovery_info=None):
"""Set ... | the XS1 switch platform."""
from xs1_api_client.api_constants import ActuatorType
actuators = hass.data[COMPONENT_DOMAIN][ACTUATORS]
switch_entities = []
for actuator in actuators:
if (actuator.type() == ActuatorType.SWITCH) or \
(actuator.type() == ActuatorType.DIMMER):
... | ntation of a XS1 switch actuator."""
@property
def name(self):
"""Return the name of the device if any."""
return self.device.name()
@property
def is_on(self):
"""Return true if switch is on."""
return self.device.value() == 100
def turn_on(self, **kwargs):
... |
andrew749/andrew749.github.io | application/caches/test/test_local_cache.py | Python | apache-2.0 | 367 | 0.029973 | import unittest
from application.caches.local_cache import LocalC | ache
class LocalCacheTest(unittest.TestCase):
def setUp(self):
self.cache = LocalCache()
def tearDown(self):
pass
def test_add_element(self):
self.cache | .add("test.key", "test.value")
self.assertEqual(self.cache.get("test.key"), "test.value")
if __name__ == "__main__":
unittest.main() |
perey/pegl | src/pegl/ext/khr_vgimage.py | Python | gpl-3.0 | 983 | 0 | #!/usr/bin/env python3
'''Khronos OpenVG parent image binding for EGL.
http://www.khronos.org/registry/egl/extensions/KHR/EGL_KHR_vg_parent_image.txt
'''
# Copyright © 2012-13 Tim Pederick.
#
# This file is part of Pegl.
#
# Pegl is free software: you can redistribute it and/or modify it
# under the terms of the GNU... | ion 3 of the License, or
# (at your option) any later version.
#
# Pegl is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; with | out even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
# License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Pegl. If not, see <http://www.gnu.org/licenses/>.
# Local imports.
from .khr_image import Ima... |
pexip/os-kombu | docs/conf.py | Python | bsd-3-clause | 924 | 0 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from sphinx_celery import conf
globals().update(conf.build_config(
'kombu', __file__,
project='Kombu',
version_dev='4.3',
version_stable='4.2',
canonical_url='http://docs.kombu.me',
webdomain='kombu.me',
| github_project='celery/k | ombu',
author='Ask Solem & contributors',
author_name='Ask Solem',
copyright='2009-2016',
publisher='Celery Project',
html_logo='images/kombusmall.jpg',
html_favicon='images/favicon.ico',
html_prepend_sidebars=['sidebardonations.html'],
extra_extensions=['sphinx.ext.napoleon'],
apich... |
AndreasMadsen/bachelor-code | visualizer/__init__.py | Python | mit | 71 | 0 |
from graph.graph_se | rver import G | raphServer
__all__ = ['GraphServer']
|
taoliu/MACS | MACS2/bdgbroadcall_cmd.py | Python | bsd-3-clause | 2,141 | 0.01121 | # Time-stamp: <2019-09-25 10:04:48 taoliu>
"""Description: Fine-tuning script to call broad peaks from a single
bedGraph track for scores.
This code is free software; you can redistribute it and/or modify it
under the terms of the BSD License (see the file LICENSE included with
the distribution).
"""
# ------------... | --------
# python modules
# ------------------------------------
import sys
import os
import logging
from MACS2.IO import BedGraphIO
# ------------------------------------
# constants
# ------------------------------------
logging.basicConf | ig(level=20,
format='%(levelname)-5s @ %(asctime)s: %(message)s ',
datefmt='%a, %d %b %Y %H:%M:%S',
stream=sys.stderr,
filemode="w"
)
# ------------------------------------
# Misc functions
# ---------------------------... |
csvtools/csvtools | src/widgets/importwiz.py | Python | gpl-3.0 | 3,525 | 0.003972 | from PyQt4. | QtCore import *
from PyQt4.QtGui import *
import lib.images_rc
import sys
class QImportWiz(QDialog):
#
# private
#
def _getCheckableList(self, sheets):
| """return an instance model with a sheet list composed of
three columns (sheet, number of rows, number of columns)
"""
model = QStandardItemModel(len(sheets), 3)
model.setHeaderData(0, Qt.Horizontal, self.tr('Sheet'))
model.setHeaderData(1, Qt.Horizontal, self.tr('Rows'))
... |
genome21/dcos-cli | dcos/jsonitem.py | Python | apache-2.0 | 7,404 | 0.00027 | import collections
import json
import re
from dcos import util
from dcos.errors import DCOSException
logger = util.get_logger(__name__)
def parse_json_item(json_item, schema):
"""Parse the json item based on a schema.
:param json_item: A JSON item in the form 'key=value'
:type json_item: str
:param... | tring to parse
:type value: str
:returns: The parsed value
:rtype: list
"""
try:
array = json.loads(value)
if array is None or isinstance(array, collections.Sequence):
| return array
else:
raise DCOSException(
'Unable to parse {!r} as an array'.format(value))
except ValueError as error:
logger.exception('Error parsing value as a JSON array')
msg = 'Unable to parse {!r} as an array: {}'.format(value, error)
rai... |
argilo/bbhn-utils | nodeinfo.py | Python | gpl-3.0 | 1,671 | 0.000598 | #!/usr/bin/env python3
# Copyright 2017-2018 Clayton Smith
#
# This file is part of bbhn-utils
#
# bbhn-utils is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later ... | mport NodeDB
DISPLAY_HOURS = 24
node_db = NodeDB()
app = Flask(__name__, static_url_path='/static')
@app.route('/')
def node_info():
last_seen = node_db.last_seen(DISPLAY_HOURS)
return render_template('index.html', last_seen=last_seen)
@app.route('/link/<ip>.html')
def link_info(ip):
name = node_db.na... | DISPLAY_HOURS)
for i, neighbour in enumerate(neighbours):
cost = node_db.cost_history(ip, neighbour[1], DISPLAY_HOURS)
cost = [(ts.timestamp() * 1000, lq) for ts, lq in cost]
neighbours[i] = neighbour + (json.dumps(cost),)
return render_template('link.html', ip=ip, name=name, neighbours=... |
asedunov/intellij-community | python/testData/completion/heavyStarPropagation/lib/_pkg1/_pkg1_1/_pkg1_1_1/_pkg1_1_1_0/_pkg1_1_1_0_0/_mod1_1_1_0_0_1.py | Python | apache-2.0 | 128 | 0.007813 | name1_1_1_0_0 | _1_0 = None
name1_1_1_0_0_1_1 = None
name1_1_1_0_0_1_2 = None
name1_1_1_0_0_1_3 = None
name1_1_1_0_0_1_ | 4 = None |
teythoon/Insekta | docs/conf.py | Python | mit | 7,761 | 0.007473 | # -*- coding: utf-8 -*-
#
# Insekta documentation build configuration file, created by
# sphinx-quickstart on Sat Dec 24 16:48:19 2011.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All... | 1pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping | the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'Insekta.tex', u'Insekta Documentation',
u'Insekta team', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
... |
RoboPi-CSEDU/rupai | Adafruit_Python_SSD1306/examples/shapes.py | Python | mit | 4,281 | 0.002569 | # Copyright (c) 2014 Adafruit Industries
# Author: Tony DiCola
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | dress parameter like:
# disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST, i2c_address=0x3C)
# Alternatively you can specify an explicit I2C bus number, for example
# with the 128x32 display you would use: |
# disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST, i2c_bus=2)
# 128x32 display with hardware SPI:
# disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST, dc=DC, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=8000000))
# 128x64 display with hardware SPI:
disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST, dc=DC, spi=SPI.SpiD... |
bvalot/panISa | lib/clipread.py | Python | gpl-3.0 | 2,634 | 0.007976 | #!/usr/bin/python
# -*- coding: utf-8 -*-
##Copyright (c) 2017 Benoit Valot and Panisa Treepong
##benoit.valot@univ-fcomte.fr
##UMR 6249 Chrono-Environnement, Besançon, France
##Licence GPL
from . import variables
class ClipRead():
"""Clip read object"""
def __init__(self, alignedsegment):
self.read_... | epr__(self):
return self.read_seq
def __str__(self):
return str(self.ref_start) + ": " + str(self.read_start) + self.read_seq | + \
str(self.read_end) + " :" + str(self.ref_end)
if __name__=='__main__':
import doctest
doctest.testmod()
|
frownless/EMUstack | backend/mode_calcs.py | Python | gpl-3.0 | 13,371 | 0.004712 | """
mode_calcs.py is a subroutine of EMUstack that contains methods to
calculate the modes of a given layer, either analytically
(class 'Anallo') or from the FEM routine (class 'Simmo').
Copyright (C) 2013 Bjorn Sturmberg, Kokou Dossou, Felix Lawrence
EMUstack is free software: you can r... | if 'TE' == pol:
inc_amp[spec_TE] = 1
elif 'TM' == pol:
inc_amp[spec_TM] = 1
elif 'R Circ' == pol:
inc_amp[spec_TE] = 1/sqrt(2.)
inc_amp[spec_TM] = +1j/sqrt(2.)
elif 'L Circ' == pol:
inc_amp[spec_TE] = 1/sqrt(2.)
... | |
moteloquito/final-project | final/apps/fondo/views.py | Python | gpl-3.0 | 5,222 | 0.003255 | from django.contrib.auth import authenticate, login
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.models import User
from django.core import serializers
from django.core.paginator import Paginator, EmptyPage
from django.core.serializers.json import DjangoJSONEncoder
from django.http.... | r(status='SUBM')
aproved = fondo | .ticket_set.filter(status='OPEN')
total_submited = 0.0
total_aproved = 0.0
if submited:
total_submited = sum(t.value for t in submited)
if aproved:
total_aproved = sum(t.value for t in aproved)
print ("Status: submited %s, aproved %s" % (total_submited, total_aproved))
data = {... |
Wang-Sen/nqzx-backend | bootcamp/app/views.py | Python | gpl-3.0 | 11,441 | 0.007145 | # -*- coding: utf8 -*-
from django.conf import settings
from django.contrib import auth
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from django.views.decora... | save()
result = {"status": True, "data": {"id": user.id, "email": user.email, \
"location": user.profile.location, "mobile": user.profile.mobile, "reputation": \
user.profile.reputation,"signdate": user.profile.signdate}}
return HttpResponse(json.dumps(result), content_type="application/json")
... | sername": user.username, "email": user.email, "location": user.profile.location, \
"mobile": user.profile.mobile, "reputation": user.profile.reputation,"first_name": user.first_name, \
"sex": user.profile.sex,"signdate": user.profile.signdate}
return HttpResponse(json.dumps(state), content_t... |
oVirt/vdsm | lib/vdsm/host/__init__.py | Python | gpl-2.0 | 2,088 | 0.000479 | #
# Copyright 2008-2019 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed ... | of the license
#
from __future__ import absolute_import
from __future__ import division
import os
import logging
from vdsm.common import cpuarch
from vdsm.common.cache import m | emoized
from vdsm import dmidecodeUtil
P_VDSM_NODE_ID = '/etc/vdsm/vdsm.id'
@memoized
def uuid():
host_UUID = None
try:
if os.path.exists(P_VDSM_NODE_ID):
with open(P_VDSM_NODE_ID) as f:
host_UUID = f.readline().replace("\n", "")
else:
arch = cpuarch.r... |
ryanpdwyer/newtex | newtex/tests/test_git.py | Python | mit | 116 | 0 | import unittest
class TestExample(unittest.TestCase):
def test_example(self):
| self.assertEquals(0, 0)
| |
lemoncoin/lemoncoin | contrib/spendfrom/spendfrom.py | Python | mit | 10,043 | 0.005775 | #!/usr/bin/env python
#
# Use the raw transactions API to spend bitcoins received on particular addresses,
# and send any change back to that same address.
#
# Example usage:
# spendfrom.py # Lists available funds
# spendfrom.py --from=ADDRESS --to=ADDRESS --amount=11.00
#
# Assumes it will talk to a bitcoind or Bit... | 20000000.00000003")
satoshis = int(json.loads(json.dumps(float(n)))*1.0e8)
if satoshis != 2000000000000003:
raise RuntimeError("JSON encode/decode loses precision")
def determine_db_dir():
"""Return the default | location of the bitcoin data directory"""
if platform.system() == "Darwin":
return os.path.expanduser("~/Library/Application Support/Bitcoin/")
elif platform.system() == "Windows":
return os.path.join(os.environ['APPDATA'], "Bitcoin")
return os.path.expanduser("~/.bitcoin")
def read_bitcoi... |
wolfram74/numerical_methods_iserles_notes | venv/lib/python2.7/site-packages/sympy/solvers/tests/test_solvers.py | Python | mit | 58,517 | 0.002956 | from sympy import (
Abs, And, Derivative, Dummy, Eq, Float, Function, Gt, I, Integral,
LambertW, Lt, Matrix, Or, Piecewise, Poly, Q, Rational, S, Symbol,
Wild, acos, asin, atan, atanh, cos, cosh, diff, erf, erfinv, erfc,
erfcinv, erf2, erf2inv, exp, expand, im, log, pi, re, sec, sin,
sinh, solve, so... | ve_strategy( 2*cos(x) - y, x ) # == GS_TRANSCENDENTAL
assert guess_solve_strategy(
exp(x) + exp(-x) - y, x ) # == GS_TRANSCENDENTAL
assert guess_solve_strategy(3**x - 10, x) # == GS_TRANSCENDENTAL
assert g | uess_solve_strategy(-3**x + 10, x) # == GS_TRANSCENDENTAL
assert guess_solve_strategy(a*x**b - y, x) # == GS_TRANSCENDENTAL
def test_solve_args():
# equation container, issue 5113
ans = {x: -3, y: 1}
eqs = (x + 5*y - 2, -3*x + 6*y - 15)
assert all(solve(container(eqs), x, y) == ans for containe... |
msettles/expHTS | expHTS/spadesCMD.py | Python | apache-2.0 | 3,121 | 0.006729 | from validate_app import validateApp
import os
from distutils import spawn
import sys
from parse_files import parseOutHTseq, bringTogether
from bashSub import bashSub
def checkPreprocessApplications():
applications = ["spades.py"]
source = ["http://bioinf.spbau.ru/spades"]
i = 0;
for app in applicatio... | + e[0]
PE2 += "," + e[1]
return [SE, PE1, PE2]
def check_dir(Dir):
if not os.path.exists(Dir):
os.mkdir(Dir)
class spadesCMD:
def __init__(self):
self.metaDataFolder = "MetaData"
def execute(self, args):
time = 0
checkPreprocessApplications() | ;
logFiles = []
# checkPreprocessApplications()
validate = validateApp()
validate.setValidation(True)
dictSampleSeqFiles = validate.validateSampleSheet(args.readFolder, args.spadesFolder, args.samplesFile, args.force, True)
#keys tuple 0 location being input folder
... |
pmakahmann/CL_Project | CL_Project/settings.py | Python | mit | 3,282 | 0.001219 | """
Django settings for CL_Project project.
Generated by 'django-admin startproject' using Django 1.9.9.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os... | types',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'songs',
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.m | iddleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'CL_Project... |
jbuchbinder/youtube-dl | youtube_dl/extractor/prosiebensat1.py | Python | unlicense | 17,378 | 0.002303 | # coding: utf-8
from __future__ import unicode_literals
import re
| from hashlib import sha1
from .common import InfoExtractor
from ..compat import compat_str
from ..utils import (
ExtractorError,
determine_ext,
float_or_none,
int_or_none,
unified_strdate,
)
class ProSiebenSat1BaseIE(InfoExtractor):
def _extract_video_info(self, url, clip_id):
client_l... | {
'access_token': self._TOKEN,
'client_location': client_location,
'client_name': self._CLIENT_NAME,
'ids': clip_id,
})[0]
if video.get('is_protected') is True:
raise ExtractorError('This video is DRM protected.', expected=... |
ferreiro/Python-NoSQL-Security | assignment6/El_Coladero/coladero.py | Python | mit | 2,952 | 0.006108 | # -*- coding: utf-8 -*-
"""
@title: | El Coladero
@description: Aplicación web para detectar y corregir vulnerabilidades
@author: Enrique Martín Martín
@email: emartinm@ucm.es
"""
from bottle import run, template, get, post, request
import sqlite3
@get('/show_all_questions')
def show_all_questions():
conn = sqlite3.connect("database.db")
cur = ... | fetchall())
conn.close()
return template('messages.html', questions=res)
@post('/insert_question')
def insert_question():
author = request.forms['author']
title = request.forms['title']
tags = request.forms['tags']
body = request.forms['body']
conn = sqlite3.connect("database.... |
ricleal/reductionServer | src/data/messages.py | Python | gpl-3.0 | 1,661 | 0.022878 | '''
Created on Sep 27, 2013
@author: leal
Default JSON MESSAGES
'''
import ast
import logging
import config.config
logger = logging.getLogger(__name__)
class Messages(object):
'''
classdocs
'''
messageTemplate = """{
'success' : '%r',
'message' : '%s',
'details' : %r
... | t.literal_eval(details))
logger.debug(messageAsStr)
messageAsDic = ast.literal_eval(messageAsStr)
return messageAsDic
if __name__ == '__main__':
Messages.success("OK")
Messages.success("OK", "File received")
Messages.error("Error")
Messages.error("Error",details='There was an e... | orDetailed("Error adding X.","Valid values are", [1,2,3,5])
|
waynezhanghk/FastCausation | features.py | Python | apache-2.0 | 23,932 | 0.013497 | import numpy as np
from sklearn.base import BaseEstimator
import pandas as pd
import operator
from estimator_base import *
from features_base import *
BINARY = "Binary"
CATEGORICAL = "Categorical"
NUMERICAL = "Numerical"
class FeatureMapper:
def __init__(self, features):
self.features = features
... | igci), ['Normalized Value[B,B type]', 'Normalized Value[A,A type]']),
('Sub', ['IGCI[A,A type,B,B type]','IGCI[B,B type,A,A type]'], MultiColumnTransform(operator.sub)),
('Abs', 'Sub[IGCI[A,A type,B,B type],IGCI[B,B type,A,A type]]', SimpleTr | ansform(abs)),
('Gaussian Divergence', ['A','A type'], MultiColumnTransform(gaussian_divergence), ['Count Value[A,A type]']),
('Gaussian Divergence', ['B','B type'], MultiColumnTransform(gaussian_divergence), ['Count Value[B,B type]']),
('Max', ['Gaussian Divergence[A,A type]','Gaussian Diverge... |
dimatura/opendr | test_geometry.py | Python | mit | 1,656 | 0.008454 | #!/usr/bin/env python
# encoding: utf-8
"""
Author(s): Matthew Loper
See LICENCE.txt for licensing and contact information.
"""
import sys
import os
import unittest
import chumpy as ch
from chumpy import Ch
import numpy as np
from util_tests import get_earthmesh
class TestGeometry(unittest.TestCase):
def setUp(... | np.random.randn(3)
rt2 = rt + np.random.rand(3)*1e-5
foo1 = Rodrigues(rt = rt)
foo2 = Rodrigues(rt = rt2)
empirical = (foo2.r - foo1.r).flatten()
predicted = foo1. | dr_wrt(foo1.rt).dot(rt2-rt)
self.assertTrue(np.max(np.abs(empirical - predicted)) < 1e-10)
def test_vert_normals(self):
from geometry import VertNormals
import numpy as np
mesh = get_earthmesh(np.zeros(3), np.zeros(3))
v, f = mesh.v*127., mesh.f
v... |
bmcfee/librosa | librosa/onset.py | Python | isc | 19,286 | 0.001141 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Onset detection
===============
.. autosummary::
:toctree: generated/
onset_detect
onset_backtrack
onset_strength
onset_strength_multi
"""
import numpy as np
import scipy
from ._cache import cache
from . import core
from . import util
from .util.e... | r, units='time')
array([0.07 , 0.232, | 0.395, 0.604, 0.743, 0.929, 1.045, 1.115,
1.416, 1.672, 1.881, 2.043, 2.206, 2.368, 2.554, 3.019])
Or use a pre-computed onset envelope
>>> o_env = librosa.onset.onset_strength(y, sr=sr)
>>> times = librosa.times_like(o_env, sr=sr)
>>> onset_frames = librosa.onset.onset_detect(onset_envelo... |
bschoenfeld/va-court-scraper | courtutils/user.py | Python | mit | 990 | 0.00303 | import hashlib
import os
from database import Database
from email import send_welcome_email
from flask.ext.login import UserMixin
def get_hash(data):
hash = hashlib.sha256()
hash.update(os.environ['PASSWORD_TOKEN_SALT'])
hash.update( | data)
return hash.hexdigest()
class User(UserMixin):
def _ | _init__(self, user):
self.id = user['email']
self.user = user
@classmethod
def get(cls, id):
return User(Database.get_user(id))
@classmethod
def registered(cls, email):
return Database.get_user(email) != None
@classmethod
def create(cls, email):
Databas... |
ddboline/Garmin-Forerunner-610-Extractor_fork | ant/base/ant.py | Python | mit | 12,100 | 0.003884 | # Ant
#
# Copyright (c) 2012, Gustav Tiger <gustav@tiger.name>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, m... | ger.debug(" - sent message from queue, %r", m)
if(m._id != Message.ID.BURST_TRANSFER_DATA or \
m._data[0] & 0b10000000):# or m._data[0] == 0):
break
else:
... | self._message_queue_cond.release()
self._last_data = message._data
except usb.USBError as e:
_logger.warning("%s, %r", type(e), e.args)
_logger.debug("Ant runner stopped")
def _main(self):
while self._running:
try:
(event_... |
bsmr-eve/Pyfa | eos/effects/usemissiles.py | Python | gpl-3.0 | 1,203 | 0.002494 | # useMissiles
#
# Used by:
# Modules from group: Missile Launcher Heavy (12 of 12)
# Modules from group: Missile Launcher Rocket (15 of 15)
# Modules named like: Launcher (154 of 154)
# Structure Modules named like: Standup Launcher (7 of 7)
type = 'active', "projected"
def handler(fit, src, context):
# Set reloa... | ain(src, speed + moduleReactivationDelay, neutAmount, 0)
# Lockbreaker Bombs
ecmStrengthBonus = src.getMod | ifiedChargeAttr("scan{0}StrengthBonus".format(fit.scanType))
if ecmStrengthBonus:
strModifier = 1 - ecmStrengthBonus / fit.scanStrength
fit.ecmProjectedStr *= strModifier
|
joebowen/ChannelWormDjango | ChannelWorm/channelworm/settings.py | Python | mit | 3,520 | 0 | """
Django settings for channel_worm project.
Generated by 'django-admin startproject' using Django 1.8.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build... | 'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'digitizer',
'ion_channel'
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.mid... | on.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddlew... |
relman/sevpn-mgmt-py | SevpnMgmtPy/admin_api/traffic.py | Python | mit | 1,143 | 0.000875 | # -*- coding: utf-8 -*-
class TrafficEntry:
def __init__(self, broadcast_count=0L, broadcast_bytes=0L, unicast_count=0L, unicast_bytes=0L):
self.broadcast_count = broadcast_count
self.broadcast_bytes = broadcast_bytes
self.unicast_count = unicast_count
self.unicast_bytes = ... | lue("Recv.BroadcastBytes")
self.r | ecv.broadcast_count = pack.get_value("Recv.BroadcastCount")
self.recv.unicast_bytes = pack.get_value("Recv.UnicastBytes")
self.recv.unicast_count = pack.get_value("Recv.UnicastCount")
self.send.broadcast_bytes = pack.get_value("Send.BroadcastBytes")
self.send.broadcast_count = pack.g... |
dynaryu/inasafe | safe/storage/test/test_raster.py | Python | gpl-3.0 | 2,520 | 0.002778 | # coding=utf-8
"""**Tests for safe raster layer class**
contains tests for QGIS specific methods.
See test_io.py also
"""
__author__ = 'Dmitry Kolesov <kolesov.dm@gmail.com>'
__revision__ = '$Format:%H$'
__date__ = '28/12/2013'
__license__ = "GPL"
__copyright__ = 'Copyright 2012, Australia Indonesia Facility f... | logging.getLogger('InaSAFE')
KEYWORD_PATH = test_data_path('hazard', 'jakarta_flood_design.xml')
RASTER_BASE = test_data_path('hazard', 'jakarta_flood_design')
class RasterTest(unittest.TestCase):
def setUp(self):
msg = 'Keyword file does not exist at %s' % KEYWORD_PATH
assert os.path.exists(KEYW... | ding(self):
"""Test that reading from QgsRasterLayer works."""
# This line is the cause of the problem:
qgis_layer = QgsRasterLayer(RASTER_BASE + '.tif', 'test')
layer = Raster(data=qgis_layer)
qgis_extent = qgis_layer.dataProvider().extent()
qgis_extent = [qgis_extent.xM... |
ivanamihalek/progesterone | 16_UCSC_sources_to_ENCODE.py | Python | gpl-2.0 | 3,087 | 0.024619 | #!/usr/bin/python3
#
# This file is part of Progesterone pipeline.
#
# Progesterone pipeline is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later v... | pen(mapping_file,"r") as inf:
for line in inf:
if 'UCSC' in line: continue # header
[ucsc, encode_exp, encode_file] = line.split("\t")[:3]
ucsc_ids.append(ucsc)
encode_exp_id[ucsc] = encode_exp
encode_file_id[ucsc] = encode_file
#########################
# plug in to local database
db = connect_t... | ea if the database grows really large
# first make sure we have single entry for each of multiple ids
for line in search_db(cursor,"select id, external_id from xrefs where xtype='ucsc'"):
[xref_id, ucsc_str] = line
ucsc_ids_stored = ucsc_str.split(",")
if len(ucsc_ids_stored) <2: continue
for ucsc_id in ucsc_... |
skeuomorf/Binge | binge/core/views.py | Python | mit | 1,811 | 0.002209 | from django.shortcuts import render
from django.contrib.auth.models import User
from django.utils.text import slugify
from django.core.exceptions import ObjectDoesNotExist
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.p... | et_slug = slugify("{} {}".format(request.user.username, data['bucket']))
bucket = Bucke | t.objects.get(slug=bucket_slug)
data['bucket'] = bucket.id
try:
inst = Element.objects.get(name=data['name'], trakt_id=data['trakt_id'])
serializer = ElementSerializer(inst, data=data)
except ObjectDoesNotExist:
serializer = ElementSerializer(data=data)
... |
crossgovernmentservices/csdigital-prototype | application/frontend/forms.py | Python | mit | 402 | 0 | fr | om flask.ext.wtf import Form
fro | m flask.ext.wtf.html5 import EmailField
from wtforms.validators import Required
from wtforms.fields import (
TextAreaField,
HiddenField
)
class LoginForm(Form):
email = EmailField('Email address', validators=[Required()])
next = HiddenField('next')
class FeedbackForm(Form):
feedback = TextAreaF... |
nanocell/lsync | python/boto/route53/connection.py | Python | gpl-3.0 | 13,538 | 0.000222 | # Copyright (c) 2006-2010 Mitch Garnaat http://garnaat.org/
# Copyright (c) 2010, Eucalyptus Systems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# w... | ntifies the request
and that allows f | ailed CreateHostedZone requests to be retried
without the risk of executing the operation twice. If you don't
provide a value for this, boto will generate a Type 4 UUID and
use that.
:type comment: str
:param comment: Any comments you want to include about the hoste... |
sdoran35/hate-to-hugs | venv/lib/python3.6/site-packages/nltk/translate/ibm2.py | Python | mit | 12,271 | 0.000815 | # -*- coding: utf-8 -*-
# Natural Language Toolkit: IBM Model 2
#
# Copyright (C) 2001-2013 NLTK Project
# Authors: Chin Yee Lee, Hengfeng Li, Ruxin Hou, Calvin Tanujaya Lim
# URL: <http://nltk.org/>
# For license information, see LICENSE.TXT
"""
Lexical translation model that considers word order.
IBM Model 2 improv... | (round(ibm2.translation_table['das']['book'], 3))
0.0
>>> print(round(ibm2.translation_table['buch'][None], 3))
0.0
>>> print(round(ibm2.translation_table['ja'][None], 3))
0.0
>>> print(ibm2.alignment_table[1][1][2][2])
0.938...
>>> print(round(ibm2.alignment_table[1][2][2][2], 3))
... | st', 'ja', 'klein']
>>> test_sentence.mots
['the', 'book', 'is', 'small']
>>> test_sentence.alignment
Alignment([(0, 0), (1, 1), (2, 2), (3, 2), (4, 3)])
"""
def __init__(self, sentence_aligned_corpus, iterations,
probability_tables=None):
"""
Train on ``senten... |
nesterione/problem-solving-and-algorithms | problems/Empireofcode/IndexPower.py | Python | apache-2.0 | 441 | 0.018141 | def index_power(array, n):
if n>=len(array):
return -1
else:
return array[n | ]**n
if __name__ == '__main__':
# These "asserts" using only for self-checking and not necessary for auto-testing
a | ssert index_power([1, 2, 3, 4], 2) == 9, "Square"
assert index_power([1, 3, 10, 100], 3) == 1000000, "Cube"
assert index_power([0, 1], 0) == 1, "Zero power"
assert index_power([1, 2], 3) == -1, "IndexError" |
liyongyue/dnsspider | dns/opcode.py | Python | isc | 2,603 | 0.005763 | # Copyright (C) 2001-2005 Nominum, Inc.
#
# Permission to use, copy, modify, and distribute this software and its
# document | ation for any purpose with or without fee is hereby granted,
# provided that the above copyright notice and this permission notice
# appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
# WITH | REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER T... |
ptdtan/Ragout | lib/newick/treetest.py | Python | gpl-3.0 | 4,858 | 0.009881 |
import unittest
import lexer
import parser
from tree import *
from tree import _TreeBuilder
class BuilderTest(unittest.TestCase):
''' Test of the _TreeBuilder (and Leaf and Tree) class. '''
def testTreeBuilding(self):
''' Test that the tree builder constructs trees correctly when
parsed. ... | t.identifier, "treelabel")
t = parse_tree("(('A', 'B')label, 'C')1")
self.assertEqual(t.identifier, "1")
def testAddDistanceFromRoot(self):
''' Test the add_distance_from_root() function. '''
t = parse_tree('((A,B),C);')
add_distance_from_root(t)
self.assertEqual([... | stance_from_root for l in t.leaves],[3,4,6])
test_suite = unittest.TestSuite()
test_suite.addTest(unittest.makeSuite(BuilderTest))
test_suite.addTest(unittest.makeSuite(TestParseTree))
test_suite.addTest(unittest.makeSuite(TreeTest))
test_suite.addTest(unittest.makeSuite(TestFunctions))
if __name__ == '__main__':
... |
Reactive-Extensions/RxPy | tests/test_observable_creation.py | Python | apache-2.0 | 34,022 | 0.006937 | from rx import Observable
from rx.testing import TestScheduler, ReactiveTest, is_prime, MockDisposable
from rx.disposables import Disposable, SerialDisposable
on_next = ReactiveTest.on_next
on_completed = ReactiveTest.on_completed
on_error = ReactiveTest.on_error
subscribe = ReactiveTest.subscribe
subscribed = Reactiv... | bda x: True,
lambda x: _raise(ex),
lambda x: x,
scheduler)
results = scheduler.start(create)
results.messages.assert_equal(
on_next(201, 0),
| on_error(202, ex)
)
def test_generate_dispose():
scheduler = TestScheduler()
ex = 'ex'
def create():
return Observable.generate(0,
lambda x: True,
lambda x: x + 1,
lambda x: x,
scheduler)
results = scheduler.star... |
allegro/django-powerdns-dnssec | powerdns/models/__init__.py | Python | bsd-2-clause | 162 | 0 | from .ownership import * # noqa
from | .powerdns import * # noqa |
from .requests import * # noqa
from .templates import * # noqa
from .tsigkeys import * # noqa
|
kuke/models | legacy/image_classification/googlenet.py | Python | apache-2.0 | 5,341 | 0 | import paddle.v2 as paddle
__all__ = ['googlenet']
def inception(name, input, channels, filter1, filter3R, filter3, filter5R,
filter5, proj):
cov1 = paddle.layer.img_conv(
name=name + '_1',
input=input,
filter_size=1,
num_channels=channels,
num_filters=filter... | fc_o1 = paddle.layer.fc(name="fc_o1",
input=conv_o1,
size=1024,
layer_attr=paddle.attr | .Extra(drop_rate=0.7),
act=paddle.activation.Relu())
out1 = paddle.layer.fc(input=fc_o1,
size=class_dim,
act=paddle.activation.Softmax())
# fc for output 2
pool_o2 = paddle.layer.img_pool(
name="pool_o2",
inpu... |
projectcalico/calico-neutron | neutron/agent/metadata/config.py | Python | apache-2.0 | 3,403 | 0 | # Copyright 2015 OpenStack Foundation.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | for ssl")),
cfg.StrOpt('endpoint_type',
default='adminURL',
help=_("Network service endpoint type to pull from "
"the keystone catalog")),
cfg.StrOpt('nova_metadata_ip', default='127.0.0.1',
help=_("IP address used by Nova metadata server | .")),
cfg.IntOpt('nova_metadata_port',
default=8775,
help=_("TCP Port used by Nova metadata server.")),
cfg.StrOpt('metadata_proxy_shared_secret',
default='',
help=_('Shared secret to sign instance-id request'),
secret=True),
... |
MJB47/Jokusoramame | migrations/versions/9a0f78ff57d6_add_tagalias_table.py | Python | mit | 1,126 | 0.008881 | """Add TagAlias table
Revision ID: 9a0f78ff57d6
Revises: d19881f4c045
Create Date: 2017-03-19 15:34:30.271997
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '9a0f78ff57d6'
down_revision = 'd19881f4c045'
branch_labels = None
depends_on = None
def upgra | de():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('tag_alias',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('alias_name', sa.String( | ), nullable=False),
sa.Column('tag_id', sa.Integer(), nullable=True),
sa.Column('guild_id', sa.BigInteger(), nullable=True),
sa.Column('user_id', sa.BigInteger(), nullable=True),
sa.ForeignKeyConstraint(['guild_id'], ['guild.id'], ),
sa.ForeignKeyConstraint(['tag_id'], ['tag.id'], ),
sa.ForeignK... |
Matoking/pastebin-django | users/views.py | Python | unlicense | 14,332 | 0.012071 | from django.shortcuts import render
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout, update_session_auth_hash
from django.core.exceptions import ObjectDoesNotExist
from django.core.cache import cache
from django.http im... | e.objects.filter(user=profile_user, removed=Paste.NO_REMOVAL).filter(hidden=Fa | lse).count()
cache.set("user_public_paste_count:%s" % profile_user.username, total_paste_count)
elif total_paste_count == None and request.user == profile_user:
total_paste_count = Paste.objects.filter(user=profile_user, removed=Paste.NO_REMOVAL).count()
cache.set("user_paste_count:%s" % pro... |
Sergey19940808/OurFoto | repository_our_fotos/urls.py | Python | mit | 671 | 0.034277 | # Imports
from django.conf.urls import url
from .models import OurFoto
from .views import HomeFoto, ShowFoto, DeleteFoto, AddFoto, \
Edit | Foto, SearchFoto
# Urls for app
urlpatterns = [
url(r'^$', HomeFoto.as_view(model = OurFoto), name = 'index'),
url(r'^foto/(?P<pk>\d+)/$', ShowFoto.as_view(model = OurFoto), name = 'foto'),
url(r'^add_foto/$', AddFoto.as_view(), name = 'add_foto'),
url(r'^edit_foto/(?P<pk>\d+)/$', EditFoto.as_view(mode... | _foto'),
url(r'^delete_foto/(?P<pk>\d+)/$', DeleteFoto.as_view(model = OurFoto), name = 'delete_foto')
]
|
Rootbuzz/Django-Socialtags | socialtags/templatetags/social_tags.py | Python | mit | 1,400 | 0.007143 | from django.template import Library
from django.conf import settings
if "django.contrib.sites" in settings.INSTALLED_APPS:
from django.contrib.sites.models import Site
current_domain = lambda: Site.objects.get_current().domain
elif getattr(settings, "SITE_DOMAIN", None):
current_domain = lambda: settings.... |
@register.inclusion_tag('social_tags/twitter.html')
def twitter_share(url=None):
url = fully_qualified(url)
return locals()
@register.inclusion_tag('social_tags/facebook.html')
def fac | ebook_share(url=None):
url = fully_qualified(url)
return locals()
@register.inclusion_tag('social_tags/linkedin.html')
def linkedin_share(url=None):
url = fully_qualified(url)
return locals()
@register.inclusion_tag('social_tags/email.html')
def email_share(url=None):
url = fully_qualified(url)
... |
dvalcarce/filmyou-web | src/apps/films/models.py | Python | apache-2.0 | 9,791 | 0.000511 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db import models
from userena.models import UserenaBaseProfile
from caching.base import CachingManager, CachingMixin
from apps.utils.db import retrieve_i... | er = models.URLField(null=True)
awards = models.PositiveIntegerField(null=True)
updated = models.DateField(null=True)
poster_ | file = models.ImageField(upload_to='posters', null=True)
n_votes = models.PositiveIntegerField(default=0)
sum_votes = models.FloatField(default=0)
directors = models.ManyToManyField(Person, related_name="director")
writers = models.ManyToManyField(Person, related_name="writer")
casts = models.Many... |
dantebarba/docker-media-server | plex/Sub-Zero.bundle/Contents/Libraries/Shared/dateutil/test/test_parser.py | Python | gpl-3.0 | 31,922 | 0.000377 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from ._common import unittest
from datetime import datetime, timedelta, date
from dateutil.tz import tzoffset
from dateutil.parser import *
import six
from six import assertRaisesRegex, PY3
from six.moves import StringIO
class ParserTest(unittest.TestC... | parserinfo=rus_parserinfo()),
datetime(2015, 9, 10, 10, 20))
def testParseWithNulls(self):
# This re | lies on the from __future__ import unicode_literals, because
# explicitly specifying a unicode literal is a syntax error in Py 3.2
# May want to switch to u'...' if we ever drop Python 3.2 support.
pstring = '\x00\x00August 29, 1924'
self.assertEqual(parse(pstring),
... |
anthonyabeo/MeetNEat | api/oauth.py | Python | unlicense | 3,846 | 0.00026 | import json
from flask import session
from flask import url_for, redirect, request
from rauth import OAuth1Service, OAuth2Service
from meetneat.config import OAUTH_CREDENTIALS
class OAuthSignIn(object):
providers = None
def __init__(self, provider_name):
self.provider_name = provider_name
c... | auth_session(
request_token[0],
request_token[1],
data={'oauth_verifier': request.args['oauth_verifier']}
)
me = oauth_session.get('account/verify_credentials.json').json()
social_id = 'twitter$' + str(me.get('id'))
username = me.get('screen_name')
... | does not provide email
|
Caveat4U/home_automation | trigger.py | Python | gpl-2.0 | 793 | 0.011349 | fr | om abc import ABCMeta,abstractmethod
from my_hue import *
# Would dynamically choose a trigger based on trigger type
def trigger_factory(trigger_type):
return None
class Trigger(object):
__m | etaclass__ = ABCMeta
def __init__(self):
self.action()
@abstractmethod
def action(self):
pass
class IClickerTrigger(object):
def __init__(self, clicker_id, response_info, time_of_trigger, sequence_number):
super(IClickerTrigger, self).__init__()
self.clicker_id = ... |
LCAS/teaching | turtlebot_simulator/turtlebot_stdr/nodes/tf_connector.py | Python | mit | 741 | 0.002699 | #!/usr/bin/env python
__author__ = 'mehdi tlili'
import rospy
fr | om tf2_msgs.msg import TFMessage
import tf
class Remapper(object):
def __init__(self):
self.br = tf.TransformBroadcaster()
rospy.Subscriber("/tf", TFMessage, self.tf_remapper)
def tf_remapper(self, msg):
if msg.transforms[0].header.frame_id == "/robot0":
self.br.sendTrans... | tf.transformations.quaternion_from_euler(0, 0, 0),
rospy.Time.now(),
"base_footprint",
"robot0")
if __name__ == '__main__':
rospy.init_node('remapper_nav')
remapper = Remapper()
rospy.spin()
|
Stratoscale/inaugurator | inaugurator/tests/test_idlistener.py | Python | apache-2.0 | 5,274 | 0.000948 | import os
import sys
import mock
import logging
import unittest
from inaugurator.server import idlistener
from inaugurator.tests.common import PikaChannelMock
class Test(unittest.TestCase):
def setUp(self):
self.consumeCallback = mock.Mock()
self.channel = PikaChannelMock(self)
self.expect... | assertFalse(self.channel.declaredQueue | s)
if not allowOtherRequests:
self.assertFalse(self.channel.requests)
self.assertFalse(self.channel.queue_bind.called)
self.assertFalse(self.channel.basic_consume.called)
if __name__ == '__main__':
_logger = logging.getLogger("inaugurator.server")
handler = logging.... |
box-community/box-weekly-stats | add_shared_to_group.py | Python | apache-2.0 | 3,242 | 0.005861 | """ Copyright 2015 Kris Steinhoff, The University of Michigan
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or ag... | unt % 2 == 1:
return values[count/2]
else:
return ( values[(count/2)-1] + values[count/2] ) / 2.0
if __na | me__ == "__main__":
parser = optparse.OptionParser()
parser.add_option("-d", "--dry-run", action="store_true", dest="dry_run", default=False, help="simulate changes")
(options, args) = parser.parse_args()
box = box.BoxApi()
config = ConfigParser.ConfigParser()
settings_file = os.path.join(os.p... |
winnerineast/Origae-6 | origae/model/__init__.py | Python | gpl-3.0 | 352 | 0 | # Copyright (c) 2014-2017, NVIDIA CORPORATION. All rights reserved.
from __future__ import absolute_import
from | .images import (
ImageClassificationModelJob,
GenericImageModelJob,
ImageModelJob,
)
from | .job import ModelJob
__all__ = [
'ImageClassificationModelJob',
'GenericImageModelJob',
'ImageModelJob',
'ModelJob',
]
|
gallupliu/QA | preprocess/data_helper.py | Python | apache-2.0 | 4,978 | 0.004219 | #coding=utf-8
import codecs
import logging
import numpy as np
import os
from collections import defaultdict
# define a logger
logging.basicConfig(format="%(message)s", level=logging.INFO)
def load_embedding(filename, embedding_size):
"""
load embedding
"""
embeddings = []
word2idx = defaultdict(... | qids.append(result)
except Exception as e:
logging.error("load test error," , e)
| finally:
rf.close()
logging.info("load test data finish!")
return ori_quests, cand_quests, labels, qids
def batch_iter(ori_quests, cand_quests, batch_size, epoches, is_valid=False):
"""
iterate the data
"""
data_len = len(ori_quests)
batch_num = int(data_len / batch_size)... |
disqus/psycopg2-managed-connection | setup.py | Python | apache-2.0 | 971 | 0.00309 | import os
from setuptools import (
find_packages,
setup,
)
from setuptools.command.test import test
PACKAGE_DIR = 'src'
class PyTest(test):
def finalize_options(self):
test.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
import ... | nnection',
description='Thread-safe connection manager for psycopg2 connections.',
version='1.0.0',
author='Ted Kaemming, Disqus',
author_email='ted@disqus.com',
license='Apache License 2.0',
setup_requires=(
'setuptools>=8.0',
),
install_requires=(
'psycopg2~=2.6' | ,
),
packages=find_packages(PACKAGE_DIR),
package_dir={
'': PACKAGE_DIR,
},
zip_safe=False,
cmdclass = {
'test': PyTest,
},
tests_require=(
'pytest~=2.7',
),
)
|
svviz/svviz | src/ssw/ssw_wrap.py | Python | mit | 15,367 | 0.00898 | """
@package ssw_wrap
@brief Simple python wrapper for SSW align library
To use the dynamic library libssw.so you may need to modify the LD_LIBRARY_PATH environment
variable to include the library directory (export LD_LIBRARY_PATH=$PWD) or for definitive
inclusion of the lib edit /etc/ld.so.conf and add the path or the... | es import *
import os
def _get_libssw_path():
base = os.path.dirname(__file__)
matches = [x for x in os.listdir(base) if (x.startswith("libssw") & x.endswith(".so"))]
if len(matches) < 1:
raise Exception("Couldn't find libssw.so in this directory: '{}'".format(base))
return os.path.join(base, m... | os.path.join(os.path.dirname(__file__), 'libssw.so'))
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
class CAlignRes(Structure):
"""
@class SSWAlignRes
@brief ctypes Structure with s_align struct mapping returned by SSWAligner.Align func
Co... |
TrimBiggs/calico | calico/etcddriver/driver.py | Python | apache-2.0 | 43,284 | 0.000046 | # -*- coding: utf-8 -*-
# Copyright 2015 Metaswitch Networks
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | hem out.
"""
try:
while not self._stop_event.is_set():
for msg_type, msg in self._msg_reader.new_messages(timeout=1):
if msg_type == MSG_TYPE_INIT:
| # Init message, received at start of day.
self._handle_init(msg)
elif msg_type == MSG_TYPE_CONFIG:
# Config message, expected after we send the raw
# config to Felix.
self._handle_config(msg)
... |
imito/odin | odin/utils/progbar.py | Python | mit | 17,930 | 0.010095 | # -*- coding: utf-8 -*-
##################################################################
# Example of usage:
##################################################################
from __future__ import print_function, division, absolute_import
import sys
import time
import inspect
from numbers import Number
from dateti... | * any report key contain "confusionmatrix" will be printed out using
`print_confusion`
* any report key
"""
FP = sys.stderr
def __init__(self, target, interval=0.08, keep=False,
print_progress=True, print_report=True, print_summary=False,
count_func=None, report_func=No... | e(target, Number):
self.target = int(target)
self.__iter_obj = None
elif hasattr(target, '__len__'):
self.target = len(target)
self.__iter_obj = target
else:
raise ValueError("Unsupport for `target` type: %s" %
str(target.__class__))
self._seen_so_far = ... |
Yarrick13/hwasp | tests/wasp1/AllAnswerSets/3col_aggregates_1_5_enc2.test.py | Python | apache-2.0 | 14,386 | 0.001738 | input = """
% Guess colours.
chosenColour(N,C) | notChosenColour(N,C) :- node(N), colour(C).
% At least one color per node.
:- #count{ C : chosenColour(X,C) } > 1, node(X).
:- #count{ C : chosenColour(X,C) } < 1, node(X).
% No two adjacent nodes have the same colour.
:- link(X,Y), X<Y, chosenColour(X,C), ch... | chosenColour(3,green0), chosenColour(4,blue0), chosenColour(5,red0), colour(blue0), colour(green0), colour(red0), link(1,2), link(1,3), link(2,1), link(2,3), link(3,1), link(3,2), link(3,5), link(4,5), link(5,3), link | (5,4), node(1), node(2), node(3), node(4), node(5), notChosenColour(1,green0), notChosenColour(1,red0), notChosenColour(2,blue0), notChosenColour(2,green0), notChosenColour(3,blue0), notChosenColour(3,red0), notChosenColour(4,green0), notChosenColour(4,red0), notChosenColour(5,blue0), notChosenColour(5,green0)}
{chosen... |
Anthony25/barython | barython/widgets/base.py | Python | bsd-3-clause | 10,749 | 0.000558 | #!/usr/bin/env python3
import fcntl
import logging
import os
import shlex
import subprocess
import threading
from barython.hooks import HooksPool
from barython.tools import splitted_sleep
logger = logging.getLogger("barython")
def protect_handler(handler):
def handler_wrapper(self, *args, **kwargs):
tr... | Used for callbacks
self.screens = screens if screens is not None else set()
#: pool of hooks
self.hooks = HooksPool(parent=self)
#: run in an infinite loop or not
self.infinite = infinite
#: event to stop the widget
self._stop = threading.Event()
self._... | n()
self._lock_update = threading.Condition()
self._refresh_lock = threading.Semaphore(2)
class TextWidget(Widget):
text = ""
def update(self):
with self._lock_update:
new_content = self.decorate_with_self_attributes(
self.organize_result(self.text)
... |
JARR-aggregator/JARR | newspipe/commands.py | Python | agpl-3.0 | 5,322 | 0.002067 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import os
from dateutil.relativedelta import relativedelta
from datetime import datetime, date
import click
from werkzeug.security import generate_password_hash
import newspipe.models
from newspipe.bootstrap import application, db
from newspipe.controller... | {}...".format(user.nickname))
| db.session.commit()
except:
db.session.rollback()
print("Inactive users deleted.")
@application.cli.command("disable_inactive_users")
@click.option("--last-seen", default=6, help="Number of months since last seen.")
def disable_inactive_users(last_seen):
"Disable inactive users (in... |
bearicc/python-wavelet-transform | mycwt.py | Python | agpl-3.0 | 1,948 | 0.010267 | """ ------------------------------
bior2_6
cwt
by BEAR, 05/04/14
------------------------------ """
import scipy as sp
import numpy as np
from scipy.signal import convolve
#import pywt
_scale_max = 1024
_scale_max = int(2**(sp.ceil(sp.log2(_scale_max))))
tmp = np.loadtxt('bior2.6_1024.txt')
_x_bior2_6 = tmp[:,0]
... | :] = convolve(x, wavelet(length, i), mode='same')
if bplot: |
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
plt.ion()
fig = plt.figure(num=None, figsize=(14,5), dpi=100, facecolor='w', edgecolor='k')
plt.clf()
gs = gridspec.GridSpec(3, 1)
ax1 = fig.add_subplot(gs[0,0])
ax1.plot(x,'b-')
... |
Vauxoo/stock-logistics-warehouse | stock_orderpoint_generator/wizard/__init__.py | Python | agpl-3.0 | 35 | 0 | fr | om . impor | t orderpoint_generator
|
eschleicher/flask_shopping_list | venv/lib/python3.4/site-packages/argh/interaction.py | Python | mit | 2,403 | 0.00125 | # coding: utf-8
#
# Copyright © 2010—2014 Andrey Mikhaylenko and contributors
#
# This file is part of Argh.
#
# Argh is free software under terms of the GNU Lesser
# General | Public License version 3 (LGPLv3) as published by the Free
# Software Foundation. See the file README.rst for copying conditions.
#
"""
Interaction
~~~~~~~~~~~
"""
from argh.compat import text_type
from argh.io import safe_input
__all__ = ['confirm', 'safe_input']
def confirm(action, default=None, skip=False):
... | "Apply changes". A question mark
will be appended.
:param default:
`bool` or `None`. Determines what happens when user hits :kbd:`Enter`
without typing in a choice. If `True`, default choice is "yes". If
`False`, it is "no". If `None` the prompt keeps reappearing until user
... |
PythonSanSebastian/python-rtmbot | plugins/ep_volunteer/catch_all.py | Python | mit | 38 | 0 |
def | catch_all(data):
prin | t(data)
|
pigmonkey/django-wishlist | wishlist/urls.py | Python | bsd-3-clause | 443 | 0.002257 | from django.conf.urls.defaults import *
from wishlist.models import Item
from wishlist.views impor | t add_item, delete_item, wishlist, bookmarklet
urlpatterns = patterns('',
(r'^add/$', add_item),
(r'^(?P<id>\d+)/delete/$', delete_item),
url(r'^tag/(?P<querytag>[^/]+)/$', view=wishlist, name="items_by_tag"),
(r'^bookmarklet/$', bookmarklet),
(r'^sort/(?P<sort_by>\w+)/(?P<sort>\w+)/$', wish | list),
(r'^$', wishlist),
)
|
bacaldwell/ironic | ironic/tests/unit/drivers/modules/ilo/test_vendor.py | Python | apache-2.0 | 9,258 | 0 | # Copyright 2015 Hewlett-Packard Development Company, L.P.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2... | '}, [])
@mock.patch.object(iscsi_deploy.VendorPassthru, 'continue_deploy' | ,
spec_set=True, autospec=True)
@mock.patch.object(ilo_common, 'update_secure_boot_mode', autospec=True)
@mock.patch.object(ilo_common, 'update_boot_mode', autospec=True)
def test_continue_deploy(self,
func_update_boot_mode,
fu... |
scott-w/pyne-django-tutorial | chatter/chatter/urls.py | Python | mit | 1,113 | 0 | from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns(
'',
# Examples:
# url(r'^$', 'chatter.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'', include('chatter.base.urls')),
url(r'^admin/', include(admin.site.urls)... | gin/$', 'login', name='login'),
url(r'^logout/$', 'logout_then_login', name='logout'),
url(r'^reset/$', 'password_reset', name='password_reset'),
url(r'^reset/done/$', 'password_reset_done', name='password_reset_done'),
url(
r'^reset/confirm/'
r'(?P<uidb64>[0-9A-Za-z_\-]+)/'
r'(?... | name='password_reset-confirm'),
url(
r'^reset/complete/$',
'password_reset_complete',
name='password_reset_complete'),
)
|
a25kk/newe | src/newe.sitecontent/newe/sitecontent/testing.py | Python | mit | 1,963 | 0 | # -*- coding: utf-8 -*-
"""Base module for unittesting."""
from plone.app.testing import applyProfile
from plone.app.testing import FunctionalTesting
from plone.app.testing import IntegrationTesting
from plone.app.testing import login
from plone.app.testing import PLONE_FIXTURE
from plone.app.testing import PloneSandb... | .app.testing import setRoles
from plone.app.tes | ting import TEST_USER_ID
from plone.app.testing import TEST_USER_NAME
from plone.testing import z2
import unittest2 as unittest
class neweSitecontentLayer(PloneSandboxLayer):
defaultBases = (PLONE_FIXTURE,)
def setUpZope(self, app, configurationContext):
"""Set up Zope."""
# Load ZCML
... |
airwoot/timeline-hack-core | app/resources.py | Python | mit | 7,302 | 0.015338 | from flask import current_app, redirect, url_for, request, session, flash, send_file
from flask.ext import restful
from flask.ext.login import login_required, current_user, login_user, logout_user
import twitter
from request_parsers import *
from datetime import datetime
from models import *
from rauth.service import O... | ul.abort(500, message = 'internal server error.')
class CreateList(restful. | Resource):
@login_required
def get(self):
args = create_list_parser.parse_args()
user = current_user
try:
return controllers.create_list(user, args['screen_name'])
pass
except twitter.TwitterError as e:
if e.message[0]['code'] == 34:
... |
MTG/dunya | hindustani/migrations/0001_initial.py | Python | agpl-3.0 | 25,073 | 0.004706 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.9 on 2016-09-19 15:30
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import hindustani.models
class Migration(migrations.Migration):
initial = True
dependencies = [
('data', '0001_in... | tyle, models.Model),
),
migrations.CreateModel(
name='Form',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=50)),
| ('common_name', models.CharField(max_length=50)),
('uuid', models.UUIDField(db_index=True)),
('description', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+', to='data.Description')),
('images', models.ManyToMany... |
ascott1/regulations-site | regulations/tests/layers_paragraph_markers_tests.py | Python | cc0-1.0 | 1,212 | 0.00165 | from unittest import TestCase
from mock import patch
from regulations.generator.layers.paragraph_markers import *
class ParagraphMarkersLayerTest(TestCase):
@patch('regulations.generator.layers.paragraph_markers.loader')
def test | _apply_layer(self, loader):
pml = ParagraphMarkersLayer({
'1001-12-a': [{'text': '(a)', 'locations': [0]}],
'1001-12-q': [{'text': 'q.', 'locations': [1]}]
})
self.assertEqual([], pml.apply_layer('1002-01-01'))
a = pml.apply_layer('1001-12-a')
sel... | eturn_value.render.call_args[0][0]
self.assertEqual('(a)', call_args['paragraph'])
self.assertEqual('a', call_args['paragraph_stripped'])
q = pml.apply_layer('1001-12-q')
self.assertEqual(1, len(q))
self.assertEqual('q.', q[0][0])
self.assertEqual([1], q[0][2])
c... |
Guidobelix/pyload | module/plugins/crypter/LetitbitNetFolder.py | Python | gpl-3.0 | 1,221 | 0.015561 | # -*- coding: utf-8 -*-
import re
from module.plugins.internal.Crypter import Crypter
class LetitbitNetFolder(Crypter):
__name__ = "LetitbitNet"
__type__ = "crypter"
__version__ = "0.16"
__status__ = "testing"
__pattern__ = r'http://(?:www\.)?letitbit\.net/folder/\w+'
__config__ = [... | "
__authors__ = [("DHMH", "webmaster@pcProfil.de"),
("z00nx", "z00nx0@gmail.com")]
FOLDER_PATTERN = r'<table>(.*)</table>'
LINK_PATTERN = r'<a href="(.+?)" target="_blank">'
def decrypt(self, pyfile):
html = self.load(pyfile.url)
folder = re.search(self.FO... | not found"))
self.links.extend(re.findall(self.LINK_PATTERN, folder.group(0)))
|
llou/panopticon | panopticon/core/actions/service.py | Python | gpl-3.0 | 3,447 | 0.004062 | # service.py is part of Panopticon.
# Panopticon is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# Panopticon is distributed in the h... | ribute_class = ServiceAction
def _get_base_dict(self):
servi | ce_action_class = self.action_launcher_class
actions = {}
defined_action_names = []
for aname, action in self.service._meta["actions"]:
defined_action_names.append(aname)
actions[aname] = action
for rname, role in self.service.roles:
for raname, action... |
shengqh/ngsperl | lib/SmallRNA/updateShortReadParentCount.py | Python | apache-2.0 | 7,328 | 0.019378 | import argparse
import sys
import logging
import os
import csv
class ReadItem:
def __init__(self, sequence, totalCount):
self.Sequence = sequence
self.TotalCount = totalCount
self.SampleMap = {}
class AnnotationItem:
def __init__(self, sequence, totalCount, category, counts):
self.Sequence = seque... | = []
for read in shortReadMap.values():
validSampleCount = len([v for v in read.SampleMap.values() if v >= minReadCount])
if validSampleCount >= minSampleCount:
shortReads.append(read)
else:
shortReads = shortReadMap.values()
shortReads = sorted(shortReads, key=getValue, reverse=True)
... | hortReads = shortReads[0:maxNumber]
logger.info("Reading max mapped reads:" + maxMapped + " ...")
maxmappedReads = {}
with open(maxMapped, 'r') as sr:
for line in sr:
parts = line.split('\t')
logger.info(" Reading " + parts[0] + " ...")
with open(parts[0], 'r') as fin:
while True:
... |
zamattiac/SHARE | providers/edu/iowaresearch/__init__.py | Python | apache-2.0 | 1,863 | 0.000537 | default_app_config = 'providers.edu.iowaresearch.apps.AppConfig'
"""
Example Record
<record>
<header>
<identifier>oai:ir.uiowa.edu:iwp_archive-1227</identifier>
<datestamp>2016-07-05T19:23:14Z</datestamp>
<setSpec>publication:iwp</setSpec>
<setSpec>publication:grad</setSpec>
... | on:harvest</setSpec>
<setSpec>publication:fullharvest</setSpec>
</header>
<metadata>
<oai_dc:dc xmlns:oai_dc="http://www.openarchives.org/OAI/2.0/oai_dc/"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-inst | ance"
xsi:schemaLocation="http://www.openarchives.org/OAI/2.0/oai_dc/
http://www.openarchives.org/OAI/2.0/oai_dc.xsd">
<dc:title>Writing Sample</dc:title>
<dc:creator>Gamerro, Carlos</dc:creator>
<dc:description>
Excerpts from T... |
daniele-athome/kontalk-legacy-xmppserver | kontalk/xmppserver/version.py | Python | gpl-3.0 | 967 | 0 | # -*- coding: utf-8 -*-
"""Version information."""
"""
Kontalk XMPP server
Copyright (C) 2014 Kontalk Devteam <devteam@kontalk.org>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either versi... | License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
NAME = "Kontalk XMPP server"
IDENTITY = "kontalk"
PACKAGE = "kontalk-xmppserver"
VERSION = "devel"
AUTHORS = (
{
"name": "Daniele Ricci", |
"email": "daniele.athome@gmail.com"
},
)
|
camallen/aggregation | experimental/condor/presentation/condor_IBCC.py | Python | apache-2.0 | 9,662 | 0.00859 | #!/usr/bin/env python
__author__ = 'greghines'
import numpy as np
import os
import pymongo
import sys
import cPickle as pickle
import bisect
import random
import csv
import matplotlib.pyplot as plt
if os.path.exists("/home/ggdhines"):
base_directory = "/home/ggdhines"
else:
base_directory = "/home/greg"
def i... | = sum([1 for x in X_negative if x >= alpha])
negative_rate = negative_count/float(len(X_negative))
roc_X.append(negative_rate)
roc_Y.append(positive_rate)
#print roc_X
plt.plot(roc_X,roc_Y,color="red")
X_positive = []
X_negative = []
#repeat with MV
for subject_index,zooniverse_id in enumerate(big_sub... | ondor = gold_condor[subject_index]
if wreness_condor == 0:
X_negative.append(np.mean(votes))
else:
X_positive.append(np.mean(votes))
alpha_list = X_negative[:]
alpha_list.extend(X_posi |
sunlightlabs/wikipedia-dump-tools | wikitools/__init__.py | Python | gpl-3.0 | 71 | 0 | # -*- coding: utf-8 -*-
from exceptions | imp | ort DropPage, AbortProcess
|
DreamSourceLab/DSView | libsigrokdecode4DSL/decoders/1-spi/pd.py | Python | gpl-3.0 | 13,821 | 0.002532 | ##
## This file is part of the libsigrokdecode project.
##
## Copyright (C) 2011 Gareth McMullin <gareth@blacksphere.co.nz>
## Copyright (C) 2012-2014 Uwe Hermann <uwe@hermann-uwe.de>
## Copyright (C) 2019 DreamSourceLab <support@dreamsourcelab.com>
##
## This program is free software; you can redistribute it and/or mo... | self.misobits = []
self.mosibits = []
self.misobytes = []
self.mosibytes = []
self.ss_block = -1
self.samplenum = -1
self.ss_transfer = -1
self.cs_was_deasserted = False
self.have_cs = self.have_miso = self.have_mosi = None
def start(self):
... | srd.OUTPUT_ANN)
self.out_binary = self.register(srd.OUTPUT_BINARY)
self.out_bitrate = self.register(srd.OUTPUT_META,
meta=(int, 'Bitrate', 'Bitrate during transfers'))
self.bw = (self.options['wordsize'] + 7) // 8
def metadata(self, key, value):
if key == srd.SRD_CONF... |
cycladesnz/chambersAndCreatures | src/effects/dv_effects.py | Python | gpl-2.0 | 3,581 | 0.006981 | import copy
from pdcglobal import *
from .effect import Effect
import dungeon
class FloatingEyeGazeEffect(Effect):
def __init__(self, host, owner):
dur = d(10)
Effect.__init__(self, dur, host, owner)
weaponinfotext = 'Stuns the enemy'
def tick(self):
self.host.timer += ... | Eye`s gaze!')
else:
self.host.game.shout('%s is stu | nned by the Floating Eye`s gaze!' % (self.host.name))
Effect.tick(self)
class AcidSplatterEffect(Effect):
notrigger=[]
def __init__(self, host, owner):
dur = 1
Effect.__init__(self, dur, host, owner)
actors = owner.game.get_all_srd_actors(owner.pos())
for act in... |
dchaplinsky/declarations.com.ua | declarations_site/catalog/elastic_models.py | Python | mit | 66,029 | 0.001889 | import re
import os.path
from operator import or_
from functools import reduce
from datetime import date
import logging
import urllib.parse
from django.conf import settings
from django.urls import reverse
from django.db.models.functions import ExtractYear
from django.db.models import Sum, Count
from django.template.lo... | w_family_string
from .converters import PaperToNACPConverter, ConverterError
from .translator import HTMLTranslator
logger = logging.getLogger(__name__) |
class NoneAwareDate(Date):
"""Elasticsearch DSL Date field chokes on None values and parses empty
strings as current date, hence the workaround.
TODO: move this upstream in some form."""
def _to_python(self, data):
if data is None:
return data
return super(NoneAwareDate, ... |
lnielsen/invenio | invenio/modules/messages/models.py | Python | gpl-2.0 | 8,905 | 0.007748 | # -*- coding: utf-8 -*-
#
## This file is part of Invenio.
## Copyright (C) 2011, 2012 CERN.
##
## Invenio is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (at your opti... | ullable=False)
subject = db.Column(db.Text, nullable=False)
body = db.Column(db.Text, nullable=True)
sent_date = db.Column(db.DateTime, nullable=False,
server_default='1900-01-01 00:00:00') # db.func.now() -> 'NOW()'
receiv | ed_date = db.Column(db.DateTime,
server_default='1900-01-01 00:00:00')
user_from = db.relationship(User, backref='sent_messages')
#recipients = db.relationship(User,
# secondary=lambda: UserMsgMESSAGE.__table__,
# collection_class=set)
... |
oliverhr/odoo | addons/stock/stock.py | Python | agpl-3.0 | 269,349 | 0.005732 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004 | -2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This pro... | ITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.