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
bgroveben/python3_machine_learning_projects
oreilly_GANs_for_beginners/oreilly_GANs_for_beginners/introduction_to_ml_with_python/mglearn/mglearn/plot_knn_regression.py
Python
mit
1,285
0.000778
import numpy as np import matplotlib.pyplot as plt from sklearn.neighbors import KNeighborsRegressor from sklearn.metrics import euclidean_distances from .datasets import make_wave from .plot_helpers import cm3 def plot_knn_regression(n_neighbors=1): X, y = make_wave(n_samples=40) X_test = np.array([[-1.5],...
ighbor, 0] - x[0], y[neighbor] - y_, head_width=0, fc='k', ec='k') train, = plt.plot(X, y, 'o', c=cm3(0)) test, = plt.plot(X_test, -3 * np.ones(len(X_test)), '*', c=cm3(2), markersize=20) pred, = plt.plot(X_test, y_pred, '*', c=cm3(0), markersize=20) plt.v...
5)) plt.ylim(-3.1, 3.1) plt.xlabel("Feature") plt.ylabel("Target")
songmonit/CTTMSONLINE
addons/account/report/account_aged_partner_balance.py
Python
agpl-3.0
21,185
0.005806
# -*- 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...
] self.localcontext.update({ 'time': time, 'get_lines_with_out_partner': self._get_lines_with_out_partner, 'get_lines': self._get_lines, 'get_total': self._get_total, 'get_direction': self._get_direction, 'get_for_period': self._get_for_per...
'get_partners':self._get_partners, 'get_account': self._get_account, 'get_fiscalyear': self._get_fiscalyear, 'get_target_move': self._get_target_move, }) def set_context(self, objects, data, ids, report_type=None): obj_move = self.pool.get('account.mov...
stanford-mast/nn_dataflow
nn_dataflow/nns/lstm_phoneme.py
Python
bsd-3-clause
1,086
0.000921
""" $lic$ Copyright (C) 2016-2020 by Tsinghua University and The Board of Trustees of Stanford University This pro
gram is free software: you can redistribute it and/or modify it under the terms of the Modified BSD-3 License as published by the Op
en Source Initiative. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the BSD-3 License for more details. You should have received a copy of the Modified BSD-3 License along with thi...
UXE/local-edx
lms/djangoapps/instructor_task/tests/test_api.py
Python
agpl-3.0
9,831
0.003764
""" Test for LMS instructor background task queue management """ from bulk_email.models import CourseEmail, SEND_TO_ALL from courseware.tests.factories import UserFactory from xmodule.modulestore.exceptions import ItemNotFoundError from instructor_task.api import ( get_running_instructor_tasks, get_instructor_...
task_function(self.create_task_request(self.instructor), location) def test_submit_rescore_all(self): self._test_submit_task(submit_rescore_problem_for_all_students) def test_submit_rescore_student(self): self._test_
submit_task(submit_rescore_problem_for_student, self.student) def test_submit_reset_all(self): self._test_submit_task(submit_reset_problem_attempts_for_all_students) def test_submit_delete_all(self): self._test_submit_task(submit_delete_problem_state_for_all_students) class InstructorTaskCou...
junwoo091400/MyCODES
Projects/FootPad_Logger/logged_data_analyzer_LSTM/Train.py
Python
gpl-3.0
4,440
0.04009
from Base import * from RNN_LSTM import * from Data_manipulation import * import ipdb def log_2_Batch_Y32(log): # Encodes Y as 0~31. print('log_2_Batch. log Data raw count:',len(log.Data)*200,str(log)) X = []#Must be 5 seconds/ each. Y = [] idx = 0 for datum in log.Data:#Each server uploads -> 20 seconds. for ...
Value_Idx(out) for out in one_hot_output_series]) #ipdb.set_trace() plt.subplot(2, 3, batch_series_idx + 2) plt.cla() plt.axis([0, backprop_length, 0, num_classes]) left_offset = range(backprop_length) #plt.bar(left_offset, batchX[batch_series_idx, :], width=1, color="blue") plt.bar(left_offset, batchY[ba...
single_output_series * 0.5, width=1, color="green") #ipdb.set_trace()#REMOVE me. plt.draw() plt.pause(0.0001) def main(): logs = get_Logs('Mega.csv') X_bat, Y_bat = [], [] Log_bat = [] for flg in logs: if( not isIgnored(flg)): x,y = log_2_Batch_Y32(flg) X_bat.append(x) Y_bat.append(y) Log_bat.a...
mitdbg/modeldb
client/verta/verta/configuration/__init__.py
Python
mit
293
0
# -*- coding: utf-8 -*- """Utilities for configuration
versioning.""" from verta._internal_utils import documentation from ._configuration import _Configuration from ._hyperparameters import Hyperparameters documentation.reassign_module( [Hyperpa
rameters], module_name=__name__, )
jeffbuttars/upkg
upkg/cmds/status.py
Python
gpl-2.0
1,988
0.003018
import logging logger = logging.getLogger('upkg') from blessings import Terminal from cmds.base import BaseCmd from upkg.lib import Repo class Cmd(BaseCmd): """Docstring for Search """ name = 'status' help_text = ("Get the status of what's installed") aliases = ['st', 'stat'] def build(self): ...
logger.debug("repos: %s", repos) if repos: rlist = [Repo(name=x) for x in repos] else: # Update them all! rlist = Repo.installed_list() logger.debug("repo list: %s", rlist) t = Terminal() for r in rlist: logger.debug("calling ...
me)) / 2) - 1) print(t.magenta("*" * w)) print(t.magenta("{} {} {}".format(" " * nw, r.name, " " * nw))) if (rpw + 2) < w: print(t.magenta("{} {} {}".format(" " * bw, rp, " " * bw))) else: print(t.magenta(rpw)) print(t.magenta("...
nipunreddevil/bayespy
bayespy/utils/tests/test_linalg.py
Python
gpl-3.0
6,989
0.011447
###################################################################### # Copyright (C) 2013 Jaakko Luttinen # # This file is licensed under Version 3.0 of the GNU General Public # License. See LICENSE for a text of the license. ###################################################################### ####################...
[[1], [2]], [[1,2,3], [4,5,6]]) # Do not accept less than 2-D arrays: (2) * (2,2) self.assertRaises(ValueError,
linalg.dot, [1,2], [[1,2,3], [4,5,6]]) class TestBandedSolve(TestCase): def test_block_banded_solve(self): """ Test the Gaussian elimination algorithm for block-banded matrices. """ # # Cre...
toomore/grs
test_unittest.py
Python
mit
5,685
0.000177
# -*- coding: utf-8 -*- ''' Unittest ''' import grs import unittest from datetime import datetime from types import BooleanType from types import NoneType class TestGrs(unittest.TestCase): def get_data(self): self.stock_no = '2618' self.data = grs.Stock(self.stock_no) def test_stock(self): ...
oving_average(self): self.get_data() result = self.data.moving_average(3) assert isinstance(result[0], list) assert isinstance(result[1], int) assert result == self.data.MA(3) def test_moving_average_value(self): self.get_data() result = self
.data.moving_average_value(3) assert isinstance(result[0], list) assert isinstance(result[1], int) assert result == self.data.MAV(3) def test_moving_average_bias_ratio(self): self.get_data() result = self.data.moving_average_bias_ratio(6, 3) assert isinstance(result[...
accuen/rqt
lib/rqt/cli_parser.py
Python
apache-2.0
6,256
0.006394
# Copyright 2014 Accuen # # 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 agreed to in writing,...
r def mk_argparser(): desc = "Utility for running Redshift queries." epi = dedent("""\ Try "rqt SUBCOMMAND -h" for help on a spec
ific subcommand. Try "rqt help" for extended help. """) parser = argparse.ArgumentParser(description=desc, epilog=epi, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("--config", metavar="JSON_FILE...
opennorth/inventory
inventory/migrations/0006_auto_20150217_2002.py
Python
mit
1,132
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('inventory', '0005_remove_distribution_validation_extension'), ] operations = [ migrations.RenameField( model_nam...
ame='distribution', old_name='validation_encoding', new_name='http_charset', ), migrations.RenameField( mo
del_name='distribution', old_name='validation_content_type', new_name='http_content_type', ), migrations.RenameField( model_name='distribution', old_name='validation_headers', new_name='http_headers', ), migrations.AddField( ...
MartinSeeler/euler-python
problem-2.py
Python
mit
252
0.007937
sum_of_even = 0 prev
= 0 current = 1 next = current while (prev+current) <= 4000000: next = prev + current prev = current current = next if next % 2 == 0: sum_of_even += next print "The sum of all even is %s" % s
um_of_even
51reboot/actual_09_homework
09/liubaobao/cmdb_V4/manage.py
Python
mit
121
0.033058
#encoding:utf-
8 from user import app if __name__ == '__main__': ap
p.run(host='0.0.0.0',port=9002,debug=True)
sjsucohort6/openstack
python/venv/lib/python2.7/site-packages/openstack/tests/unit/network/v2/test_quota.py
Python
mit
1,695
0
# 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 agreed to in writing, software # distributed under t...
on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either
express or implied. See the # License for the specific language governing permissions and limitations # under the License. import testtools from openstack.network.v2 import quota IDENTIFIER = 'IDENTIFIER' EXAMPLE = { 'floatingip': 1, 'network': 2, 'port': 3, 'tenant_id': '4', 'router': 5, 's...
zenodo/invenio
invenio/legacy/elmsubmit/scripts/elmsubmit.py
Python
gpl-2.0
2,040
0.00049
#!@PYTHON@ # -*- mode: python; coding: utf-8;
-*- # # This file is part of In
venio. # Copyright (C) 2004, 2005, 2006, 2007, 2008, 2010, 2011 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 option) any later version. # # I...
Evzdrop/celery-2619-repro
celery_repro/repro/tasks/incoming.py
Python
mit
524
0.005725
import json import requests from celery import shared_task from repro.monitoring.custom_metrics import custom_metric_timed_nod
e from celery.utils.log import get_task_logger logger = get_task_logger(__name__) @shared_task() @custom_metric_timed_node('Custom/incoming/twitter/2') def incoming(tweet, *args, **kwargs): parsed = json.loads(tweet) return parsed @custom_metric_timed_node('Custom/incoming/infer_location/3
') def infer_location(post): requests.get('https://yahoo.com') # Fake IO request return
95subodh/Leetcode
020. Valid Parentheses.py
Python
mit
474
0.048523
#Given a string containing just the characters '(', ')', '{', '}', '
[' and ']', determine if the input string is valid. # #The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not. class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ l=[] for i in s: if i in '[({': l.append(i) el
if len(l) and ord(i)<ord(l[-1])+3: l.pop() else: return False return not len(l)
JioCloud/horizon
openstack_dashboard/dashboards/admin/domains/tables.py
Python
apache-2.0
6,160
0.000325
# Copyright 2013 Hewlett-Packard Development Company, L.P. # # 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 requir...
_url, param]) class CreateDomainLink(tables.LinkAction): name = "create" verbose_name = _("Create Domain") url = constants.DOMAINS_CREATE_URL classes =
("ajax-modal",) icon = "plus" policy_rules = (('identity', 'identity:create_domain'),) def allowed(self, request, domain): return api.keystone.keystone_can_edit_domain() class EditDomainLink(tables.LinkAction): name = "edit" verbose_name = _("Edit") url = constants.DOMAINS_UPDATE_URL ...
staticfloat/pybladeRF
bladeRF/tools/waterfall.py
Python
gpl-3.0
919
0.005441
import numpy import matplotlib.pyplot import matplotlib.animation HEIGHT = 500 WIDTH
= 1024 fig = matplotlib.pyplot.figure() im_data = numpy.zeros((HEIGHT, WIDTH), dtype=numpy.float32) im = matplotlib.pyplot.imshow(im_data, cmap=matplotlib.pyplot.get_cmap('gray')) im.set_clim(0.0, 1.0) data = numpy.zeros(FFTPOINTS, dtype=numpy.float32) def init_image(): im.set_array(numpy.zeros((HEIGHT, WIDTH),...
a[:] = numpy.fromstring( sys.stdin.read(8192), dtype=numpy.complex64, ) fft = numpy.fft.rfft(data) line = numpy.sqrt(numpy.real(fft)**2+numpy.imag(fft)**2) im_data[:,:WIDTH-1] = im_data[:,1:] im_data[:,WIDTH-1] = line im.set_array(im_data) return (im,) ani = matplotlib...
agx/libvirt-sandbox-debian
libvirt-sandbox/image/template.py
Python
lgpl-2.1
4,199
0.001191
# # -*- coding: utf-8 -*- # Authors: Daniel P. Berrange <berrange@redhat.com> # # Copyright (C) 2015 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 Licen...
rlparse(uri) idx = o.scheme.find("+") if idx == -1: source = o.scheme protocol = None else: source = o.scheme[0:idx] protocol = o.scheme[idx + 1:] query = {} if o.query is not None and o.query != "": for param in o.que...
split("&"): (key, val) = param.split("=") query[key] = val return klass(source, protocol, o.hostname, o.port, o.username, o.password, o.path, query) @classmethod def get_all(klass, source, templatedir): ...
nburn42/tensorflow
tensorflow/python/keras/utils/generic_utils_test.py
Python
apache-2.0
2,330
0.006438
# Copyright 2016 The Ten
sorFlow Authors. 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.0 # # Unless required by applicable law or agreed to in ...
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for Keras generic Python utils.""" from __future__ i...
PrairieLearn/PrairieLearn
testCourse/questions/brokenGrading/server.py
Python
agpl-3.0
156
0.019231
import random, copy def generate(data): data['correct_answ
ers']['x'] = 3 def grade(data): raise Exception('d
eliberately broken grading function')
miminus/youtube-dl
youtube_dl/extractor/videomega.py
Python
unlicense
1,920
0.002083
# coding: utf-8 from __future__ import unicode_literals import re from .common import InfoExtractor from ..compat import compat_urllib_request class VideoMegaIE(InfoExtractor): _VALID_URL = r'(?:videomega:|https?://(?:www\.)?videomega\.tv/(?:(?:view|iframe|cdn)\.php)?\?ref=)(?P<id>[A-Za-z0-9]+)' _TESTS = [{...
ct(self, url): video_id = self._match_id(url) iframe_url = 'http://videomega.tv/cdn.php?ref=%s' % video_id req = compat_urllib_request.Request(iframe_url) req.add_header('Referer', url) req.add_heade
r('Cookie', 'noadvtday=0') webpage = self._download_webpage(req, video_id) title = self._html_search_regex( r'<title>(.+?)</title>', webpage, 'title') title = re.sub( r'(?:^[Vv]ideo[Mm]ega\.tv\s-\s*|\s*-\svideomega\.tv$)', '', title) thumbnail = self._search_rege...
sergiopasra/megaradrp
megaradrp/processing/sky.py
Python
gpl-3.0
2,585
0.002321
# # Copyright 2019-2020 Universidad Complutense de Madrid # # This file is part of Megara DRP # # SPDX-License-Identifier: GPL-3.0+ # License-Filename: LICENSE.txt # import logging import numpy import megaradrp.instrument.focalplane as fp from numina.frame.utils import copy_img def subtract_sky(img, ignored_sky_bu...
sky_img def subtract_sky_rss(img, sky_img, ignored_sky_bundles=None, logger=None): """Subtract a sky image from an image"""
# Sky subtraction if logger is None: logger = logging.getLogger(__name__) #logger.info('obtain fiber information') final_img = copy_img(img) # fiberconf_sky = dm.get_fiberconf(sky_img) # fiberconf_target = dm.get_fiberconf(img) logger.debug('using WLMAP extension to compute valid...
texastribune/txlege84
txlege84/bills/views.py
Python
mit
1,812
0
from django.http import JsonResponse from django.views.generic import DetailView, ListView, TemplateView from bills.mixins import AllSubjectsMixin from core.mixins import ConveneTimeMixin from committees.mixins import AllCommitteesMixin from legislators.mixins import AllLegislatorsMixin, ChambersMixin from bills.model...
oed__isnull=False) template_name = 'pages/vetoed-bills.html' class SubjectDetail(AllSubjectsMixin, AllLegislatorsMixin, ConveneTimeMixin, DetailView): model = Subject template_name = 'pages/subject.html' class SubjectListDetail(ConveneTimeMixin, ListView): model = Subject tem...
atorsMixin, AllSubjectsMixin, AllCommitteesMixin, ConveneTimeMixin, TemplateView): template_name = 'pages/find-bills.html' class BillSearchJson(ListView): queryset = Bill.objects.all().values('name', 'slug') def render_to_response(self, context, **kwargs): return JsonResponse...
bradhowes/pyslimp3
server/ClientPersistence.py
Python
gpl-3.0
3,504
0.015126
# # Copyright (C) 2009 Brad Howes. # # This file is part of Pyslimp3. # # Pyslimp3 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 version. # # Pyslimp3 is distr...
# If any Client settings have changed, write the entire collection to disk. # Also, detect any Client objects that have not received any heartbeats # since some amount of time and cull them. # def save( self ):
now = datetime.now() changed = False stale = [] # # Visit all of the clients looking for changed state or staleness # for key, client in self.clients.items(): if client.settingsAreDirty(): changed = True elif client.isStale( now...
openwns/wrowser
openwns/wrowser/probeselector/DirectoryReaders.py
Python
gpl-2.0
2,528
0.001978
############################################################################### # This file is part of openWNS (open Wireless Network Simulator) # _____________________________________________________________________________ # # Copyright (C) 2004-2007 # Chair of Communication Networks (ComNets) # Kopernikusstr. 16, D-...
esentations import os class CampaignReader: def __init__(self, directory, progressNotify = None): self.path
= os.path.abspath(directory) self.progressNotify = progressNotify self.stopped = False def stop(self): self.stopped = True def read(self): directories = [self.path] for base, subDirs, files in os.walk(self.path): if callable(self.progressNotify): ...
LodewijkSikkel/paparazzi
sw/tools/parrot/parrot_utils.py
Python
gpl-2.0
2,820
0.00461
# # Copyright (C) 2012-2014 T
he Paparazzi Team # # This file is part of Paparazzi. # # Paparazzi 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, or (at your option) # any later version. # # Paparazzi is distributed in th...
Y 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 paparazzi; see the file COPYING. If not, see # <http://www.gnu.org/licenses/>. # from __future__ import print_function import socket import ...
AtsushiSakai/PyAdvancedControl
inverted_pendulum_mpc_control/inverted_pendulum_mpc_control.py
Python
mit
4,100
0
""" Inverted Pendulum MPC control author: Atsushi Sakai """ import matplotlib.pyplot as plt i
mport numpy as np import math import time import cvxpy print("cvxpy version:", cvxpy.__version__) l_bar = 2.0 # length of bar M = 1.0 # [kg] m = 0.3 # [kg] g = 9.8 # [m/s^2] Q = np.diag([0.0, 1.0, 1.0, 0.0]) R = np.diag([0.01]) nx = 4 # number of state nu = 1
# number of input T = 30 # Horizon length delta_t = 0.1 # time tick animation = True def main(): x0 = np.array([ [0.0], [0.0], [0.3], [0.0] ]) x = np.copy(x0) for i in range(50): ox, dx, otheta, dtheta, ou = mpc_control(x) u = ou[0] x = sim...
GirlsCodePy/girlscode-coursebuilder
modules/assessment_tags/questions.py
Python
gpl-3.0
14,631
0.000478
# Copyright 2013 Google Inc. 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.0 # # Unless required by applicable law or ...
if not question_dto: return '[Question deleted]' if weight is Non
e: weight = 1.0 else: try: weight = float(weight) except ValueError: weight = 1.0 template_values = question_dto.dict template_values['embedded'] = embedded template_values['instanceid'] = instanceid template_values['resources_path'] = RESOURCES_PATH ...
sbarbett/ssp-sdk-python
src/blacklists.py
Python
apache-2.0
1,822
0.017014
# Copyright 2017 NeuStar, Inc.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.0 # # Unless required by applicable law or a...
n from .blacklist_id import BlacklistId from .sponsor import Sponsor from .account import Account class Blacklists: def __init__(self, connection, base_uri): self.connection = connection self.base_uri = base_uri+"/blacklists" def get(self): """Get a list of blacklists.""" return self.connection.get(self.bas...
e name of the blacklist. Keyword Arguments: sponsorId -- The sponsor ID associated with the blacklist (only required for NeustarAdmins) description -- A description of the blacklist. """ properties = {"accountId": account_id, "name": name} if kwargs is not None: properties.update(kwargs) return self....
TieWei/openstack-kit
openstackkit/ping_working_public.py
Python
mit
5,255
0.000761
#! /usr/bin/python # @author: wtie import subprocess import sys import time import argparse DIFF = False FIRST = [] def get_floating_ips(): sql = """SELECT fip.floating_ip_address FROM neutron.floatingips
AS fip JOIN neutron.ports AS p JOIN neutron.securitygroupportbindings AS sgb JOIN neutron.securitygrouprules AS sgr JOIN ( SELECT ins.uuid , Count(p.id) AS count FROM nova.instances AS ins ...
ins.task_state IS NULL GROUP BY ins.uuid ) AS i WHERE fip.fixed_port_id=p.id AND p.admin_state_up=1 AND sgb.port_id=p.id AND sgb.security_group_id=sgr.security_group_id AND sgr.direction='ingress' AND sgr.protocol='icmp' AND sgr.remote_ip_prefix='0.0.0.0/0' AND p.device_id=i.uui...
MakerLabPC/makerlinks
makerlinks.py
Python
gpl-3.0
1,532
0.035901
import os import sqlite3 from flask import Flask, request, session, g, redirect, url_for, abort, \ render_template, flash # create makerlinks application app = Flask(__name__) app.config.from_object(__name__) app.config.update(dict( DATABASE = os.path.join(app.root_path, 'makerlinks-dev.db'), DEBUG = True, APP_NA...
USERNAME = 'admin', PASSWORD = 'default' )) app.config.from_envvar('MAKERLINKS_SETTINGS', silent = True) def connect_db(): rv = sqlite3.connect(app.config['DATABASE']) rv.row_factory = sqlite3.Row return rv def get_db(): if not hasattr(g, 'sqlite_db'): g.sqlite_db = connect_db() return g.sqlite_db def init...
() with app.open_resource('schema.sql', mode='r') as f: db.cursor().executescript(f.read()) db.commit() @app.teardown_appcontext def close_db(error): if hasattr(g, 'sqlite_db'): g.sqlite_db.close() @app.route('/') def show_links(): db = get_db() cur = db.execute('select link, submitter from links order by...
GHubgenius/Beebeeto-framework
demo/baseframe.py
Python
gpl-2.0
4,824
0.002695
#!/usr/bin/env python # coding=utf-8 # Create: 2014-07-15 # Author: www.beebeeto.com # Team: n0tr00t security team import os import sys import json import traceback from pprint import pprint from optparse import OptionParser, OptionGroup from utils import http BEEBEETO_STATEMENT = \ "This POC is created for s...
if not self.options.target: print '\n[*] No target input!\n' self.base_parser.print_help() sys.exit() def __init_base_parser(self): self.base_parser.add_option('-t', '--target',
action='store', dest='target', default=None, help='the target to be checked by this poc.') self.base_parser.add_option('-v', '--verify', action='store_true', dest='verify', default=True, help='run poc in...
alanmcruickshank/superset-dev
superset/migrations/versions/ad82a75afd82_add_query_model.py
Python
apache-2.0
2,354
0.002974
"""Update models to support storing the queries. Revision ID: ad82a75afd82 Revises: f162a1dea4c4 Create Date: 2016-07-25 17:48:12.771103 """ # revision identifiers, used by Alembic. revision = 'ad82a75afd82' down_revision = 'f162a1dea4c4' from alembic import op import sqlalchemy as sa def upgrade(): op.create...
n('end_time', sa.Numeric(precision=20, scale=6), nullable=True), sa.ForeignKeyConstraint(['database_id'], [u'dbs.id'], ), sa.ForeignKeyConstraint(['user_id'], [u'ab_user.id'], ), sa.PrimaryKeyConstraint('id') ) op.add_column('dbs', sa.Column('select_as_create_table_as', sa.Boolean(), ...
op.create_index( op.f('ti_user_id_changed_on'), 'query', ['user_id', 'changed_on'], unique=False) def downgrade(): op.drop_table('query') op.drop_column('dbs', 'select_as_create_table_as')
jwparker1797/USAR_Add_In
Install/Data/GP_tools/HQIIS_report.py
Python
gpl-3.0
9,879
0.014576
############################################################## ##HQIIS Updater Version 2.0 ## ##*Changes for v2.0 ## -Upgraded tool to work with SDSFIE 3.1 Army Adaptation ## ##This script takes data from an HQIIS excel file and can run a report from a USAR SDSFIE 3.1 geodatabase. ## ##This script only works on GIS re...
dField_management(HQIIS_report, "GIS_QTY","FLOAT") arcpy.AddField_management(HQIIS_report, "GIS_UOM","TEXT") if siteuid != 0: site_uid_delim = arcpy.AddFieldDelimiters (HQIIS_report, "SITE_UID") arcpy.TableSelect_analysis(HQIIS_report,report_name + "_" + "site" + ".dbf", site_uid...
t = report_location + os.sep + report_name + "_" + "site" + ".dbf" arcpy.env.workspace = database arcpy.env.overwriteOutput = True ##Generate Report arcpy.AddMessage("Generating report...") datasetlist = arcpy.ListDatasets("*", "Feature") for dataset in datasetlist: ...
alcides/rdflib
test/test_sparql/test_not_equals.py
Python
bsd-3-clause
1,072
0.007463
from rdflib.term import URIRef, Literal from rdflib.namespace import Namespace, RDF, RDFS from rdflib import plugin from rdflib.parser import StringInputSource from rdflib.graph import Graph, ReadOnlyGraphAggregate, ConjunctiveGraph import sys from pprint import pprint def testSPARQLNotEquals(): NS = u"http://exa...
?node rdf:value ?val. FILTER (?val != 1) }""", initNs={'rdf': RDF.uri}, DEBUG=False) for row in rt: #item = row[0] item = row assert item == UR...
/bar"), "unexpected item of '%s'" % repr(item) if __name__ == '__main__': testSPARQLNotEquals()
east825/green-type
test/test_data/resolve/local/import_chain/main.py
Python
mit
64
0.015625
import sibling as alias
class MyClass(alias.A.Inner):
pass
rackerlabs/django-DefectDojo
dojo/tools/meterian/parser.py
Python
bsd-3-clause
5,223
0.001723
import json from datetime import datetime from dojo.models import Finding class MeterianParser(object): def get_scan_types(self): return ["Meterian Scan"] def get_label_for_scan_types(self, scan_type): return scan_type def get_description_for_scan_
types(self, scan_type): return "Meterian JSON report output file can be imported." def get_findings(self, report, test): findings = [] report_json = json.load(report) security_reports = self.get_security_reports(report_json) scan_date = str(datetime.fromisoformat(report_jso...
: findings += self.do_get_findings(single_security_report, scan_date, test) return findings def get_security_reports(self, report_json): if "reports" in report_json: if "security" in report_json["reports"]: if "reports" in report_json["reports"]["security"]:...
justinlulejian/fah-gae
lib/google/cloud/storage/__init__.py
Python
mit
1,604
0
# Copyright 2014 Google Inc. # # 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 agreed to in writing, ...
buted on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Shortcut methods for getting set up with Google Cloud S
torage. You'll typically use these to get started with the API: >>> from google.cloud import storage >>> client = storage.Client() >>> bucket = client.get_bucket('bucket-id-here') >>> # Then do other things... >>> blob = bucket.get_blob('/remote/path/to/file.txt') >>> print(blob.download_as_string()) >>> blob.upload_...
jseppi/load-cms-data
load_cms_data.py
Python
mit
7,893
0.003801
import sys, getopt import sqlite3 import csv import os from create_cms_db import create_cms_db #TODO: In blog, mention had to save this as CSV because only Excel provided region_crosswalk_file = 'data/ZipHsaHrr11.csv' inpatient_file = 'data/Medicare_Provider_Charge_Inpatient_DRG100_FY2011.csv' outpatient_file...
vider_street = row[3] provider_city = row[4] provider_state = row[5] provider_zip = str(row[6]).zfill(5) # unused: ref_regi
on_name = row[7] providers[provider_id] = { 'name': provider_name, 'street': provider_street, 'city': provider_city, 'state': provider_state, 'zip': provider_zip } num_discharged = int(row[8]) avg_charge = float(row...
openpolis/open_municipio
fabfile.sample/conf_production.py
Python
agpl-3.0
3,837
0.011989
import os # IP/domain name of the production server SERVER_MACHINE = 'www.openmunicipio.it' ## CHANGEME! # Python interpreter executable to use on virtualenv creation PYTHON_BIN = 'python' #pyhton 2.7 PYTHON_PREFIX = '' # e.g. ``/usr``, ``/usr/local``; leave empty for default. PYTHON_FULL_PATH = "%s/bin/%s" % (PYTHON_...
R_DOWNLOAD_LINK = 'http://apache.fastbull.org/lucene/solr/3.6.0/apache-solr-3.6.0.tgz' # where Solr configuration and data reside on the server machine SOLR_INSTALL_DIR = '/home/apache-solr-3.6.0' # where configuration/data files for Solr reside on the server machine SOLR_HOME = '/home/solr' ###------------------ Post...
service postgresql-8.4' # DB username DB_USER = OM_USER # name of the application DB DB_NAME = OM_USER
eLRuLL/scrapy
scrapy/core/downloader/handlers/s3.py
Python
bsd-3-clause
4,259
0.000704
from urllib.parse import unquote from scrapy.core.downloader.handlers.http import HTTPDownloadHandler from scrapy.exceptions import NotConfigured from scrapy.utils.boto import is_botocore from scrapy.utils.httpobj import urlparse_cached from scrapy.utils.misc import create_instance def _get_boto_connection(): fr...
lace(url=url,
headers=signed_headers) return self._download_http(request, spider)
AliZafar120/NetworkStimulatorSPl3
rapidnet/plot/merge_logs.py
Python
gpl-2.0
12,893
0.02831
#!/usr/bin/python import os, sys import math, gmpy if len (sys.argv) not in [2, 3, 4]: print 'Usage: merge_logs <logs_dir> [<route_quality(True/False)>] [<bandwidth_color(True/False)>]' sys.exit (0) dir = sys.argv[1] if len (sys.argv) >= 3: route_quality = sys.argv[2] else : route_quality = 'False' if len (...
'): ofile.write ('info graph linkevent Per-Second_Link_Events 0 %s 0 %d %d\n'%(duration, max_linkevent, 3)) ##### For Chord def parse_for_chord (time, line): MAX = (gmpy.mpz (1) << 160) - 1 RADIUS = gmpy.mpz (700) CX, CY = [gmpy.mpz (1000), gmpy.mpz (1000)] node_id = line.split(' ')[2] if ('
node_attr2' in line): id = gmpy.mpz (line.rpartition(':')[2], 16) angle = gmpy.mpf (math.pi) * id / MAX x, y = CX + RADIUS * math.cos (angle), CY + RADIUS * math.sin(angle) add_event (time, '%ldns position %s %f %f 0 0 0 0\n' % (time, node_id, x, y)) add_event (time, '%ldns state %s +chordRing\n' % ...
squadran2003/filtering-searching-mineral-catalogue
filtering-searching-mineral-catalogue/minerals/tests.py
Python
mit
3,110
0.052275
from django.test import TestCase from django.urls import reverse # Create your tests here. from .models import Mineral class MineralModelTests(TestCase): def test_new_mineral_created(self): mineral = Mineral.objects.create( name = "Abelsonite", image_filename = "240px-Abelsonite_-_Green_River_Formation%...
inerals_view(self): resp = self.client.get(reverse('minerals:mineral_list')) sel
f.assertEqual(resp.status_code,200) self.assertIn(self.mineral, resp.context['minerals']) self.assertTemplateUsed(resp, 'minerals/minerals.html') def test_minerals_detail_view(self): resp = self.client.get(reverse('minerals:mineral_detail', kwargs={'pk':self.mineral.id })) self.assertEqual(resp.sta...
stczhc/neupy
neupy/plots/error_plot.py
Python
mit
1,872
0
import numpy as np import matplotlib.pyplot as plt __all__ = ('error_plot',) def error_plot(network, logx=False, ax=None, show=True): """ Makes line plot that shows training progress. x-axis is an epoch number and y-axis is an error. Parameters ---------- logx : bool Parameter set up lo...
""" if ax is None: ax = plt.gca() if not network.errors: network.logs.warning("There is no data to plot") return ax train_errors = netw
ork.errors.normalized() validation_errors = network.validation_errors.normalized() if len(train_errors) != len(validation_errors): network.logs.warning("Number of train and validation errors are " "not the same. Ignored validation errors.") validation_errors = [] ...
alard/warctozip
hanzo/httptools/messaging.py
Python
mit
18,022
0.000555
"""A set of stream oriented parsers for http requests and responses, inline with the current draft recommendations from the http working group. http://tools.ietf.org/html/draft-ietf-httpbis-p1-messaging-17 Unlike other libraries, this is for clients, servers and proxies. Missing: comma parsing/header folding ""...
#TODO: No idea what this does, looks broken
self.header.write(buf) buf.extend('\r\n') self.write_body(buf) def write_decoded_message(self, buf): """Writes the parsed data to the buffer passed.""" self.header.write_decoded(buf) if self.header.has_body(): length = sum(l for o, l in self.body_chunks) ...
kushalbhola/MyStuff
Practice/PythonApplication/env/Lib/site-packages/pandas/core/arrays/__init__.py
Python
apache-2.0
581
0
from .array_ import array # noqa: F401 from .base import ( # noqa: F401 ExtensionArray, ExtensionOpsMixin, ExtensionScalarOpsMixin, ) from .categorical import Categorical # noqa: F401 from .datetimes import DatetimeArray # noqa: F401 from .integer import Inte
gerArray, integer_array # noqa: F401 from .interval import IntervalArray # noqa: F401 from .numpy_ import Pa
ndasArray, PandasDtype # noqa: F401 from .period import PeriodArray, period_array # noqa: F401 from .sparse import SparseArray # noqa: F401 from .timedeltas import TimedeltaArray # noqa: F401
waseem18/oh-mainline
mysite/base/disk_cache.py
Python
agpl-3.0
504
0
# Note: # This is a total hack to implement simple disk-based memoization, # with no expiration. import os PATH = '/tmp/django_cache_belonging_to_%s' % os.environ.get('USER', 'unknown') def set(key, value): if not os.path.isdir(PATH): os.mkdir(PATH) file_obj = file(os.path.join(PATH, key), 'w') f...
with open(os.path.join(PATH, key)) as f: return f.read() ex
cept IOError: return None
efiop/dvc
tests/unit/command/test_imp_url.py
Python
apache-2.0
3,589
0
import logging from dvc.cli import parse_args from dvc.command.imp_url import CmdImportUrl from dvc.exceptions import DvcException def test_import_url(mocker): cli_args = parse_args( [ "import-url", "src", "out", "--file", "file", "-...
cli_args) m = mocker.patch.object(cmd.repo, "imp_url", autospec=True) assert cmd.run() == 0 m.assert_called_once_with( "src", out="out", fname="file", no_exec=False, remote=None, to_remote=False, desc="description",
jobs=4, ) def test_failed_import_url(mocker, caplog): cli_args = parse_args(["import-url", "http://somesite.com/file_name"]) assert cli_args.func == CmdImportUrl cmd = cli_args.func(cli_args) mocker.patch.object(cmd.repo, "imp_url", side_effect=DvcException("error")) with caplog.at_l...
google-research/adamatch
semi_supervised_domain_adaptation/adamatch.py
Python
apache-2.0
10,175
0.003735
# Copyright 2019 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
yParallel(eval_op, static_argnums=(1,)) def main(argv): del argv print('JAX host: %d / %d' % (jax.host_id(), jax.host_count())) print('JAX devices:\n%s' % '\n'.join(str(d) for d in jax.devices()), flush=True) setup_tf() source = FSL_DATASETS()[f'{FLAGS.dataset}_{FLAGS.source}-0']() target_name...
aset}_{FLAGS.target}') target_labeled = SSL_DATASETS()[target_name](target_samples_per_class, target_seed) target_unlabeled = FSL_DATASETS()[f'{target_name}-0']() testsets = [target_unlabeled.test, source.test] # Ordered by domain (unlabeled always first) module = AdaMatch(source.nclass, network(FLAGS....
davidam/python-examples
basics/verpython.py
Python
gpl-3.0
1,075
0.000934
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (C) 2018 David Arroyo Menéndez # Author: David Arroyo Menéndez <davidam@gnu.org> # Maintainer: David Arroyo Menéndez <davidam@gnu.org> # This file is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as p...
h GNU Emacs; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA, # encoding: utf-8 ver = raw_input("¿Quieres ver mi python? (Si | No): ") if (ver == "Si"): print("Te quiero") elif (ver == "No"):
print("Eres una estrecha")
dalou/django-cargo
cargo/migrations/0008_auto_20151120_0906.py
Python
bsd-3-clause
486
0.002058
#
-*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cargo', '0007_auto_20151120_0720'), ] operations = [ migrations.AlterModelOptions( name='emailinguseractivationto...
vation"}, ), ]
davisd50/sparc.db
sparc/db/splunk/tests/test_kvstore.py
Python
mit
5,425
0.006452
import os import unittest import zope.testrunner from zope import component from sparc.testing.fixture import test_suite_mixin from sparc.testing.testlayer import SPARC_INTEGRATION_LAYER from sparc.db.splunk.testing import SPARC_DB_SPLUNK_INTEGRATION_LAYER from zope import schema from zope.interface import Interface c...
value_type=schema.Text(title=u"value")) ip = schema.DottedName(title=u"ip",min_dots=3,max_dots=3) ascii = schema.ASCII(title=u"ascii") class SparcCacheSplunkAreaTestCase(unittest.TestCase): layer = SPARC_INTEGRATION_LAYER sm = component.getSiteManager()
def test_ISplunkKVCollectionSchema_adapter_for_schemas(self): from sparc.db.splunk import ISplunkKVCollectionSchema schema = ISplunkKVCollectionSchema(ITestSchema) self.assertIn('field.date', schema) self.assertEquals(schema['field.date'], 'time') self.a...
seomoz/roger-mesos-tools
bin/roger.py
Python
apache-2.0
2,779
0.00072
#!/usr/bin/python from __future__ import print_function import os import
sys import subprocess i
mport re import importlib from cli.utils import Utils def print_help_opt(opt, desc): print(" {} {}".format(opt.ljust(13), desc)) def roger_help(root, commands): print("usage: roger [-h] [-v] command [arg...]\n") print("a command line interface to work with roger mesos.") print("\npositional argumen...
MERegistro/meregistro
meregistro/apps/titulos/models/EstadoTituloNacional.py
Python
bsd-3-clause
471
0.002128
# -*- coding: utf-8 -*- from django.db import models """ Representa las opciones de estados que
tiene cada título nacional """ class EstadoTituloNacional(models.Model): NO_VIGENTE = u'No vigente' VIGENTE = u'Vigente' nombre = models.CharField(max_length=50, unique=True) class Meta: app_label = 'titulos' ordering = ['nombre'] db_table = 'titulos_estado_titulo_nacional' ...
unicode__(self): return self.nombre
dhalleine/tensorflow
tensorflow/python/ops/nn.py
Python
apache-2.0
50,569
0.002472
# Copyright 2015 The TensorFlow Authors. 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.0 # # Unless required by applica...
the specific l
anguage governing permissions and # limitations under the License. # ============================================================================== # pylint: disable=unused-import,g-bad-import-order """## Activation Functions The activation ops provide different types of nonlinearities for use in neural networks. Th...
rjusher/djsqla-query-operations
djsqla_query_operations/compat.py
Python
mit
590
0
# -*- coding: utf-8 -*- from sys i
mport version_info import copy import types try: from collections import OrderedDict except ImportError: # pragma: nocover # Django < 1.5 fallback from django.utils.datastructures import SortedDict as OrderedDict # noqa # There is a bug with deepcopy in 2.6, patch if we are running python < 2.7 # http:...
x.im_class) copy._deepcopy_dispatch[types.MethodType] = _deepcopy_method
jrichte43/hangman
hangman/models/role.py
Python
gpl-2.0
278
0
from flask_security.core import RoleMixin from hangman.models import db class Role(db.Model, RoleMixin): __tablename__ = 'roles' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80), unique=True) description = db.Co
lumn(db.String(255))
fracpete/python-weka-wrapper3
python/weka/flow/container.py
Python
gpl-3.0
7,930
0.001009
# 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 your option) any later version. # # This program is distributed in the hope that it will be useful, # bu...
SelectionContainer(Container): """ Container for models. """ def __init__(self, original=None, reduced=None, num_atts=None, selected=None, results=None): """ Initializes the container. :param original: the original dataset :type original: Instances
:param reduced: the reduced dataset :type reduced: Instances :param num_atts: the number of attributes :type num_atts: int :param selected: the list of selected attribute indices (0-based) :type selected: list :param results: the generated results string :type...
yzl0083/orange
Orange/OrangeWidgets/plot/owplot.py
Python
gpl-3.0
71,969
0.011394
''' ################# Plot (``owplot``) ################# .. autoclass:: OrangeWidgets.plot.OWPlot ''' LeftLegend = 0 RightLegend = 1 BottomLegend = 2 TopLegend = 3 ExternalLegend = 4 UNUSED_ATTRIBUTES_STR = 'unused attributes' from owaxis import * from owcurve import * from owlegend import * from owpalette i...
tion in data coordinates :type pos: tuple of float float :rtype: :obj:`.OWPoint` **Data curves** The preferred method for showing a series of data points is :meth:`set_main_curve_data`. It allows you to specify po
int positions, colors, labels, sizes and shapes. .. automethod:: set_main_curve_data .. automethod:: add_curve .. automethod:: add_custom_curve .. automethod:: add_marker .. method:: add_item(item) Adds any PlotIt...
exowanderer/SpitzerDeepLearningNetwork
Python Scripts/spitzer_cal_NALU_train.py
Python
mit
15,910
0.009742
from multiprocessing import set_start_method, cpu_count #set_start_method('forkserver') import os os.environ["OMP_NUM_THREADS"] = str(cpu_count()) # or to whatever you want from argparse import ArgumentParser from datetime import datetime from sklearn.model_selection import train_test_split from sklearn.metrics impo...
--pre_process', type=str2bool, nargs='?', required=False, default=True, help='Toggle whether to MinMax-preprocess the features.') ap.add_argument('-pca', '--pca_transform', type=str2bool, nargs='?', required=Fals
e, default=True, help='Toggle whether to PCA-pretransform the features.') ap.add_argument('-v', '--verbose', type=str2bool, nargs='?', required=False, default=False, help='Whether to set verbosity = True or False (default).') ap.add_argument('-ds', '--data_set', type=str, required=False, default='', help='The csv file ...
shackra/thomas-aquinas
tests/customstuff.py
Python
bsd-3-clause
1,159
0.000863
# coding: utf-8 from summa.director import director from summa.scene import Scene import pyglet class TimedScene(Scene): def __init__(self, *children): super(TimedScene, self).__init__(*children) self._dt = 0
self._maxtime = 20 self._next_scene = None self._changetype = 0 self.schedule(self.timeit) def changescene(self): if self._next_scene is None: pyglet.app.exit() if self._changetype == 0: director.push(self._next_scene) elif self._changety
pe == 1: self._next_scene = None director.pop() elif self._changetype == 2: director.replace(self._next_scene) elif self._changetype == 3: self._next_scene = None director.scene.end(True) def timeit(self, dt): if self._dt >= self._...
andyrenpanlong/Taptap
tabUnique.py
Python
mit
987
0.003995
#coding=utf-8 import pymongo def delete_repeat_data(): client = pymongo.MongoClient('localhost', 27017) db = client.admin collection = db.taplist for
url in collection.distinct('game_id'): # 使用distinct方法,获取每一个独特的元素列表 num = collection.count({"game_id": url}) # 统计每一个元素的数量 print num, "===== aawa =====", url # for i in range(1, num): # 根据每一个元素的数量进行删除操作,当前元素只有一个就不再删除 #
print 'delete %s %d times ' % (url, i) # # 注意后面的参数, 很奇怪,在mongo命令行下,它为1时,是删除一个元素,这里却是为0时删除一个 # collection.remove({"game_id": url}, 0) # for i in collection.find({"game_id": url}): # 打印当前所有元素 # print i # print collection.distinct('game_id') # 再次打印一遍所要去重的元素 delete...
EIREXE/SpaceDock
SpaceDock/blueprints/admin.py
Python
mit
3,466
0.004328
from flask import Blueprint, render_template, abort, redirect from flask.ext.login import current_user from sqlalchemy import desc from SpaceDock.objects import User, Mod, GameVersion, Game, Publisher from SpaceDock.database import db from SpaceDock.common import * from SpaceDock.config import _cfg from SpaceDoc...
def create_game(): name = request.form.get("gname") sname = request.form.get("sname") pid = request.form.get("p
name") if not name or not pid or not sname: return redirect("/asdf") if any(Game.query.filter(Game.name == name)): return redirect("/fsda") go = Game(name,pid,sname) db.add(go) db.commit() return redirect("/admin") @admin.route("/publishers/create", methods=['POST'])...
ric2b/Vivaldi-browser
chromium/chrome/installer/mac/signing/signing_test.py
Python
bsd-3-clause
9,294
0.000861
# Copyright 2019 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import unittest from . import model, signing, test_common, test_config mock = test_common.import_mock() # python2 support. try: FileNotFoundError exce...
se) signing.sign_part(self.paths, self.config, part) run_command.assert_called_once_with([ 'codesign', '--sign', '[IDENTITY]', '--timestamp', '--identifie
r', 'test.signing.app', '/$W/Test.app' ]) def test_sign_part_with_options(self, run_command, linker_signed_arm64_needs_force): part = model.CodeSignedProduct( 'Test.app', 'test.signing.app', options=model.CodeSignOp...
cts-admin/cts
cts/fundraising/migrations/0003_auto_20170824_0419.py
Python
gpl-3.0
546
0.001832
# -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2017-08-24 04:19 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('fundraising', '0002_ctsdonor_profile'), ] operatio...
s.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='accounts.Profi
le'), ), ]
pdp10/sbpipe
sbpipe/pl/ps2/parscan2.py
Python
mit
13,510
0.002073
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2018 Piero Dalle Pezze # # 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 ...
IABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # for computing the pipeline elapsed time import datetime import glob import logging import
os import os.path import yaml import traceback from ..pipeline import Pipeline from sbpipe.utils.dependencies import is_r_package_installed from sbpipe.utils.io import refresh from sbpipe.utils.parcomp import parcomp from sbpipe.utils.rand import get_rand_alphanum_str from sbpipe.report.latex_reports import latex_repor...
boxu0001/practice
py3/S163_L641_MissingRange.py
Python
gpl-3.0
1,104
0.005435
''' Given a sorted integer array where the range of elements are in the inclusive r
ange [lower, upper], return its missing ranges. Have you met this question in a real interview? Example Example 1 Input: nu
ms = [0, 1, 3, 50, 75], lower = 0 and upper = 99 Output: ["2", "4->49", "51->74", "76->99"] Explanation: in range[0,99],the missing range includes:range[2,2],range[4,49],range[51,74] and range[76,99] Example 2 Input: nums = [0, 1, 2, 3, 7], lower = 0 and upper = 7 Output: ["4->6"] Explanation: in range[0,7],the missi...
Ibcrootbeer/PyScripts
Install/RemoveAll.py
Python
mit
432
0.002315
#!/usr/bin/env python import os os.system("sudo apt-get -y purg
e apache2") os.system("sudo apt-get -y purge openssh-server") os.system("sudo rm /etc/motd") os.system("sudo rm ~/.ssh/known_hosts") os.system("sudo apt-get -y purge vsftpd") os.system("sudo apt-get -y purge mysql*") os.system("sudo rm /usr/bin/mysql -R") os.system("sudo rm /var/lib/mysql -R") os.system("sudo rm /etc/m...
)
dNG-git/pas_tasks
src/pas_tasks/abstract_persistent.py
Python
gpl-2.0
2,708
0.000739
# -*- coding: utf-8 -*- """ direct PAS Python Application Services ---------------------------------------------------------------------------- (C) direct Netware Group - All rights reserved https://www.direct-netware.de/redirect?pas;tasks The following license agreement remains valid unless any additions or changes ...
slots__ = TimedTasksMixin._mixin_slots_ """ python.org: __slots__ reserves space for the declared variables and prevents the automatic creation of __dict__ and __weakref__ for each instance. """ def __init__(self): """ Constructor __init__(AbstractPersistent) :since: v1.0.0 """ Ab...
medTasksMixin.__init__(self) # @classmethod def is_executing_daemon(cls): """ True if the instance is executing scheduled tasks. :return: (bool) True if executing scheduled tasks :since: v1.0.0 """ _return = False try: persistent_tasks = cls.get_instance() ...
pimier15/PyGUI
Kivy/Kivy/Bk_Interractive/My/C1/Proj_ComicBook/comiccreator.py
Python
mit
434
0.013825
from kivy.app import App from kivy.lang
import Builder from kivy.uix.anchorlayout import AnchorLayout Builder.load_file('toolbox.kv') Builder.load_file('generaloptions.kv') Builder.load_file('statusbar.kv') Builder.load_file('drawingspace.kv') class ComicCreator(AnchorLayout): pass class ComicCreatorApp(App): def build(self)
: return ComicCreator() if __name__=='__main__': ComicCreatorApp().run()
mkieszek/odoo
addons/purchase/res_config.py
Python
agpl-3.0
4,217
0.005454
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from openerp.osv import fields, osv from openerp.tools.translate import _ class purchase_config_settings(osv.osv_memory): _name = 'purchase.config.settings' _inherit = 'res.config.settings' _columns = { ...
se_double_validation.'), 'module_purchase_requisition': fields.selection([ (0, 'Purchase propositions trigger draft purchase orders to a single supplier'), (1, 'Allow using call for tenders to get quotes from multiple suppliers (advanced)') ], "Calls for Tenders", ...
hen you want to generate requests for quotations to several vendors for a given set of products. You can configure per product if you directly do a Request for Quotation to one vendor or if you want a Call for Tenders to compare offers from several vendors."""), 'module_s...
sorgerlab/indra
indra/sources/medscan/fix_csxml_character_encoding.py
Python
bsd-2-clause
1,680
0.00119
import sys import logging codec_options = ['utf-8', 'latin_1'] logger = logging.getLogger(__name__) def try_decode(byte_string, codec): try: s = byte_string.decode(codec) return s except: return None def shortest_string(strings): best_string = None best_length = None ...
len(s) return best_string def fix_character_encoding(input_file, output_file): with open(input_file, 'rb') as f_in: with open(output_file, 'wb') as f_out: for line in f_in: # Try to decode with both latin_1 and utf-8 decoded = [try_decode(line, c) for c in c...
None] if len(decoded) == 0: # Hopefully at least one codec worked logger.info('Could not decode: %s' % line) sys.exit(1) else: # If more than one, choose the codec that gives the best # l...
npcasler/phenomics
HTPGeoprocessor.py
Python
apache-2.0
4,471
0.006039
""" /*************************************************************************** Name : HTP Geoprocessor Description : Tools for processing HTP geospatial data Date : 29/Mar/12 copyright : (C) 2012 by Dr. Kelly Thorp, USDA-ARS email : kelly.thorp@...
action that will start plugin configuration icon = QIcon(":/plugins/htpgeoprocessor/icon.png") self.createmap = QAction(icon,u"Map Creator", self.iface.mainWindow()) self.preprocess = QAction(icon,u"Preprocessor", self.iface.mainWindow()) self.geoprocess = QAction(icon,u"
Geoprocessor", self.iface.mainWindow()) self.helpme = QAction(icon, u"Help", self.iface.mainWindow()) # connect the action to a method self.createmap.triggered.connect(self.CreateMap) self.preprocess.triggered.connect(self.Preprocess) self.geoprocess.triggered.conn...
jimengliu/cattle
tests/integration/cattletest/core/test_link.py
Python
apache-2.0
7,262
0
from common_fixtures import * # NOQA def test_link_instance_stop_start(super_client, client, context): target1 = context.create_container(ports=['180', '122/udp']) target2 = context.create_container(ports=['280', '222/udp']) c = context.create_container(instanceLinks={ 'target1_link': target1.id...
== 1 link = links[0] assert link.state == 'inactive' c = client.wait_success(c.start()) link = client.reload(link) assert c.state == 'running'
assert link.state == 'active' c = client.wait_success(c.stop()) assert c.state == 'stopped' link = client.reload(link) link = super_client.wait_success(link.remove()) assert link.state == 'removed' c = client.wait_success(c.start()) assert c.state == 'running'
bsc-dd/hecuba
hecuba_py/tests/withcassandra_twins/storagenumpy_twins_tests.py
Python
apache-2.0
6,773
0.00502
import gc import unittest from hecuba import config, StorageNumpy import uuid import numpy as np from storage.api import getByID class StorageNumpyTwinsTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.old = config.execution_name config.execution_name = "StorageNumpyTest".lower(...
s = StorageNumpy(n, 'persistent') self.assertTrue(s._twin_id is not None) self.assertEqual(s._twin_name, self.ksp+'_arrow.persistent_arrow') self.assertTrue(np.array_equal(s._twin_ref, n.T)) self.assertEqual(s._twin_ref._name, self.ksp+'_arrow.persistent_arrow') self.assertEqu...
ssertEqual(n.T.shape, s._twin_ref.shape) self.assertEqual(s._build_args.twin_id, s._twin_id) #stored data in cassandra res = config.session.execute( "SELECT twin_id FROM hecuba.istorage WHERE storage_id = %s", [s.storage_id] ) self.assertEqual(res....
h4ck3rm1k3/orca-sonar
test/keystrokes/gtk-demo/role_dialog.py
Python
lgpl-2.1
1,507
0.002654
#!/usr/bin/python """Test of dialog presentation.""" from macaroon.playback import * import utils sequence = MacroSequence() sequence.append(KeyComboAction("<Control>f")) sequence.append(TypeAction("Expander")) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("Return")) sequence.append(...
ck on the triangle for details.'", "SPEECH OUTPUT: 'Details toggle button collapsed'"])) sequence.append(KeyComboAction("Tab")) sequence.append(KeyComboAction("Tab")) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("KP_Enter")) sequence.append(utils.AssertPresentationAction( "Dia...
ls collapsed toggle but', cursor=1", "SPEECH OUTPUT: 'Details'", "SPEECH OUTPUT: 'toggle button collapsed'"])) sequence.append(KeyComboAction("<Alt>F4")) sequence.append(utils.AssertionSummaryAction()) sequence.start()
project-callisto/callisto-core
callisto_core/wizard_builder/forms.py
Python
agpl-3.0
1,434
0.000697
fro
m django import forms from django.contrib.auth import get_user_model from . import widgets User = get_user_model() class PageForm(forms.Form): @classmethod def setup(cls, page, data): cls.base_fields = { question.field_id: question.make_field() for question in page.mock_questions ...
self.page = page self.full_clean() return self @property def sections(self): from .models import Page return dict(Page.SECTION_CHOICES) @property def serialized(self): return [question.serialized for question in self.page.mock_questions] def _clean_fields...
k11a/snmpconverter
configinit.py
Python
gpl-3.0
24,267
0.015366
# Copyright 2017 www.msv.space # # This file is part of SNMPTableMixer. # # SNMPTableMixer 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 versi...
щественной лицензии GNU. # # Вы должны были получить копию Стандартной общественной лицензии GNU # вместе с этой программой. Если это не так, см. # <http://www.gnu.org/licenses/>. import sqlite3 def normalization(data=''): if '=' in data: pos = data.find('=') data = data[:pos].rstrip() + '=' + da...
swith('#'): data = '' if ' #' in data: data = data[:data.find(' #')] + '\n' data = data.rstrip() + '\n' return data def calc_pos_param(data): return len(data) - len(data.lstrip()) def check_param_value(param_value, checker_value): result_ok = False errdesc = '' if checker...
natetrue/ReplicatorG
skein_engines/skeinforge-0006/skeinforge_tools/export_plugins/binary_16_byte.py
Python
gpl-2.0
10,998
0.037189
""" Binary 16 byte is an export plugin to convert gcode into 16 byte binary segments. An export plugin is a script in the export_plugins folder which has the functions getOuput, isArchivable and writeOutput. It is meant to be run from the export tool. To ensure that the plugin works on platforms which do not handle ...
0 floatValue = ( float( lineFromCharacter ) + offset ) / stepLength return int( round( floatValue ) ) def getIntegerFlagFromCharacterSplitLine( character, splitLine ): "Get the integer flag after the first occurence of the character in the split line." lineFromCharacter = getStri
ngFromCharacterSplitLine( character, splitLine ) if lineFromCharacter == None: return 0 return 1 def getOutput( gcodeText, binary16BytePreferences = None ): """Get the exported version of a gcode file. This function, isArchivable and writeOutput are the only necessary functions in a skeinforge export plugin. If...
masaori335/hyper
hyper/http20/connection.py
Python
mit
27,500
0.000255
# -*- coding: utf-8 -*- """ hyper/http20/connection ~~~~~~~~~~~~~~~~~~~~~~~ Objects that build hyper's connection-level HTTP/2 abstraction. """ from ..tls import wrap_socket, H2_NPN_PROTOCOLS, H2C_PROTOCOL from ..common.exceptions import ConnectionResetError from ..common.bufsocket import BufferedSocket from ..common....
# also save the most recent one for easy access without having to walk # the dictionary. self.streams = {}
self.recent_stream = None self.next_stream_id = 1 # Header encoding/decoding is at the connection scope, so we embed a # header encoder and a decoder. These get passed to child stream # objects. self.encoder = Encoder() self.decoder = Decoder() # Values f...
ThreatConnect-Inc/tcex
tests/api/tc/v2/threat_intelligence/test_intrusion_set_interface.py
Python
apache-2.0
2,914
0
"""Test the TcEx Threat Intel Module.""" # standard library import os from .ti_helpers import TestThreatIntelligence, TIHelper class TestIntrustionSetGroups(TestThreatIntelligence): """Test TcEx Instrusion Set Groups.""" group_type = 'Intrusion Set' owner = os.getenv('TC_OWNER') ti = None ti_hel...
.""" super().group_get_filter() def tests_ti_intrusion_set_get_includes(self, request): """Test group get with includes.""" super().group_get_includes(request) def tests_ti_intrusion_set_get_attribute(self, request): """Test group get attribute.""" super().group_get_att...
_label(self): """Test group get label.""" super().group_get_label() def tests_ti_intrusion_set_get_tag(self, request): """Test group get tag.""" super().group_get_tag(request) def tests_ti_intrusion_set_update(self, request): """Test updating group metadata.""" ...
weso/CWR-WebClient
cwr_webclient/report/cwr.py
Python
mit
2,566
0
# -*- encoding: utf-8 -*- import StringIO import xlsxwriter """ Web app module. """ __author__ = 'Bernardo Martínez Garrido' __license__ = 'MIT' __status__ = 'Development' def generate_cwr_report_excel(cwr): output = StringIO.StringIO() workbook = xlsxwriter.Workbook(output, {'in_memory': True}) _gen...
t.write(row, col + 1, header.creation_date_time) row += 1 results_sheet.write(row, col, 'Transmission Date', bold) results_sheet.write(row, col + 1, header.transmission_date) row += 1 row += 1 results_sheet.write(row, col, 'EDI Standard', bold) results_sheet.write(row, col + 1, header.ed...
ite(row, col + 1, header.character_set) row += 1 row += 1 results_sheet.write(row, col, 'Counts', bold) row += 1 results_sheet.write(row, col, 'Groups', bold) results_sheet.write(row, col + 1, trailer.group_count) row += 1 results_sheet.write(row, col, 'Transactions', bold) res...
rootcanal/whereikeepinfo
whereikeepinfo/forms.py
Python
gpl-2.0
2,003
0.003495
import formencode import os class FileValidator(formencode.FancyValidator): __unpackargs__ = ('upload_field', 'max_upload_size') def _to_python(self, field_storage, state): if field_storage is None: return field_storage fileobj = field_storage.file fileobj.seek(0, os.SEEK_...
oad_size): raise formencode.Invalid( _('File too big'), field_storage, state, error_dict={self.upload_field:
formencode.Invalid(_('File too big'), field_storage, state)}) fileobj.seek(0) return dict(filename=field_storage.filename, file=fileobj, size=size) class RegistrationSchema(formencode.Schema): allow_extra_fields = True username = formencode.validators.PlainText(not_empty=Tru...
krishauser/Klampt
Python/python2_version/klampt/vis/glcommon.py
Python
bsd-3-clause
15,541
0.014156
"""Defines GLWidgetPlugin, GLMultiViewportProgram, and CachedGLObject, which are used by the core visualization module. They may be useful for writing your own GLPluginInterface classes, too. """ from glinterface import GLPluginInterface from glprogram import GLProgram,GLPluginProgram import math from OpenGL.GL impo...
): self.refresh() return True return False def motionfunc(self,x,y,dx,dy): if self.klamptwidgetdragging: self.klamptwidgetmaster.drag(dx,-dy,self.viewport()) self.widgetchangefunc("mousedrag") if self.klamptwidgetmaster.wantsRedraw(): ...
master.hover(x,self.view.h-y,self.viewport()) if self.klamptwidgetmaster.wantsRedraw(): self.widgethoverfunc() self.refresh() return False def idlefunc(self): self.klamptwidgetmaster.idle() return True class GLMultiViewportProgram(GLProgram): ...
practice-vishnoi/dev-spark-1
examples/src/main/python/ml/simple_text_classification_pipeline.py
Python
apache-2.0
2,809
0.001068
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
beled. Document = Row("id", "text") test = sc.parallelize([(4, "spark i j k"), (5, "l m n"), (6, "spark hadoop spark"), (7, "apac
he hadoop")]) \ .map(lambda x: Document(*x)).toDF() # Make predictions on test documents and print columns of interest. prediction = model.transform(test) selected = prediction.select("id", "text", "prediction") for row in selected.collect(): print(row) sc.stop()
gustavomazevedo/tbackup-server
server/tests.py
Python
mit
8,897
0.015398
from django.utils import timezone from django.conf import settings from django.test import TestCase from django.core.files import File from django.contrib.auth.models import User, AnonymousUser from rest_framework.test import APITestCase from rest_framework import status import os import shutil import subprocess imp...
: if os.path.isfile(file_path) and 'reactive_course source code_reactive-week1.zip' not in file_path: print 'remove file %s' % file_path os.remove(file_path) elif os.path.isdir(file_path): rm_dir_files(file_path) print 'remove dir %...
ERROR %s' % e pass # Create your tests here. class DestinationCase(TestCase): def setUp(self): o = Origin.objects.create( name = 'Guadalupe', plan = 'blablablablabla' ) self.user = User.objects.create( username='Guadalu...
dominicneeraj/Technex_api
bell/admin.py
Python
mit
308
0.032468
from django.contrib import admin from bell.mo
dels import * class CityAdmin(admin.ModelAdmin): list_display = ['name'] admin.site.register(City,CityAdmin) admin.site.register(Restra) class DealAdmin(admin
.ModelAdmin): list_display = ['id','restra_name'] admin.site.register(Deal,DealAdmin)
OCA/l10n-italy
l10n_it_fatturapa_in/models/__init__.py
Python
agpl-3.0
91
0
fr
om . import attachment from . import account from . import partner from . import company
synergeticsedx/deployment-wipro
openedx/core/djangoapps/cors_csrf/views.py
Python
agpl-3.0
2,496
0.000801
"""Views for enabling cross-domain requests. """ import logging import json from django.conf import settings from django.views.decorators.cache import cache_page from django.http import HttpResponseNotFound from edxmako.shortcuts import render_to_response from .models import XDomainProxyConfiguration log = logging.g...
) XDOMAIN_PROXY_CACHE_TIMEOUT = getattr(settings, 'XDOMAIN_PROXY_CACHE_TIMEOUT', 60 * 15) @cache_page(XDOMAIN_PROXY_C
ACHE_TIMEOUT) def xdomain_proxy(request): # pylint: disable=unused-argument """Serve the xdomain proxy page. Internet Explorer 9 does not send cookie information with CORS, which means we can't make cross-domain POST requests that require authentication (for example, from the course details page o...
apiaas/gae-search
src/api/urls.py
Python
gpl-3.0
350
0.008571
from django.conf.urls import patterns, url from . import views url
patterns = patterns('',
url(r'^endpoints/$', views.endpoint_list, name='endpoint_list'), url(r'^endpoints/(?P<path>[^?#]+)/$', views.endpoint_details, name='endpoint_details'), url(r'^api/(?P<path>[^?#]+)/$', views.application_endpoint, name='application_endpoint'), )
enigmampc/catalyst
catalyst/pipeline/factors/factor.py
Python
apache-2.0
58,406
0
""" factor.py """ from functools import wraps from operator import attrgetter from numbers import Number from math import ceil from numpy import empty_like, inf, nan, where from scipy.stats import rankdata from catalyst.errors import BadPercentileBounds, UnknownRankMethod from catalyst.lib.normalize import naive_grou...
result of `left <op> right`. """ if is_comparison(op): if left != right: raise TypeError(
"Don't know how to compute {left} {op} {right}.\n" "Comparisons are only supported between Factors of equal " "dtypes.".format(left=left, op=op, right=right) ) return bool_dtype elif left != float64_dtype or right != float64_dtype: raise ...
ul-fmf/projekt-tomo
web/courses/models.py
Python
agpl-3.0
20,320
0.002805
from django.db import models from django.db.models import Count from django.utils.translation import ugettext_lazy as _ from django.template.defaultfilters import slugify from django.template.loader import render_to_string from users.models import User from utils.models import OrderWithRespectToMixin from taggit.manage...
stu
dent(self, user): enrollment = StudentEnrollment.objects.get(course=self, user=user) enrollment.delete() def promote_to_teacher(self, user): self.unenroll_student(user) self.teachers.add(user) def demote_to_student(self, user): self.enroll_student(user) self.tea...
vpv11110000/pyss
setup.py
Python
mit
533
0.005629
# -*- coding: utf-8 -*- try:
from setuptools import setup except ImportError: from distutils.core import setup from setuptools import find_packages from os.path import join, dirname import pyss import unittest setup( name='pyss', version=pyss.__version__, packages=find_packages(), long_description=open(join(dirname(__fi...
over_tests', )
AngelTerrones/Algol
Core/regfile.py
Python
mit
2,952
0
#!/usr/bin/env python # Copyright (c) 2015 Angel Terrones (<angelterrones@gmail.com>) # # 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 r...
ss RFWritePort: """ Defines the RF's write IO port. :ivar wa: Write address :ivar we: Write enable :ivar wd: Write data """ def __init__(self): """ Initializes the IO ports. """ self.wa = Signal(modbv(0)[5:]) self.we = Signal(False) self.wd = ...
egisters, with the register 0 hardwired to zero. :param clk: System clock :param portA: IO bundle (read port) :param portB: IO bundle (read port) :param writePort: IO bundle (write port) """ _registers = [Signal(modbv(0)[32:]) for ii in range(0, 32)] @always_comb def read...
almarklein/scikit-image
skimage/util/shape.py
Python
bsd-3-clause
7,382
0.000135
__all__ = ['view_as_blocks', 'view_as_windows'] import numpy as np from numpy.lib.stride_tricks import as_strided def view_as_blocks(arr_in, block_shape): """Block view of the input n-dimensional array (using re-striding). Blocks are non-overlapping views of the input array. Parameters ---------- ...
[[[76, 77], [82, 83]]]]) """ # -- basic checks on arguments if not isinstance(block_shape, tuple): raise TypeError('block needs to be a tuple') block_shape = np.array(block_shape) if (block_shape <= 0).any(): raise ValueError("'block_shape' elements must be str...
"as 'arr_in.shape'") arr_shape = np.array(arr_in.shape) if (arr_shape % block_shape).sum() != 0: raise ValueError("'block_shape' is not compatible with 'arr_in'") # -- restride the array to build the block view arr_in = np.ascontiguousarray(arr_in) new_shape = tuple(arr_s...
StephDC/MiniBioKit
bioChemData/protein.py
Python
gpl-3.0
1,344
0.019345
from . import sqldb class aminoAcid(): def __init__(self,abbr1,abbr3,name): self.abbr3 = abbr3 self.abbr1 = abbr1 self.name = name def __str__(self): return self.name def __repr__(self): return self.name def getOne(self): return self.abbr1 def getThree...
ass aminoAcidDB(): def __init__(self): self.db = sqldb.sqliteDB('bioChemData/data.sql','protein') def getAA3(self,abbr3): abbr1 = self.db.getItem(abbr3,'one') name = self.db.getItem(abbr3,'name') return aminoAcid(abbr1,abbr3,name) class translateDB(): def __init__(self): ...
ta/data.sql','translate') def getAA3(self,codon): return self.db.getItem(codon,'protein') def codonTranslate(codon,codonDB,aaDB): return aaDB.getAA3(codonDB.getAA3(codon)) def nucleotideTranslation(posStrand): pointer = 0 result = '' lastAA = 'M' adb = aminoAcidDB() cdb = translate...
doclements/pywps-4
pywps/storage.py
Python
mit
2,563
0.002341
from abc import ABCMeta, abstractmethod, abstractproperty import os class STORE_TYPE: PATH = 0 # TODO: cover with tests class StorageAbstract(object): """Data storage abstract class """ __metaclass__ = ABCMeta @abstractmethod def store(self): """ :param output: of type IOHandl...
... tiff_file.close()
... return 'file.tiff' >>> fake_out = FakeOutput() >>> (type, path, url) = store.store(fake_out) >>> type == STORE_TYPE.PATH True """ def __init__(self, config): """ :param config: storage configuration object """ self.target = config.get('FileStorage...
NeCTAR-RC/nectar-images
community_image_tests/setup.py
Python
apache-2.0
1,054
0
# Copyright (c) 2016, Monash e-Research Centre # (Monash University, Australia) # 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...
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specif
ic language governing permissions and limitations # under the License. import setuptools # In python < 2.7.4, a lazy loading of package `pbr` will break # setuptools if some other modules registered functions in `atexit`. # solution from: http://bugs.python.org/issue15881#msg170215 try: import multiprocessing ...